From 72c7cce23647d729c94f1f1d2091b4e3466e751e Mon Sep 17 00:00:00 2001 From: Brevno78 <168448563+Brevno78@users.noreply.github.com> Date: Sat, 18 May 2024 21:47:15 +0300 Subject: [PATCH 1/4] fix to pep8 --- .pre-commit-config.yaml | 223 +++++++++++ .../Update a binary file2.py | 2 +- ...on 1 (elegible for remedial, top marks).py | 3 +- 1 File handle/File handle text/counter.py | 9 +- ...e handle 12 length of line in text file.py | 17 +- 1 File handle/File handle text/happy.txt | 2 +- .../input,output and error streams.py | 9 +- 1 File handle/File handle text/question 2.py | 21 +- 1 File handle/File handle text/question 5.py | 22 +- 1 File handle/File handle text/question 6.py | 12 +- 1 File handle/File handle text/question3.py | 16 +- .../special symbol after word.py | 2 +- 1 File handle/File handle text/story.txt | 4 +- AI Game/Tic-Tac-Toe-AI/tictactoe.py | 89 +++-- Armstrong_number | 2 +- Armstrong_number.py | 26 +- Assembler/GUIDE.txt | 32 +- Assembler/README.md | 10 +- Assembler/assembler.py | 49 ++- Assembler/examples/code.txt | 8 +- Assembler/examples/code2.txt | 2 +- Assembler/examples/code3.txt | 2 +- Assembler/examples/code4.txt | 1 - Assembler/examples/test.txt | 2 +- Automated Scheduled Call Reminders/caller.py | 8 +- .../requirements.txt | 16 +- .../schedular.py | 2 - Bank Application .ipynb | 261 +++++++------ Battery_notifier.py | 6 +- Binary_search.py | 7 +- BlackJack_game/blackjack.py | 8 +- BlackJack_game/blackjack_rr.py | 8 +- BlackJack_game/blackjack_simulate.py | 21 +- BlackJack_game/requirements.txt | 2 +- BoardGame-CLI/python.py | 29 +- BoardGame-CLI/snakeLadder.py | 42 +- BoardGame-CLI/uno.py | 49 ++- BruteForce.py | 5 +- CONTRIBUTING.md | 8 +- CRC/crc.py | 2 +- Caesar Cipher Encoder & Decoder.py | 8 +- Calculate resistance.py | 14 +- Calendar (GUI).py | 3 +- Cat/cat.py | 5 + Cat/text_b.txt | 2 +- Checker_game_by_dz/first.py | 10 +- Checker_game_by_dz/modules/checker.py | 3 +- Checker_game_by_dz/modules/checker_board.py | 38 +- Checker_game_by_dz/modules/pieces.py | 3 +- Chrome Dino Automater.py | 6 +- Classification_human_or_horse.py | 10 +- CliYoutubeDownloader.py | 21 +- CliYoutubeDownloader/CliYoutubeDownloader.py | 21 +- Colors/pixel_sort.py | 25 +- Compression_Analysis/PSNR.py | 2 +- CountMillionCharacter.py | 11 +- CountMillionCharacters-2.0.py | 2 +- Crack_password.py | 34 +- Credit_Card_Validator.py | 2 +- Cricket_score.py | 3 +- Day_of_week.py | 5 +- Decimal_To_Binary.py | 1 + Divide Operator.py | 2 +- Downloaded Files Organizer/obs.py | 7 +- Downloaded Files Organizer/readme.md | 20 +- Downloaded Files Organizer/requirements.txt | 4 +- Droplistmenu/GamesCalender.py | 32 +- Electronics_Algorithms/resistance.py | 117 +++--- Emoji Dictionary/emoji_dictionary.py | 21 +- Emoji Dictionary/requirements.txt | 4 +- Encryption using base64.py | 13 +- EncryptionTool.py | 5 +- Exception_Handling_in_Python.py | 4 +- .../Parent/Child1/Text_Child1.txt | 2 +- .../Parent/Child2/Text_Child2.txt | 2 +- .../Parent/Child3/Text_Child3.txt | 2 +- Extract-Table-from-pdf-txt-docx/main.py | 3 +- ExtractThumbnailFromVideo/README.md | 4 +- .../extract_thumbnail_from_video.py | 24 +- FIND FACTORIAL OF A NUMBER.py | 25 +- FTP in python | 86 ++--- .../face_recofnation_first.py | 2 +- .../mask_detection.py | 6 +- FibonacciNumbersWithGenerators.py | 13 +- ...er of any city using openweathermap API.py | 136 +++---- FindingResolutionOfAnImage.py | 29 +- FizzBuzz.py | 1 - Flappy Bird - created with tkinter/.gitignore | 2 +- .../Background.py | 39 +- Flappy Bird - created with tkinter/Bird.py | 10 +- .../Flappy Bird.py | 13 +- Flappy Bird - created with tkinter/README.md | 2 +- .../Settings.py | 7 +- Flappy Bird - created with tkinter/Tubes.py | 44 ++- Generate a random number between 0 to 9.py | 2 +- Google_Image_Downloader/create_dir.py | 11 +- Google_Image_Downloader/image_grapper.py | 22 +- Grocery calculator.py | 64 ++-- GroupSms_Way2.py | 18 +- Guessing_Game.py | 4 +- .../hand_motion_recognizer.py | 44 ++- Hand-Motion-Detection/requirements.txt | 2 +- HangMan Game | 12 +- Hangman.py | 7 +- Hotel-Management.py | 64 ++-- ImageDownloader/img_downloader.py | 9 +- Image_resize.py | 29 +- Industrial_developed_hangman/Makefile | 2 +- Industrial_developed_hangman/README.md | 2 +- .../src/hangman/main.py | 66 ++-- .../tests/test_hangman/test_main.py | 67 ++-- Infix_to_Postfix.py | 1 + JARVIS/JARVIS_2.0.py | 66 ++-- JARVIS/README.md | 2 +- JARVIS/requirements.txt | 12 +- Job_scheduling.py | 6 +- JustDialScrapperGUI/Justdial Scrapper GUI.py | 32 +- Key_Binding/key_binding.py | 2 + Kilometerstomile.py | 2 +- Koch Curve/README.txt | 10 +- LETTER GUESSER | 4 +- Laundary System/README.md | 6 +- Laundary System/code.py | 144 +++---- Letter_Counter.py | 20 +- List.py | 10 +- ML House Prediction.ipynb | 90 +++-- Mad Libs Generator.py | 28 +- Merge_linked_list.py | 1 + Model Usage.ipynb | 27 +- Monitor Apache | 14 +- Mp3_media_player.py | 5 +- Multiply.py | 23 +- MySQL_Databses.py | 5 +- News_App/Newsapp.py | 26 +- News_App/patterns.py | 233 ++++++------ News_App/requirements.txt | 8 +- Number reverse.py | 14 +- Organise.py | 16 +- PDF/demerge_pdfs.py | 16 +- PDF/header_footer.py | 3 +- PDF/images.py | 2 +- PDF/requirements.txt | 2 +- PDFtoAudiobook.py | 7 +- PORT SCANNER.PY | 14 +- Palindrome_Checker.py | 3 +- Password Generator/pass_gen.py | 14 +- Password Generator/requirements.txt | 2 +- Password Generator/requirements_new.txt | 1 - Patterns/half triangle pattern.py | 55 +-- Patterns/pattern2.py | 21 +- Patterns/pattern5.py | 17 +- Patterns/pattern6.py | 13 +- Patterns/patterns.py | 17 +- PingPong/Ball.py | 16 +- PingPong/Slab.py | 32 +- PingPong/main.py | 15 +- PongPong_Game/pong/__init__.py | 1 - PongPong_Game/pong/ball.py | 7 +- PongPong_Game/pong/load.py | 37 +- PongPong_Game/pong/paddle.py | 7 +- PongPong_Game/pong/rectangle.py | 2 +- PongPong_Game/pongpong.py | 13 +- ...everse Linked List( Recursive solution).py | 5 +- Python Distance.py | 6 +- ...uct of unique prime factors of a number.py | 54 +-- Python Program for Tower of Hanoi.py | 20 +- Python Program for factorial of a number | 40 +- ...ogram to Count the Number of Each Vowel.py | 10 +- ...play Fibonacci Sequence Using Recursion.py | 17 +- Python Program to Find LCM.py | 24 +- Python Program to Merge Mails.py | 7 +- ...Program to Print the Fibonacci sequence.py | 22 +- ...am to Remove Punctuations from a String.py | 6 +- Python Program to Reverse a linked list.py | 108 +++--- ...ogram to Sort Words in Alphabetic Order.py | 16 +- Python Program to Transpose a Matrix.py | 22 +- Python-Array-Equilibrium-Index.py | 36 +- Python_swapping.py | 38 +- QR_code_generator/qrcode.py | 3 +- QuadraticCalc.py | 2 +- Random Password Generator.py | 15 +- RandomDice.py | 1 + RandomNumberGame.py | 8 +- Randomnumber.py | 2 +- ReadFromCSV.py | 5 +- Recursion Visulaizer/recursionVisualizer.py | 2 +- SOUNDEX.py | 3 - Search_Engine/README.md | 2 +- Search_Engine/backend.py | 46 ++- Search_Engine/frontend.py | 7 +- Search_Engine/test_data.py | 4 +- Secret message generator GUI by tkinter.py | 10 +- Shortest Distance between Two Lines.py | 5 +- Snake_water_gun/main.py | 8 +- Sorting Algorithims/heapsort_linkedlist.py | 2 + Sorting Algorithims/mergesort_linkedlist.py | 15 +- Sorting Algorithims/quicksort_linkedlist.py | 14 +- Sorting Algorithms/Bubble_sort.py | 2 +- Sorting Algorithms/Counting-sort.py | 1 - Sorting Algorithms/Heap sort.py | 1 + Sorting Algorithms/Iterative Merge Sort.py | 1 + Sorting Algorithms/Tim_sort.py | 13 +- String_Palindrome.py | 6 +- Strings.py | 4 +- Sum of digits of a number.py | 38 +- TIC_TAC_TOE/index.py | 12 +- TTS.py | 2 +- TaskManager.py | 27 +- TaskPlanner.py | 27 +- Test-Case-Generator/test_case.py | 174 ++++++--- ThirdAI/Terms and Conditions/Readme.md | 1 - ThirdAI/Terms and Conditions/ThirdAI.py | 7 +- ThirdAI/Terms and Conditions/TkinterUI.py | 69 +++- TicTacToe.py | 167 ++++---- Tic_Tac_Toe.py | 3 +- Timetable_Operations.py | 3 +- ...nd the largest number between 3 numbers.py | 5 +- Translator/translator.py | 7 +- Triplets with zero sum/Readme.md | 2 +- .../find_Triplets_with_zero_sum.py | 10 +- .../audiobook_gen.py | 4 +- Turtle_Star.py | 20 +- Tweet Pre-Processing.py | 10 +- UI-Apps/README.md | 2 +- UI-Apps/clock.py | 6 +- Untitled.ipynb | 35 +- Voice Command Calculator.py | 38 +- VoiceAssistant/DOCUMENTATION.md | 21 +- VoiceAssistant/PRE-REQUISITES.md | 2 +- .../Project_Basic_struct/TextTospeech.py | 14 +- .../VoiceAssistant_main.py | 52 ++- .../Project_Basic_struct/dictator.py | 23 +- VoiceAssistant/Project_Basic_struct/menu.py | 10 +- .../Project_Basic_struct/speakListen.py | 130 ++++--- .../Project_Basic_struct/speechtotext.py | 5 +- .../Project_Basic_struct/textRead.py | 264 +++++++------ .../Project_Basic_struct/websiteWork.py | 38 +- VoiceAssistant/README.md | 22 +- VoiceRepeater/__main__.py | 6 +- Weather Scrapper/weather.py | 55 ++- WeatherGUI.py | 6 +- Web Socket.py | 15 +- Web_Scraper.py | 3 +- Webbrowser/tk-browser.py | 17 +- Wikipdedia/flask_rendering.py | 17 +- Wikipdedia/main.py | 6 +- Wikipdedia/practice_beautifulsoap.py | 26 +- Wikipdedia/static/js/output.js | 1 - WikipediaModule.py | 5 +- Windows_Wallpaper_Script/ReadMe.md | 2 +- Windows_Wallpaper_Script/wallpaper_extract.py | 2 +- Wordle/wordle.py | 14 +- XORcipher/README.md | 2 +- XORcipher/XOR_cipher.py | 6 +- Youtube Downloader With GUI/main.py | 9 +- advanced_calculator.py | 11 +- agecalculator.py | 57 ++- alexa_news_headlines.py | 2 +- armstrongnumber.py | 2 +- async_downloader/async_downloader.py | 22 +- automail.py | 31 +- backup_automater_services.py | 18 +- bank_managment_system/backend.py | 18 +- bank_managment_system/frontend.py | 159 ++++++-- batch_file_rename.py | 14 +- binary search.py | 44 ++- binarySTree isTrue_YashV1729.Java | 96 ++--- binary_search_trees/delete_a_node_in_bst.py | 67 ++-- binary_search_trees/inorder_successor.py | 18 +- binary_search_trees/inorder_traversal.py | 12 +- binary_search_trees/insert_in_bst.py | 19 +- binary_search_trees/main.py | 50 ++- binary_search_trees/mirror_a_bst.py | 12 +- binary_search_trees/print_in_range.py | 41 +- binary_search_trees/root_to_leaf_paths.py | 10 +- binary_search_trees/search_in_bst.py | 10 +- binary_search_trees/tree_node.py | 2 +- binary_search_trees/validate_bst.py | 14 +- binod.py | 4 +- birthdays.py | 28 +- blackJackGUI.py | 4 +- blackjack.py | 10 +- bodymass.py | 18 +- bookstore_manangement_system.py | 26 +- brickout-game/README.md | 7 +- brickout-game/brickout-game.py | 19 +- calc_area.py | 6 +- calculator-gui.py | 21 +- calculator.py | 9 +- cartesian_product.py | 5 +- changemac.py | 2 +- chaos.py | 2 +- ...k if a number positive , negative or zero | 1 - ...the string is Symmetrical or Palindrome.py | 86 +++-- check_file.py | 8 +- check_for_sqlite_files.py | 9 +- chicks_n_rabs.py | 2 +- classicIndianCardMatch.py | 10 +- cli_master/cli_master.py | 2 - cli_master/validation_page.py | 16 +- cloning_a_list.py | 31 +- colorma_as_color.py | 6 +- colour spiral.py | 42 +- communication/file.py | 3 +- communication/pipe.py | 4 - communication/socket_conn.py | 4 - convert celsius into fahrenheit.py | 8 +- convert_time.py | 2 - count the numbers of two vovels.py | 10 +- create password validity in python.py | 43 ++- create_dir_if_not_there.py | 6 +- cricket_news.py | 4 +- currency converter/country.txt | 2 +- currency converter/main.py | 13 +- daily_checks.py | 12 +- daily_horoscope.py | 2 +- days_from_date.py | 24 +- decimal to binary.py | 2 +- depreciated_programs/corona_cases.py | 6 +- dialogs/messagebox.py | 5 +- dice.py | 2 +- diceV2_dynamic.py | 6 +- dice_rolling_simulator.py | 2 +- diction.py | 3 +- different model output | 2 +- digital_clock.py | 9 +- dir_test.py | 1 - divisors_of_a_number.py | 24 +- email id dictionary/README.md | 2 +- email id dictionary/mbox-short.txt | 56 +-- encrypter-decrypter-gui.py | 40 +- encrypter_decrypter_gui.py | 40 +- encryptsys.py | 2 +- env_check.py | 11 +- environment.yml | Bin 22572 -> 22573 bytes equations.py | 2 +- facebook id hack.py | 11 +- facebook-autologin-bot.py | 5 +- factorial_perm_comp.py | 6 +- fastapi.py | 7 +- fibonici series.py | 22 +- file_ext_changer.py | 68 ++-- fileinfo.py | 15 +- find_cube_root.py | 4 +- find_prime.py | 11 +- finding LCM.py | 25 +- flappyBird_pygame/flappy_bird.py | 5 +- floodfill/floodfill.py | 14 +- folder_size.py | 6 +- framework/quo.md | 360 ++++++++---------- friday.py | 3 +- ftp_send_receive.py | 2 +- game_of_life/05_mixed_sorting.py | 4 +- game_of_life/game_o_life.py | 9 +- gcd.py | 3 +- generate_permutations.py | 19 +- get_crypto_price.py | 8 +- get_likes_on_FB.py | 4 +- get_youtube_view.py | 2 +- googlemaps.py | 3 +- googleweb.py | 78 ++-- greaterno.py | 12 +- gstin_scraper.py | 48 ++- gui_calculator.py | 19 +- happy_num.py | 87 +++-- helloworld.py | 2 +- housing.names | 15 +- ...d three numbers and find type in python.py | 12 +- ...display the fibonacci sequence up to n-.py | 22 +- image2pdf/image2pdf.py | 83 ++-- index.html | 1 - inheritance_YahV1729.python | 54 +-- .../instagram_image_scrapping.ipynb | 76 ++-- insta_image_saving/instructions.txt | 2 +- insta_monitering/insta_api.py | 29 +- insta_monitering/insta_datafetcher.py | 23 +- internet_connection_py3.py | 5 +- invisible_clock.py | 15 +- largestno.py | 6 +- lcm.py | 50 +-- leap year.py | 16 +- linear search.py | 19 +- linear-algebra-python/README.md | 114 +++--- linear-algebra-python/src/lib.py | 9 +- linear-algebra-python/src/tests.py | 3 +- linear_search.py | 2 +- loader.py | 8 +- .../local_weighted_learning.py | 18 +- login.py | 1 + logs.py | 4 +- magic8ball.py | 5 +- magic_8_ball.py | 5 +- mapit.py | 5 +- meme_maker.py | 7 +- memorygame.py | 1 + merge.py | 6 +- mobilePhoneSpecsScrapper.py | 13 +- multiplication_table.py | 12 +- nDigitNumberCombinations.py | 2 +- nasa_apod_with_requests/README.md | 2 +- nasa_apod_with_requests/run.py | 5 +- new.py | 7 +- new_pattern.py | 29 +- new_script.py | 4 +- news_articles__scraper.py | 5 +- .../hello_world_incre_decre_(!).py | 8 +- .../simple_calc_GUI/simple_calculator_GUI.py | 3 +- .../to_sort/JARVIS_python_bot/JARVIS_2.0.py | 28 +- .../to_sort/JARVIS_python_bot/README.md | 2 +- .../JARVIS_python_bot/requirements.txt | 16 +- nitkarshchourasia/to_sort/determine_sign.py | 2 +- .../django_projects/ToDo_webapp/manage.py | 2 +- .../django_projects/ToDo_webapp/todo/admin.py | 1 + .../django_projects/ToDo_webapp/todo/forms.py | 1 + .../todo/migrations/0001_initial.py | 2 +- .../ToDo_webapp/todo/models.py | 1 + .../todo/templates/todo/index.html | 2 +- .../django_projects/ToDo_webapp/todo/views.py | 8 +- .../ToDo_webapp/todo_site/settings.py | 2 +- .../ToDo_webapp/todo_site/urls.py | 1 + .../to_sort/one_rep_max_calculator/README.md | 2 +- .../pdf_to_docx_converter/requirements.txt | 4 +- nmap_scan.py | 5 +- nodepad/README.md | 10 +- nodepad/notepad.py | 3 +- nodepad/src/notepad.tcl | 93 +++-- notepad/notepad_support.py | 6 +- nslookup_check.py | 2 +- num-py.py | 3 +- number guessing.py | 21 +- numberguessinggame/index.py | 8 +- numeric_password_cracker.py | 8 +- oneeven.py | 2 +- other_pepole/get_ip_gui | 41 +- pan.py | 12 +- password_checker.py | 41 +- password_cracker.py | 4 +- password_manager.py | 6 +- .../animal_name_scraiper.py | 12 +- .../passwordGenerator.py | 1 + personal_translator.py | 4 +- ph_email.py | 2 +- ping_servers.py | 23 +- ping_subnet.py | 10 +- polygon.py | 3 +- portscanner.py | 2 - power_of_n.py | 6 +- powerdown_startup.py | 8 +- powers of 2.py | 6 +- powerup_checks.py | 33 +- primelib/Prime.txt | 2 +- primelib/README | 16 +- primelib/primelib.py | 10 +- print hello world.py | 2 +- prison_break_scrapper.py | 3 +- psunotify.py | 10 +- puttylogs.py | 9 +- pyauto.py | 2 +- python Space Invader game.py | 59 +-- ...finding square root for positive number.py | 8 +- python_sms.py | 10 +- python_webscraper.py | 9 +- quiz_game.py | 57 +-- quote.py | 3 +- random-sentences.py | 2 +- random_file_move.py | 7 +- randomloadingmessage.py | 2 +- rangoli.py | 4 +- rearrange-files/rearrange-files.py | 2 +- recursiveStrings.py | 22 +- recyclebin.py | 5 +- remove a character from a file and rewrite.py | 34 +- replacetext.py | 1 - requirements.txt | 192 +++++----- requirements_with_versions.txt | 192 +++++----- reversed_pattern3.py | 19 +- rock_paper_scissor_game.py | 3 - russian_roulette.py | 13 +- scrap_file.py | 4 +- script_count.py | 23 +- script_listing.py | 15 +- send_message_automation/README.md | 2 +- send_message_automation/author_name_NC.txt | 5 +- send_message_automation/message_automation.py | 3 +- sendemail.py | 11 +- sensors_information.py | 9 +- serial_scanner.py | 3 +- sierpinski_triangle.py | 11 +- simulate_memory_cpu.py | 30 +- singly_linked_list.py | 13 +- slack_message.py | 2 - snake.py | 10 +- snake_case_renamer_depth_one.py | 16 +- socket-programming/README.md | 6 +- socket-programming/server.py | 2 +- spotifyAccount.py | 6 +- sqlite_check.py | 4 +- sqlite_table_check.py | 7 +- stack.py | 1 + stackF_Harsh2255.py | 1 + stone_paper_scissor/main.py | 4 +- sum_of_digits_of_a_number.py | 3 + swap.py | 6 +- swapping of two numbers | 1 - test.cpp | 1 - text-to-audio/README.md | 5 - text-to-audio/main.py | 3 +- text-to-audio/requirements.txt | 2 +- text-to-audio/text-file-to-audio.py | 5 +- text_file_replace.py | 4 +- text_to_audio/README.md | 4 +- text_to_audio/author_name_NC.txt | 5 +- text_to_audio/main.py | 18 +- text_to_audio/special_file.txt | 20 +- text_to_pig_latin.py | 8 +- tf_idf_generator.py | 31 +- .../Nose.xml | 8 +- .../mustache-add-on-face.py | 5 +- .../utils.py | 2 +- thread_signal.py | 2 - tic-tac-toe.py | 1 + tic_tak_toe.py | 6 +- time_delta.py | 21 +- translation_of_sizes_of_underwear_RU.py | 9 +- triangles.py | 2 +- tuple.py | 18 +- turtal game.ipynb | 2 +- turtle module | 30 +- turtle_shapes_made.py | 5 +- tweeter.py | 2 +- twitter_post_scraper.py | 9 +- ultimate-phone-book/contacts.py | 39 +- ultimate-phone-book/readme.md | 14 +- videodownloder.py | 43 ++- vowel remover function.py | 2 + whatsapp-monitor.py | 17 +- whatsapp-schedule.py | 3 +- wifi hack by brutefore.py | 106 +++--- wiki/requirements.txt | 2 +- wiki/wiki.py | 33 +- wiki_random.py | 8 +- wikipedia.py | 4 +- work_connect.py | 15 +- write_excel_file.py | 2 +- youtubedownloader.py | 56 +-- 545 files changed, 5884 insertions(+), 4609 deletions(-) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000000..9e4510a69c3 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,223 @@ +repos: + - repo: https://github.com/asottile/add-trailing-comma + rev: v3.1.0 + hooks: + - id: add-trailing-comma + - repo: https://github.com/psf/black.git + rev: 24.4.0 + hooks: + - id: black + - repo: https://github.com/nbQA-dev/nbQA + rev: 1.8.5 + hooks: + - id: nbqa-black + name: nbqa-black + description: Run 'black' on a Jupyter Notebook + entry: nbqa black + language: python + require_serial: true + types_or: [jupyter, markdown] + additional_dependencies: [black] + - repo: https://github.com/asottile/pyupgrade + rev: v3.15.2 + hooks: + - id: pyupgrade + args: [--py39-plus] + - repo: https://github.com/pycqa/isort + rev: 5.13.2 + hooks: + - id: isort + - repo: https://github.com/adamchainz/blacken-docs + rev: 1.16.0 + hooks: + - id: blacken-docs + additional_dependencies: + - black==24.2.0 + - repo: https://github.com/nbQA-dev/nbQA + rev: 1.8.5 + hooks: + - id: nbqa-pyupgrade + name: nbqa-pyupgrade + description: Run 'pyupgrade' on a Jupyter Notebook + entry: nbqa pyupgrade + language: python + require_serial: true + types_or: [jupyter, markdown] + additional_dependencies: [pyupgrade] + - id: nbqa-isort + name: nbqa-isort + description: Run 'isort' on a Jupyter Notebook + entry: nbqa isort + language: python + require_serial: true + types_or: [jupyter, markdown] + additional_dependencies: [isort] + + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: debug-statements + - id: name-tests-test + - id: requirements-txt-fixer + + - repo: https://github.com/codespell-project/codespell + rev: v2.2.6 + hooks: + - id: codespell + additional_dependencies: + - tomli + + - repo: https://github.com/nbQA-dev/nbQA + rev: 1.8.5 + hooks: + - id: nbqa-flake8 + args: ["--ignore=E501,E712,W291,F632,E203"] + name: nbqa-flake8 + description: Run 'flake8' on a Jupyter Notebook + entry: nbqa flake8 + language: python + require_serial: true + types_or: [jupyter, markdown] + additional_dependencies: + - flake8-variables-names + - pep8-naming + - flake8-functions-names + + - repo: https://github.com/PyCQA/flake8 + rev: 7.0.0 + hooks: + - id: flake8 + args: ["--ignore=E501,E712,W291,F632,E203"] + additional_dependencies: + - flake8-variables-names + - pep8-naming + - flake8-functions-names + + - repo: https://github.com/nbQA-dev/nbQA + rev: 1.8.5 + hooks: + - id: nbqa-mypy + name: nbqa-mypy + description: Run 'mypy' on a Jupyter Notebook + entry: nbqa mypy + language: python + require_serial: true + types_or: [jupyter, markdown] + additional_dependencies: + - mypy + - pandas-stubs + - git+https://github.com/numpy/numpy-stubs + - mypy-extensions + - types-requests + - types-PyYAML + - types-setuptools + + args: + - --cache-dir=/dev/null + - --cache-dir=nul + - --no-incremental + - --explicit-package-bases + - --ignore-missing-imports + - --disallow-untyped-calls + - --disallow-untyped-defs + - --disallow-untyped-decorators + - --strict + - --extra-checks + - --disallow-any-unimported + - --disallow-any-decorated + - --disallow-any-explicit + - --disallow-any-generics + - --disallow-subclassing-any + - --local-partial-types + - --pretty + - --force-uppercase-builtins + - --force-union-syntax + - --warn-unreachable + - --warn-redundant-casts + - --warn-return-any + + + + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v1.9.0 + hooks: + - id: mypy + args: + - --cache-dir=/dev/null + - --cache-dir=nul + - --no-incremental + - --explicit-package-bases + - --ignore-missing-imports + - --disallow-untyped-calls + - --disallow-untyped-defs + - --disallow-untyped-decorators + - --strict + - --extra-checks + - --disallow-any-unimported + - --disallow-any-decorated + - --disallow-any-explicit + - --disallow-any-generics + - --disallow-subclassing-any + - --local-partial-types + - --pretty + - --force-uppercase-builtins + - --force-union-syntax + - --warn-unreachable + - --warn-redundant-casts + - --warn-return-any + + + + additional_dependencies: + - mypy + - pandas-stubs + - git+https://github.com/numpy/numpy-stubs + - mypy-extensions + - types-requests + - types-PyYAML + - types-setuptools + + - repo: https://github.com/nbQA-dev/nbQA + rev: 1.8.5 + hooks: + - id: nbqa-pylint + name: nbqa-pylint + description: Run 'pylint' on a Jupyter Notebook + entry: nbqa pylint + language: python + require_serial: true + types_or: [jupyter, markdown] + additional_dependencies: [pylint] + args: + [ + "--max-line-length=79", + "--const-naming-style=any", + "--disable=E0401,W0104", + ] + + - repo: https://github.com/pre-commit/mirrors-pylint + rev: v2.3.1 + hooks: + - id: pylint + name: pylint + entry: pylint + language: python + types: [python] + args: + [--max-line-length=79, "--const-naming-style=any", "--disable=E0401,W0104"] + additional_dependencies: [pylint] + + - repo: https://github.com/nbQA-dev/nbQA + rev: 1.8.5 + hooks: + - id: nbqa-pydocstyle + name: nbqa-pydocstyle + description: Run 'pydocstyle' on a Jupyter Notebook + entry: nbqa pydocstyle + language: python + require_serial: true + types_or: [jupyter, markdown] + additional_dependencies: [pydocstyle] diff --git a/1 File handle/File handle binary/Update a binary file2.py b/1 File handle/File handle binary/Update a binary file2.py index 88adeef443f..e7b18776a26 100644 --- a/1 File handle/File handle binary/Update a binary file2.py +++ b/1 File handle/File handle binary/Update a binary file2.py @@ -9,7 +9,7 @@ def update(): value = pickle.load(File) found = False roll = int(input("Enter the roll number of the record")) - + for i in value: if roll == i[0]: print(f"current name {i[1]}") diff --git a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py index bf84e9824ec..9dbc7ad327f 100644 --- a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py +++ b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py @@ -6,8 +6,9 @@ Write a function remcount( ) to count the number of students who need remedial class (student who scored less than 40 percent) - + """ + # also find no. of children who got top marks import pickle diff --git a/1 File handle/File handle text/counter.py b/1 File handle/File handle text/counter.py index 1019eeacae8..abbaf293c02 100644 --- a/1 File handle/File handle text/counter.py +++ b/1 File handle/File handle text/counter.py @@ -5,9 +5,10 @@ - Code readability """ + class Counter: - def __init__(self, text:str) -> None: + def __init__(self, text: str) -> None: self.text = text # Define the initial count of the lower and upper case. @@ -16,7 +17,7 @@ def __init__(self, text:str) -> None: self.count() def count(self) -> None: - + for char in self.text: if char.lower(): self.count_lower += 1 @@ -24,7 +25,7 @@ def count(self) -> None: self.count_upper += 1 return (self.count_lower, self.count_upper) - + def get_total_lower(self) -> int: return self.count_lower @@ -32,4 +33,4 @@ def get_total_upper(self) -> int: return self.count_upper def get_total(self) -> int: - return self.count_lower + self.count_upper \ No newline at end of file + return self.count_lower + self.count_upper diff --git a/1 File handle/File handle text/file handle 12 length of line in text file.py b/1 File handle/File handle text/file handle 12 length of line in text file.py index d14ef16a4ea..5495fdec1ee 100644 --- a/1 File handle/File handle text/file handle 12 length of line in text file.py +++ b/1 File handle/File handle text/file handle 12 length of line in text file.py @@ -1,10 +1,11 @@ - import os import time -file_name= input("Enter the file name to create:- ") + +file_name = input("Enter the file name to create:- ") print(file_name) + def write_to_file(file_name): if os.path.exists(file_name): @@ -15,16 +16,17 @@ def write_to_file(file_name): while True: text = input("enter any text to add in the file:- ") - F.write( f"{text}\n" ) + F.write(f"{text}\n") choice = input("Do you want to enter more, y/n").lower() if choice == "n": break - + + def longlines(): - with open(file_name, encoding='utf-8') as F: + with open(file_name, encoding="utf-8") as F: lines = F.readlines() - lines_less_than_50 = list( filter(lambda line: len(line) < 50, lines ) ) + lines_less_than_50 = list(filter(lambda line: len(line) < 50, lines)) if not lines_less_than_50: print("There is no line which is less than 50") @@ -32,7 +34,8 @@ def longlines(): for i in lines_less_than_50: print(i, end="\t") + if __name__ == "__main__": write_to_file(file_name) time.sleep(1) - longlines() \ No newline at end of file + longlines() diff --git a/1 File handle/File handle text/happy.txt b/1 File handle/File handle text/happy.txt index c5ca39434bb..9e776d6e4d7 100644 --- a/1 File handle/File handle text/happy.txt +++ b/1 File handle/File handle text/happy.txt @@ -8,4 +8,4 @@ Take a walk in the park At the end of the day you are more important than anything else. Many moments of happiness are waiting You are amazing! -If you truly believe. \ No newline at end of file +If you truly believe. diff --git a/1 File handle/File handle text/input,output and error streams.py b/1 File handle/File handle text/input,output and error streams.py index cecd268979b..d03bf10fcf6 100644 --- a/1 File handle/File handle text/input,output and error streams.py +++ b/1 File handle/File handle text/input,output and error streams.py @@ -4,13 +4,16 @@ sys.stdout.write("Enter the name of the file") file = sys.stdin.readline() -with open(file.strip(), ) as F: +with open(file.strip()) as F: while True: ch = F.readlines() - for (i) in ch: # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words + for ( + i + ) in ( + ch + ): # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words print(i, end="") else: sys.stderr.write("End of file reached") break - diff --git a/1 File handle/File handle text/question 2.py b/1 File handle/File handle text/question 2.py index cbb84fcd13f..e3d68ba18fc 100644 --- a/1 File handle/File handle text/question 2.py +++ b/1 File handle/File handle text/question 2.py @@ -3,33 +3,32 @@ using read function and display those words, which are less than 4 characters. """ +print("Hey!! You can print the word which are less then 4 characters") -print("Hey!! You can print the word which are less then 4 characters") def display_words(file_path): try: with open(file_path) as F: words = F.read().split() - words_less_than_40 = list( filter(lambda word: len(word) < 4, words) ) + words_less_than_40 = list(filter(lambda word: len(word) < 4, words)) for word in words_less_than_40: print(word) - - return "The total number of the word's count which has less than 4 characters", (len(words_less_than_40)) - + + return ( + "The total number of the word's count which has less than 4 characters", + (len(words_less_than_40)), + ) + except FileNotFoundError: print("File not found") + print("Just need to pass the path of your file..") file_path = input("Please, Enter file path: ") if __name__ == "__main__": - - print(display_words(file_path)) - - - - + print(display_words(file_path)) diff --git a/1 File handle/File handle text/question 5.py b/1 File handle/File handle text/question 5.py index 864520df4cd..4aa3fb069cd 100644 --- a/1 File handle/File handle text/question 5.py +++ b/1 File handle/File handle text/question 5.py @@ -1,16 +1,20 @@ """Write a function in python to count the number of lowercase alphabets present in a text file “happy.txt""" -import time, os +import os +import time + from counter import Counter -print("You will see the count of lowercase, uppercase and total count of alphabets in provided file..") +print( + "You will see the count of lowercase, uppercase and total count of alphabets in provided file.." +) file_path = input("Please, Enter file path: ") if os.path.exists(file_path): - print('The file exists and this is the path:\n',file_path) + print("The file exists and this is the path:\n", file_path) def lowercase(file_path): @@ -18,10 +22,14 @@ def lowercase(file_path): with open(file_path) as F: word_counter = Counter(F.read()) - - print(f"The total number of lower case letters are {word_counter.get_total_lower()}") + + print( + f"The total number of lower case letters are {word_counter.get_total_lower()}" + ) time.sleep(0.5) - print(f"The total number of upper case letters are {word_counter.get_total_upper()}") + print( + f"The total number of upper case letters are {word_counter.get_total_upper()}" + ) time.sleep(0.5) print(f"The total number of letters are {word_counter.get_total()}") time.sleep(0.5) @@ -30,8 +38,6 @@ def lowercase(file_path): print("File is not exist.. Please check AGAIN") - - if __name__ == "__main__": lowercase(file_path) diff --git a/1 File handle/File handle text/question 6.py b/1 File handle/File handle text/question 6.py index a98fe3a7cfb..fe50c0a97e0 100644 --- a/1 File handle/File handle text/question 6.py +++ b/1 File handle/File handle text/question 6.py @@ -3,14 +3,20 @@ from counter import Counter + def lowercase(): with open("happy.txt") as F: word_counter = Counter(F.read()) - - print(f"The total number of lower case letters are {word_counter.get_total_lower()}") - print(f"The total number of upper case letters are {word_counter.get_total_upper()}") + + print( + f"The total number of lower case letters are {word_counter.get_total_lower()}" + ) + print( + f"The total number of upper case letters are {word_counter.get_total_upper()}" + ) print(f"The total number of letters are {word_counter.get_total()}") + if __name__ == "__main__": lowercase() diff --git a/1 File handle/File handle text/question3.py b/1 File handle/File handle text/question3.py index bc05c22561d..f48f900e4d7 100644 --- a/1 File handle/File handle text/question3.py +++ b/1 File handle/File handle text/question3.py @@ -4,13 +4,13 @@ import os import time -file_name= input("Enter the file name to create:- ") + +file_name = input("Enter the file name to create:- ") # step1: print(file_name) - def write_to_file(file_name): if os.path.exists(file_name): @@ -21,11 +21,12 @@ def write_to_file(file_name): while True: text = input("enter any text") - F.write(f"{text}\n") + F.write(f"{text}\n") if input("do you want to enter more, y/n").lower() == "n": break - + + # step2: def check_first_letter(): with open(file_name) as F: @@ -37,10 +38,13 @@ def check_first_letter(): count_i = first_letters.count("i") count_m = first_letters.count("m") - print(f"The total number of sentences starting with I or M are {count_i + count_m}") + print( + f"The total number of sentences starting with I or M are {count_i + count_m}" + ) + if __name__ == "__main__": - + write_to_file(file_name) time.sleep(1) check_first_letter() diff --git a/1 File handle/File handle text/special symbol after word.py b/1 File handle/File handle text/special symbol after word.py index 1e23af6bddb..6e6c5a6fa87 100644 --- a/1 File handle/File handle text/special symbol after word.py +++ b/1 File handle/File handle text/special symbol after word.py @@ -1,4 +1,4 @@ -with open("happy.txt", "r") as F: +with open("happy.txt") as F: # method 1 for i in F.read().split(): print(i, "*", end="") diff --git a/1 File handle/File handle text/story.txt b/1 File handle/File handle text/story.txt index eb78dae4be8..6e48a12f266 100644 --- a/1 File handle/File handle text/story.txt +++ b/1 File handle/File handle text/story.txt @@ -1,5 +1,5 @@ once upon a time there was a king. he was powerful and happy. -he +he all the flowers in his garden were beautiful. -he lived happily ever after. \ No newline at end of file +he lived happily ever after. diff --git a/AI Game/Tic-Tac-Toe-AI/tictactoe.py b/AI Game/Tic-Tac-Toe-AI/tictactoe.py index 6157ff6efb0..0eb2c47b2b9 100644 --- a/AI Game/Tic-Tac-Toe-AI/tictactoe.py +++ b/AI Game/Tic-Tac-Toe-AI/tictactoe.py @@ -1,70 +1,80 @@ -import tkinter as tk #provides a library of basic elements of GUI widgets -from tkinter import messagebox #provides a different set of dialogues that are used to display message boxes import random +import tkinter as tk # provides a library of basic elements of GUI widgets +from tkinter import \ + messagebox # provides a different set of dialogues that are used to display message boxes + def check_winner(board, player): # Check rows, columns, and diagonals for a win for i in range(3): - if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)): + if all(board[i][j] == player for j in range(3)) or all( + board[j][i] == player for j in range(3) + ): return True - if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)): + if all(board[i][i] == player for i in range(3)) or all( + board[i][2 - i] == player for i in range(3) + ): return True return False + def is_board_full(board): - return all(all(cell != ' ' for cell in row) for row in board) + return all(all(cell != " " for cell in row) for row in board) + def minimax(board, depth, is_maximizing): - if check_winner(board, 'X'): + if check_winner(board, "X"): return -1 - if check_winner(board, 'O'): + if check_winner(board, "O"): return 1 - if is_board_full(board): #if game is full, terminate + if is_board_full(board): # if game is full, terminate return 0 - if is_maximizing: #recursive approach that fills board with Os - max_eval = float('-inf') + if is_maximizing: # recursive approach that fills board with Os + max_eval = float("-inf") for i in range(3): for j in range(3): - if board[i][j] == ' ': - board[i][j] = 'O' - eval = minimax(board, depth + 1, False) #recursion - board[i][j] = ' ' + if board[i][j] == " ": + board[i][j] = "O" + eval = minimax(board, depth + 1, False) # recursion + board[i][j] = " " max_eval = max(max_eval, eval) return max_eval - else: #recursive approach that fills board with Xs - min_eval = float('inf') + else: # recursive approach that fills board with Xs + min_eval = float("inf") for i in range(3): for j in range(3): - if board[i][j] == ' ': - board[i][j] = 'X' - eval = minimax(board, depth + 1, True) #recursion - board[i][j] = ' ' + if board[i][j] == " ": + board[i][j] = "X" + eval = minimax(board, depth + 1, True) # recursion + board[i][j] = " " min_eval = min(min_eval, eval) return min_eval -#determines the best move for the current player and returns a tuple representing the position + +# determines the best move for the current player and returns a tuple representing the position def best_move(board): - best_val = float('-inf') + best_val = float("-inf") best_move = None for i in range(3): for j in range(3): - if board[i][j] == ' ': - board[i][j] = 'O' + if board[i][j] == " ": + board[i][j] = "O" move_val = minimax(board, 0, False) - board[i][j] = ' ' + board[i][j] = " " if move_val > best_val: best_val = move_val best_move = (i, j) return best_move + def make_move(row, col): - if board[row][col] == ' ': - board[row][col] = 'X' - buttons[row][col].config(text='X') - if check_winner(board, 'X'): + if board[row][col] == " ": + board[row][col] = "X" + buttons[row][col].config(text="X") + if check_winner(board, "X"): messagebox.showinfo("Tic-Tac-Toe", "You win!") root.quit() elif is_board_full(board): @@ -75,28 +85,37 @@ def make_move(row, col): else: messagebox.showerror("Error", "Invalid move") -#AI's turn to play + +# AI's turn to play def ai_move(): row, col = best_move(board) - board[row][col] = 'O' - buttons[row][col].config(text='O') - if check_winner(board, 'O'): + board[row][col] = "O" + buttons[row][col].config(text="O") + if check_winner(board, "O"): messagebox.showinfo("Tic-Tac-Toe", "AI wins!") root.quit() elif is_board_full(board): messagebox.showinfo("Tic-Tac-Toe", "It's a draw!") root.quit() + root = tk.Tk() root.title("Tic-Tac-Toe") -board = [[' ' for _ in range(3)] for _ in range(3)] +board = [[" " for _ in range(3)] for _ in range(3)] buttons = [] for i in range(3): row_buttons = [] for j in range(3): - button = tk.Button(root, text=' ', font=('normal', 30), width=5, height=2, command=lambda row=i, col=j: make_move(row, col)) + button = tk.Button( + root, + text=" ", + font=("normal", 30), + width=5, + height=2, + command=lambda row=i, col=j: make_move(row, col), + ) button.grid(row=i, column=j) row_buttons.append(button) buttons.append(row_buttons) diff --git a/Armstrong_number b/Armstrong_number index 7dd1b267ea0..60174e919b9 100644 --- a/Armstrong_number +++ b/Armstrong_number @@ -9,5 +9,5 @@ def is_armstrong_number(number): num //= 10 temp += rem ** length return temp == number - + is_armstrong_number(5) diff --git a/Armstrong_number.py b/Armstrong_number.py index 59732994f81..9c73522992c 100644 --- a/Armstrong_number.py +++ b/Armstrong_number.py @@ -1,24 +1,30 @@ """ -In number theory, a narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong) or a plus perfect number), +In number theory, a narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong) or a plus perfect number), in a given number base b, is a number that is the total of its own digits each raised to the power of the number of digits. Source: https://en.wikipedia.org/wiki/Narcissistic_number NOTE: this scripts only works for number in base 10 """ -def is_armstrong_number(number:str): - total:int = 0 - exp:int = len(number) #get the number of digits, this will determinate the exponent - digits:list[int] = [] - for digit in number: digits.append(int(digit)) #get the single digits - for x in digits: total += x ** exp #get the power of each digit and sum it to the total - +def is_armstrong_number(number: str): + total: int = 0 + exp: int = len( + number + ) # get the number of digits, this will determinate the exponent + + digits: list[int] = [] + for digit in number: + digits.append(int(digit)) # get the single digits + for x in digits: + total += x**exp # get the power of each digit and sum it to the total + # display the result if int(number) == total: - print(number,"is an Armstrong number") + print(number, "is an Armstrong number") else: - print(number,"is not an Armstrong number") + print(number, "is not an Armstrong number") + number = input("Enter the number : ") is_armstrong_number(number) diff --git a/Assembler/GUIDE.txt b/Assembler/GUIDE.txt index ccb59b84cf7..6b0fd0fc977 100644 --- a/Assembler/GUIDE.txt +++ b/Assembler/GUIDE.txt @@ -2,13 +2,13 @@ ### Register -In this programming language you can use four registers. +In this programming language you can use four registers. * eax * ebx * ecx * edx -The register **eax** will be standard use for multiplication and division. +The register **eax** will be standard use for multiplication and division. Commands for arithmetic are: * add p0, p1 @@ -23,13 +23,13 @@ The commands **mul** and **div** standard use eax. For instance: mov ecx, 56 sub ecx, 10 mov eax, 4 -int 0x80 +int 0x80 ``` * The first line move the number 56 into register ecx. * The second line subtract 10 from the ecx register. -* The third line move the number 4 into the eax register. This is for the print-function. +* The third line move the number 4 into the eax register. This is for the print-function. * The fourt line call interrupt 0x80, thus the result will print onto console. * The fifth line is a new line. This is important. @@ -37,9 +37,9 @@ int 0x80 ### System-Functions -With the interrupt 0x80 you can use some functionality in your program. +With the interrupt 0x80 you can use some functionality in your program. -EAX | Function +EAX | Function ---- | --------- 1 | exit program. error code in ebx 3 | read input. onto ecx (only float) @@ -67,7 +67,7 @@ int 0x80 ``` -**Important: The arithmetic commands (add, sub) works only with registers or constans. +**Important: The arithmetic commands (add, sub) works only with registers or constans. Therefore we must use the register ebx as a placeholder, above.** @@ -79,8 +79,8 @@ Result of code, above. ### Comments available -Comments begin with ; and ends with a newline. -We noticed a comment, above. +Comments begin with ; and ends with a newline. +We noticed a comment, above. ### Push and Pop @@ -92,14 +92,14 @@ push eax ``` -This line will push the content of register eax onto the stack. +This line will push the content of register eax onto the stack. ``` -pop ecx +pop ecx ``` -This line will pop the content of the top of the stack onto the ecx register. +This line will pop the content of the top of the stack onto the ecx register. ``` push [register] @@ -109,7 +109,7 @@ pop [register] ### Jumps -With the command **cmp** we can compare two register. +With the command **cmp** we can compare two register. ``` cmp r0, r1 @@ -126,7 +126,7 @@ Otherwise the command **jmp** is actively and jumps to label **l2** For instance ``` -l1: +l1: ``` @@ -156,7 +156,7 @@ int 0x80 _double: add ecx, ecx -ret +ret _cube: push eax @@ -172,7 +172,7 @@ ret ``` -A subprogram label begins with a **_** and ends with a colon. See above. +A subprogram label begins with a **_** and ends with a colon. See above. If you call the subprogram you must avoid the colon. diff --git a/Assembler/README.md b/Assembler/README.md index 25cbcafff5d..4b7a9bfadf9 100644 --- a/Assembler/README.md +++ b/Assembler/README.md @@ -1,7 +1,7 @@ # Python-Assembler # WE need A FREE T-SHIRT -This program is a simple assembler-like (intel-syntax) interpreter language. The program is written in python 3. -To start the program you will need to type +This program is a simple assembler-like (intel-syntax) interpreter language. The program is written in python 3. +To start the program you will need to type ``` python assembler.py code.txt ``` @@ -13,16 +13,16 @@ You can find some examples in the directory 'examples'. For instance- -``` +``` $msg db "hello world" -mov ecx, $msg +mov ecx, $msg mov eax, 4 int 0x80 mov eax, 1 mov ebx, 0 int 0x80 -``` +``` Will print onto console diff --git a/Assembler/assembler.py b/Assembler/assembler.py index 24a6840c1d4..a939453f971 100644 --- a/Assembler/assembler.py +++ b/Assembler/assembler.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import sys lines = [] # contains the lines of the file. @@ -73,7 +71,7 @@ def scanner(string): match state: case 0: - + match ch: case "m": # catch mov-command @@ -185,12 +183,12 @@ def scanner(string): state = 47 token += ch - case _:# error case + case _: # error case state = 0 token = "" raise InvalidSyntax() - + case 2: # state 2 match ch: @@ -200,7 +198,7 @@ def scanner(string): state = 3 token += "v" - case _:# error case + case _: # error case state = 0 token = "" @@ -249,7 +247,7 @@ def scanner(string): raise InvalidSyntax() case 6: # state 6 - + if ch.isdigit(): state = 6 @@ -268,7 +266,7 @@ def scanner(string): raise InvalidSyntax() case 7: # state 7 - + match ch: case "d": @@ -276,7 +274,7 @@ def scanner(string): state = 8 token += ch - case _: # error case + case _: # error case state = 0 token = "" @@ -290,7 +288,7 @@ def scanner(string): state = 9 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -318,7 +316,7 @@ def scanner(string): state = 11 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -332,7 +330,7 @@ def scanner(string): state = 12 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -594,7 +592,7 @@ def scanner(string): raise InvalidSyntax() case 29: # state 29 - + match ch: case "m": @@ -806,7 +804,7 @@ def scanner(string): state = 42 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -819,7 +817,7 @@ def scanner(string): state = 43 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -846,7 +844,7 @@ def scanner(string): state = 45 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -859,7 +857,7 @@ def scanner(string): state = 46 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -886,7 +884,7 @@ def scanner(string): state = 48 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -913,7 +911,7 @@ def scanner(string): state = 50 token += ch - case _:# error case + case _: # error case state = 0 token = "" @@ -1081,7 +1079,7 @@ def parser(): zeroFlag = False if eax == 0: zeroFlag = True - + case "ebx": ebx += token.token @@ -1089,7 +1087,7 @@ def parser(): zeroFlag = False if ebx == 0: zeroFlag = True - + case "ecx": ecx += token.token @@ -1097,7 +1095,7 @@ def parser(): zeroFlag = False if ecx == 0: zeroFlag = True - + case "edx": edx += token.token @@ -1301,7 +1299,6 @@ def parser(): # actual comparing zeroFlag = setZeroFlag(token.token, tmpToken.token) - elif token.token == "je": @@ -1448,7 +1445,7 @@ def parser(): return if token.t == "register": - + match token.token: case "eax": eax /= eax @@ -1470,8 +1467,9 @@ def parser(): # increment pointer for fetching next token. pointer += 1 + def setZeroFlag(token, tmpToken): - """ return bool for zero flag based on the regToken """ + """return bool for zero flag based on the regToken""" global eax, ebx, ecx, edx # Register in string @@ -1507,6 +1505,7 @@ def setZeroFlag(token, tmpToken): return zeroFlag + def registerLabels(): """ This function search for labels / subprogram-labels and registers this in the 'jumps' list. diff --git a/Assembler/examples/code.txt b/Assembler/examples/code.txt index 4c82e4c5ad8..a637837c3c2 100644 --- a/Assembler/examples/code.txt +++ b/Assembler/examples/code.txt @@ -1,15 +1,13 @@ -; begin program +; begin program ; variable section $var1 db 56 $var2 db 44 mov ecx, $var1 -push ecx +push ecx mov eax, 3 int 0x80 pop eax add ecx, ebx -add ecx, eax +add ecx, eax mov eax, 4 int 0x80 - - diff --git a/Assembler/examples/code2.txt b/Assembler/examples/code2.txt index 81ed5ec425f..5d749ea8071 100644 --- a/Assembler/examples/code2.txt +++ b/Assembler/examples/code2.txt @@ -1,6 +1,6 @@ $msg db "hello world" -mov ecx, $msg +mov ecx, $msg mov eax, 4 int 0x80 mov eax, 1 diff --git a/Assembler/examples/code3.txt b/Assembler/examples/code3.txt index b4c60cca8ff..af2e502b49d 100644 --- a/Assembler/examples/code3.txt +++ b/Assembler/examples/code3.txt @@ -13,7 +13,7 @@ int 0x80 _double: add ecx, ecx -ret +ret _cube: push eax diff --git a/Assembler/examples/code4.txt b/Assembler/examples/code4.txt index 1e5d8584578..77b24097b01 100644 --- a/Assembler/examples/code4.txt +++ b/Assembler/examples/code4.txt @@ -11,4 +11,3 @@ div ebx mov ecx, eax mov eax, 4 int 0x80 - diff --git a/Assembler/examples/test.txt b/Assembler/examples/test.txt index 6a02962bace..cc68acd4021 100644 --- a/Assembler/examples/test.txt +++ b/Assembler/examples/test.txt @@ -7,4 +7,4 @@ mov ecx, VAR1 mov ebx, $var1 sub ecx, ebx mov eax, 4 -int 0x80 \ No newline at end of file +int 0x80 diff --git a/Automated Scheduled Call Reminders/caller.py b/Automated Scheduled Call Reminders/caller.py index 3082dbb7193..3cc3cb9e091 100644 --- a/Automated Scheduled Call Reminders/caller.py +++ b/Automated Scheduled Call Reminders/caller.py @@ -2,11 +2,12 @@ # every 1 hour using aps scedular # The project can be used to set 5 min before reminder calls to a set of people for doing a particular job import os -from firebase_admin import credentials, firestore, initialize_app -from datetime import datetime, timedelta import time +from datetime import datetime, timedelta from time import gmtime, strftime + import twilio +from firebase_admin import credentials, firestore, initialize_app from twilio.rest import Client # twilio credentials @@ -23,13 +24,14 @@ # Here the collection name is on_call which has documents with fields phone , from (%H:%M:%S time to call the person),date + # gets data from cloud database and calls 5 min prior the time (from time) alloted in the database def search(): calling_time = datetime.now() one_hours_from_now = (calling_time + timedelta(hours=1)).strftime("%H:%M:%S") current_date = str(strftime("%d-%m-%Y", gmtime())) - docs = db.collection(u"on_call").where(u"date", u"==", current_date).stream() + docs = db.collection("on_call").where("date", "==", current_date).stream() list_of_docs = [] for doc in docs: diff --git a/Automated Scheduled Call Reminders/requirements.txt b/Automated Scheduled Call Reminders/requirements.txt index ccfbb3924fa..b1b5b6c4d1f 100644 --- a/Automated Scheduled Call Reminders/requirements.txt +++ b/Automated Scheduled Call Reminders/requirements.txt @@ -1,13 +1,13 @@ BlockingScheduler -search -os -time -gmtime -strftime Client -twilio -datetime -timedelta credentials +datetime firestore +gmtime initialize_app +os +search +strftime +time +timedelta +twilio diff --git a/Automated Scheduled Call Reminders/schedular.py b/Automated Scheduled Call Reminders/schedular.py index 905adad611f..14038f59cd9 100644 --- a/Automated Scheduled Call Reminders/schedular.py +++ b/Automated Scheduled Call Reminders/schedular.py @@ -1,10 +1,8 @@ # schedular code for blocking schedular as we have only 1 process to run from apscheduler.schedulers.blocking import BlockingScheduler - from caller import search - sched = BlockingScheduler() # Schedule job_function to be called every two hours diff --git a/Bank Application .ipynb b/Bank Application .ipynb index f92a6040923..b3ae1bf9db7 100644 --- a/Bank Application .ipynb +++ b/Bank Application .ipynb @@ -6,7 +6,7 @@ "metadata": {}, "outputs": [], "source": [ - "##open project " + "##open project" ] }, { @@ -23,12 +23,12 @@ "outputs": [], "source": [ "data = {\n", - " \"accno\" : [1001, 1002, 1003, 1004, 1005],\n", - " \"name\" : ['vaibhav', 'abhinav', 'aman', 'ashish', 'pramod'],\n", - " \"balance\" : [10000, 12000, 7000, 9000, 10000],\n", - " \"password\" : ['admin', 'adminadmin', 'passwd', '1234567', 'amigo'],\n", - " \"security_check\" : ['2211', '1112', '1009', '1307', '1103']\n", - "}\n" + " \"accno\": [1001, 1002, 1003, 1004, 1005],\n", + " \"name\": [\"vaibhav\", \"abhinav\", \"aman\", \"ashish\", \"pramod\"],\n", + " \"balance\": [10000, 12000, 7000, 9000, 10000],\n", + " \"password\": [\"admin\", \"adminadmin\", \"passwd\", \"1234567\", \"amigo\"],\n", + " \"security_check\": [\"2211\", \"1112\", \"1009\", \"1307\", \"1103\"],\n", + "}" ] }, { @@ -114,122 +114,136 @@ "# import getpass\n", "print(\"-------------------\".center(100))\n", "print(\"| Bank Application |\".center(100))\n", - "print(\"-\"*100)\n", - "while True :\n", + "print(\"-\" * 100)\n", + "while True:\n", " print(\"\\n 1. Login \\n 2. Signup \\n 3. Exit\")\n", " i1 = int(input(\"enter what you want login, signup, exit :\".center(50)))\n", - " #login part\n", + " # login part\n", " if i1 == 1:\n", " print(\"login\".center(90))\n", - " print(\"_\"*100)\n", + " print(\"_\" * 100)\n", " i2 = int(input(\"enter account number : \".center(50)))\n", " if i2 in (data[\"accno\"]):\n", " check = (data[\"accno\"]).index(i2)\n", " i3 = input(\"enter password : \".center(50))\n", - " check2= data[\"password\"].index(i3)\n", - " if check == check2:\n", + " check2 = data[\"password\"].index(i3)\n", + " if check == check2:\n", " while True:\n", - " print(\"\\n 1.check ditails \\n 2. debit \\n 3. credit \\n 4. change password \\n 5. main Manu \")\n", + " print(\n", + " \"\\n 1.check ditails \\n 2. debit \\n 3. credit \\n 4. change password \\n 5. main Manu \"\n", + " )\n", " i4 = int(input(\"enter what you want :\".center(50)))\n", - " #check ditails part\n", + " # check ditails part\n", " if i4 == 1:\n", " print(\"cheak ditails\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your account number --> {data['accno'][check]}\")\n", " print(f\"your name --> {data['name'][check]}\")\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " continue\n", - " #debit part\n", - " elif i4 == 2 :\n", + " # debit part\n", + " elif i4 == 2:\n", " print(\"debit\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " i5 = int(input(\"enter debit amount : \"))\n", - " if 0 < i5 <= data['balance'][check]:\n", - " debit = data['balance'][check]-i5\n", - " data['balance'][check] = debit\n", - " print(f\"your remaining balance --> {data['balance'][check]}\")\n", + " if 0 < i5 <= data[\"balance\"][check]:\n", + " debit = data[\"balance\"][check] - i5\n", + " data[\"balance\"][check] = debit\n", + " print(\n", + " f\"your remaining balance --> {data['balance'][check]}\"\n", + " )\n", " else:\n", " print(\"your debit amount is more than balance \")\n", " continue\n", - " #credit part\n", - " elif i4 == 3 :\n", + " # credit part\n", + " elif i4 == 3:\n", " print(\"credit\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " i6 = int(input(\"enter credit amount : \"))\n", " if 0 < i6:\n", - " credit = data['balance'][check]+i6\n", - " data['balance'][check] = credit\n", + " credit = data[\"balance\"][check] + i6\n", + " data[\"balance\"][check] = credit\n", " print(f\"your new balance --> {data['balance'][check]}\")\n", " else:\n", " print(\"your credit amount is low \")\n", " continue\n", - " #password part\n", - " elif i4 == 4 :\n", + " # password part\n", + " elif i4 == 4:\n", " print(\"change password\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " old = input(\"enter your old password : \")\n", - " print(\"your password must have at list one lower case, one uppercase, one digital, one special case and length of password is 8\")\n", - " new = getpass.getpass(prompt = \"Enter your new password\" )\n", + " print(\n", + " \"your password must have at list one lower case, one uppercase, one digital, one special case and length of password is 8\"\n", + " )\n", + " new = getpass.getpass(prompt=\"Enter your new password\")\n", " if old == data[\"password\"][check]:\n", - " low, up ,sp ,di = 0, 0, 0, 0\n", - " if (len(new))> 8 :\n", + " low, up, sp, di = 0, 0, 0, 0\n", + " if (len(new)) > 8:\n", " for i in new:\n", - " if (i.islower()):\n", + " if i.islower():\n", " low += 1\n", - " if (i.isupper()):\n", - " up +=1 \n", - " if (i.isdigit()):\n", + " if i.isupper():\n", + " up += 1\n", + " if i.isdigit():\n", " di += 1\n", - " if (i in ['@','$','%','^','&','*']):\n", + " if i in [\"@\", \"$\", \"%\", \"^\", \"&\", \"*\"]:\n", " sp += 1\n", - " if (low>=1 and up>=1 and sp>=1 and di>=1 and low+up+sp+di==len(new)):\n", - " data['password'][check] = new\n", - " print(f\"your new password --> {data['password'][check]}\")\n", + " if (\n", + " low >= 1\n", + " and up >= 1\n", + " and sp >= 1\n", + " and di >= 1\n", + " and low + up + sp + di == len(new)\n", + " ):\n", + " data[\"password\"][check] = new\n", + " print(\n", + " f\"your new password --> {data['password'][check]}\"\n", + " )\n", " else:\n", " print(\"Invalid Password\")\n", " else:\n", " print(\"old password wrong please enter valid password\")\n", " continue\n", - " elif i4 == 5 :\n", + " elif i4 == 5:\n", " print(\"main menu\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " break\n", " else:\n", - " print(\"please enter valid number\") \n", + " print(\"please enter valid number\")\n", " else:\n", " print(\"please check your password number\".center(50))\n", " else:\n", - " print(\"please check your account number\".center(50)) \n", - " #signup part \n", - " elif i1 == 2 :\n", + " print(\"please check your account number\".center(50))\n", + " # signup part\n", + " elif i1 == 2:\n", " print(\"signup\".center(90))\n", - " print(\"_\"*100)\n", - " acc = 1001 + len(data['accno'])\n", - " data['accno'].append(acc)\n", - " ind = (data['accno']).index(acc)\n", + " print(\"_\" * 100)\n", + " acc = 1001 + len(data[\"accno\"])\n", + " data[\"accno\"].append(acc)\n", + " ind = (data[\"accno\"]).index(acc)\n", " name = input(\"enter your name : \")\n", - " data['name'].append(name)\n", + " data[\"name\"].append(name)\n", " balance = int(input(\"enter your initial balance : \"))\n", - " data['balance'].append(balance)\n", + " data[\"balance\"].append(balance)\n", " password = input(\"enter your password : \")\n", - " data['password'].append(password)\n", + " data[\"password\"].append(password)\n", " security_check = (int(input(\"enter your security pin (DDMM) : \"))).split()\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your account number --> {data['accno'][ind]}\".center(50))\n", " print(f\"your name --> {data['name'][ind]}\".center(50))\n", " print(f\"your balance --> {data['balance'][ind]}\".center(50))\n", " print(f\"your password --> {data['password'][ind]}\".center(50))\n", " continue\n", - " #exit part\n", - " elif i1== 3 :\n", + " # exit part\n", + " elif i1 == 3:\n", " print(\"exit\".center(90))\n", " print(\"thank you for visiting\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " break\n", " else:\n", - " print(f\"wrong enter : {i1}\".center(50))\n" + " print(f\"wrong enter : {i1}\".center(50))" ] }, { @@ -247,7 +261,7 @@ "source": [ "def cheak_ditails(check):\n", " print(\"cheak ditails\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your account number --> {data['accno'][check]}\")\n", " print(f\"your name --> {data['name'][check]}\")\n", " print(f\"your balance --> {data['balance'][check]}\")" @@ -261,12 +275,12 @@ "source": [ "def credit(check):\n", " print(\"credit\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " i6 = int(input(\"enter credit amount : \"))\n", " if 0 < i6:\n", - " credit = data['balance'][check]+i6\n", - " data['balance'][check] = credit\n", + " credit = data[\"balance\"][check] + i6\n", + " data[\"balance\"][check] = credit\n", " print(f\"your new balance --> {data['balance'][check]}\")\n", " else:\n", " print(\"your credit amount is low \")" @@ -280,12 +294,12 @@ "source": [ "def debit(check):\n", " print(\"debit\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " print(f\"your balance --> {data['balance'][check]}\")\n", " i5 = int(input(\"enter debit amount : \"))\n", - " if 0 < i5 <= data['balance'][check]:\n", - " debit = data['balance'][check]-i5\n", - " data['balance'][check] = debit\n", + " if 0 < i5 <= data[\"balance\"][check]:\n", + " debit = data[\"balance\"][check] - i5\n", + " data[\"balance\"][check] = debit\n", " print(f\"your remaining balance --> {data['balance'][check]}\")\n", " else:\n", " print(\"your debit amount is more than balance \")" @@ -299,24 +313,32 @@ "source": [ "def change_password(check):\n", " print(\"change password\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " old = input(\"enter your old password : \")\n", - " print(\"your password must have at list one lower case, one uppercase, one digital, one special case and length of password is 8\")\n", - " new = getpass.getpass(prompt = \"Enter your new password\" )\n", + " print(\n", + " \"your password must have at list one lower case, one uppercase, one digital, one special case and length of password is 8\"\n", + " )\n", + " new = getpass.getpass(prompt=\"Enter your new password\")\n", " if old == data[\"password\"][check]:\n", - " low, up ,sp ,di = 0, 0, 0, 0\n", - " if (len(new))> 8 :\n", + " low, up, sp, di = 0, 0, 0, 0\n", + " if (len(new)) > 8:\n", " for i in new:\n", - " if (i.islower()):\n", + " if i.islower():\n", " low += 1\n", - " if (i.isupper()):\n", - " up +=1 \n", - " if (i.isdigit()):\n", + " if i.isupper():\n", + " up += 1\n", + " if i.isdigit():\n", " di += 1\n", - " if (i in ['@','$','%','^','&','*']):\n", + " if i in [\"@\", \"$\", \"%\", \"^\", \"&\", \"*\"]:\n", " sp += 1\n", - " if (low>=1 and up>=1 and sp>=1 and di>=1 and low+up+sp+di==len(new)):\n", - " data['password'][check] = new\n", + " if (\n", + " low >= 1\n", + " and up >= 1\n", + " and sp >= 1\n", + " and di >= 1\n", + " and low + up + sp + di == len(new)\n", + " ):\n", + " data[\"password\"][check] = new\n", " print(f\"your new password --> {data['password'][check]}\")\n", " else:\n", " print(\"Invalid Password\")\n", @@ -332,42 +354,44 @@ "source": [ "def login():\n", " print(\"login\".center(90))\n", - " print(\"_\"*100)\n", + " print(\"_\" * 100)\n", " i2 = int(input(\"enter account number : \".center(50)))\n", " if i2 in (data[\"accno\"]):\n", " check = (data[\"accno\"]).index(i2)\n", " i3 = input(\"enter password : \".center(50))\n", - " check2= data[\"password\"].index(i3)\n", - " if check == check2:\n", + " check2 = data[\"password\"].index(i3)\n", + " if check == check2:\n", " while True:\n", - " print(\"\\n 1.check ditails \\n 2. debit \\n 3. credit \\n 4. change password \\n 5. main Manu \")\n", + " print(\n", + " \"\\n 1.check ditails \\n 2. debit \\n 3. credit \\n 4. change password \\n 5. main Manu \"\n", + " )\n", " i4 = int(input(\"enter what you want :\".center(50)))\n", - " #check ditails part\n", + " # check ditails part\n", " if i4 == 1:\n", " cheak_ditails(check)\n", " continue\n", - " #debit part\n", - " elif i4 == 2 :\n", + " # debit part\n", + " elif i4 == 2:\n", " debit(check)\n", " continue\n", - " #credit part\n", - " elif i4 == 3 :\n", + " # credit part\n", + " elif i4 == 3:\n", " credit(check)\n", " continue\n", - " #password part\n", - " elif i4 == 4 :\n", + " # password part\n", + " elif i4 == 4:\n", " change_password(check)\n", " continue\n", - " elif i4 == 5 :\n", + " elif i4 == 5:\n", " print(\"main menu\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " break\n", " else:\n", - " print(\"please enter valid number\") \n", + " print(\"please enter valid number\")\n", " else:\n", " print(\"please check your password number\".center(50))\n", " else:\n", - " print(\"please check your account number\".center(50)) " + " print(\"please check your account number\".center(50))" ] }, { @@ -377,13 +401,13 @@ "outputs": [], "source": [ "def security_check(ss):\n", - " data = {(1, 3, 5, 7, 8, 10, 12) : 31, (2, ) : 29, (4, 6, 9) : 30}\n", + " data = {(1, 3, 5, 7, 8, 10, 12): 31, (2,): 29, (4, 6, 9): 30}\n", " month = ss[2:]\n", " date = ss[:2]\n", " for key, value in data.items():\n", " print(key, value)\n", " if int(month) in key:\n", - " if 1<=int(date)<=value:\n", + " if 1 <= int(date) <= value:\n", " return True\n", " return False\n", " return False" @@ -397,22 +421,22 @@ "source": [ "def signup():\n", " print(\"signup\".center(90))\n", - " print(\"_\"*100)\n", - " acc = 1001 + len(data['accno'])\n", - " data['accno'].append(acc)\n", - " ind = (data['accno']).index(acc)\n", + " print(\"_\" * 100)\n", + " acc = 1001 + len(data[\"accno\"])\n", + " data[\"accno\"].append(acc)\n", + " ind = (data[\"accno\"]).index(acc)\n", " name = input(\"enter your name : \")\n", - " data['name'].append(name)\n", + " data[\"name\"].append(name)\n", " balance = int(input(\"enter your initial balance : \"))\n", - " data['balance'].append(balance)\n", + " data[\"balance\"].append(balance)\n", " password = input(\"enter your password : \")\n", - " data['password'].append(password)\n", - " ss=input(\"enter a secuirty quetion in form dd//mm\")\n", + " data[\"password\"].append(password)\n", + " ss = input(\"enter a secuirty quetion in form dd//mm\")\n", " security_check(ss)\n", - " data['security_check'].append(ss)\n", - " print(\".\"*100)\n", + " data[\"security_check\"].append(ss)\n", + " print(\".\" * 100)\n", " print(f\"your account number --> {data['accno'][ind]}\".center(50))\n", - " print(f\"your name --> {data['name'][ind]}\".center(50))\n" + " print(f\"your name --> {data['name'][ind]}\".center(50))" ] }, { @@ -452,26 +476,27 @@ "source": [ "def main():\n", " import getpass\n", + "\n", " print(\"-------------------\".center(100))\n", " print(\"| Bank Application |\".center(100))\n", - " print(\"-\"*100)\n", - " while True :\n", + " print(\"-\" * 100)\n", + " while True:\n", " print(\"\\n 1. Login \\n 2. Signup \\n 3. Exit\")\n", " i1 = int(input(\"enter what you want login, signup, exit :\".center(50)))\n", - " #login part\n", + " # login part\n", " if i1 == 1:\n", " login()\n", - " #signup part \n", - " elif i1 == 2 :\n", + " # signup part\n", + " elif i1 == 2:\n", " signup()\n", - " #exit part\n", - " elif i1== 3 :\n", + " # exit part\n", + " elif i1 == 3:\n", " print(\"exit\".center(90))\n", " print(\"thank you for visiting\".center(90))\n", - " print(\".\"*100)\n", + " print(\".\" * 100)\n", " break\n", " else:\n", - " print(f\"wrong enter : {i1}\".center(50))\n" + " print(f\"wrong enter : {i1}\".center(50))" ] }, { diff --git a/Battery_notifier.py b/Battery_notifier.py index d871e43d928..68bd2367950 100644 --- a/Battery_notifier.py +++ b/Battery_notifier.py @@ -1,14 +1,12 @@ -from plyer import notification # pip install plyer import psutil # pip install psutil +from plyer import notification # pip install plyer # psutil.sensors_battery() will return the information related to battery battery = psutil.sensors_battery() # battery percent will return the current battery prcentage percent = battery.percent -charging = ( - battery.power_plugged -) +charging = battery.power_plugged # Notification(title, description, duration)--to send # notification to desktop diff --git a/Binary_search.py b/Binary_search.py index 0b2211d6a48..f39d1f0a6ad 100644 --- a/Binary_search.py +++ b/Binary_search.py @@ -24,7 +24,10 @@ def binary_search(arr, l, r, x): # Main Function if __name__ == "__main__": # User input array - arr = [int(x) for x in input("Enter the array with elements separated by commas: ").split(",")] + arr = [ + int(x) + for x in input("Enter the array with elements separated by commas: ").split(",") + ] # User input element to search for x = int(input("Enter the element you want to search for: ")) @@ -34,6 +37,6 @@ def binary_search(arr, l, r, x): # printing the output if result != -1: - print("Element is present at index {}".format(result)) + print(f"Element is present at index {result}") else: print("Element is not present in array") diff --git a/BlackJack_game/blackjack.py b/BlackJack_game/blackjack.py index c1bc919e01c..b4c6e5f3d58 100644 --- a/BlackJack_game/blackjack.py +++ b/BlackJack_game/blackjack.py @@ -1,14 +1,14 @@ # master # master # BLACK JACK - CASINO A GAME OF FORTUNE!!! +# master +import random from time import * # BLACK JACK - CASINO # PYTHON CODE BASE -# master -import random deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4 @@ -28,7 +28,7 @@ print("Still Loading---") sleep(2) print( - "So You Are Still Here Not Gone I Gave You Chance But No Problem May Be You Trust Your Fortune A Lot \n Lets Begin Then" + "So You Are Still Here Not Gone I Gave You Chance But No Problem May Be You Trust Your Fortune A Lot \n Lets Begin Then", ) sleep(2) d_cards = [] # Initialising dealer's cards @@ -107,7 +107,7 @@ def dealer_choice(): # to continue the game again and again !! k = input("Want to hit or stay?\n Press 1 for hit and 0 for stay ") - if k == "1": #Ammended 1 to a string + if k == "1": # Ammended 1 to a string random.shuffle(deck) p_cards.append(deck.pop()) print("You have a total of " + str(sum(p_cards)) + " with the cards ", p_cards) diff --git a/BlackJack_game/blackjack_rr.py b/BlackJack_game/blackjack_rr.py index d7c46b83cf6..f37b7a1d50e 100644 --- a/BlackJack_game/blackjack_rr.py +++ b/BlackJack_game/blackjack_rr.py @@ -192,7 +192,7 @@ def push(player, dealer): print("\t **********************************************************") print( - "\t Welcome to the game Casino - BLACK JACK ! " + "\t Welcome to the game Casino - BLACK JACK ! ", ) print("\t **********************************************************") print(Colour.BLACK + "\t ***************") @@ -208,7 +208,7 @@ def push(player, dealer): print("\t ***************" + Colour.END) print( - "\nRULES: Get as close to 21 as you can but if you get more than 21 you will lose!\n Aces count as 1 or 11." + "\nRULES: Get as close to 21 as you can but if you get more than 21 you will lose!\n Aces count as 1 or 11.", ) deck = Deck() @@ -268,11 +268,11 @@ def push(player, dealer): + "\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n \t Congratulations! You won " + str(player_chips.total) + " coins!\n\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n " - + Colour.END + + Colour.END, ) break else: print( - "Oops! You have bet all your chips and we are sorry you can't play more.\nThanks for playing! Do come again to Casino BLACK JACK!" + "Oops! You have bet all your chips and we are sorry you can't play more.\nThanks for playing! Do come again to Casino BLACK JACK!", ) break diff --git a/BlackJack_game/blackjack_simulate.py b/BlackJack_game/blackjack_simulate.py index ae1706f6888..eaf169bbe33 100644 --- a/BlackJack_game/blackjack_simulate.py +++ b/BlackJack_game/blackjack_simulate.py @@ -120,7 +120,9 @@ def __bool__(self): def get_tips(content): fmt_tips = "{color}** TIPS: {content}! **{end}" return fmt_tips.format( - color=COLOR.get("YELLOW"), content=content, end=COLOR.get("END") + color=COLOR.get("YELLOW"), + content=content, + end=COLOR.get("END"), ) @property @@ -198,7 +200,7 @@ def __init__(self, name, role, chips_amount=None, color="END"): :param chips_amount: Casino tokens equal money """ self.name = name - self.prompt = "{role} >> ({name}) : ".format(role=role, name=self.name) + self.prompt = f"{role} >> ({self.name}) : " self.chips = Chips(chips_amount) self.color = color self.hand = [] @@ -248,7 +250,9 @@ def _sum_up(ranks): def is_point(self, opt, point): self.calculate_point() compare_fmt = "{user_point} {opt} {point}".format( - user_point=self.point, opt=opt, point=point + user_point=self.point, + opt=opt, + point=point, ) return eval(compare_fmt) @@ -265,7 +269,7 @@ def showing(self): def unveiling(self): self.calculate_point() - points_fmt = "My point is: {}".format(str(self.point)) + points_fmt = f"My point is: {str(self.point)}" self.speak(points_fmt) self.unveil_card() @@ -299,7 +303,9 @@ def __init__(self, name, amount): def refresh_prompt(self): self.prompt = "{role} [ ${remain} ] >> ({name}) : ".format( - role="Player", name=self.name, remain=self.chips.current_amount() + role="Player", + name=self.name, + remain=self.chips.current_amount(), ) def select_choice(self, pattern): @@ -345,7 +351,8 @@ def update(self, winner, chips, player_point, dealer_point): def record(self, winner, chips, player_point, dealer_point): self.update(winner, chips, player_point, dealer_point) Row = namedtuple( - "Row", ["rounds", "player_point", "dealer_point", "winner", "remain_chips"] + "Row", + ["rounds", "player_point", "dealer_point", "winner", "remain_chips"], ) row = Row( self.rounds, @@ -384,7 +391,7 @@ def digram(self): row.dealer_point, row.winner, row.remain_chips, - ) + ), ) print("") diff --git a/BlackJack_game/requirements.txt b/BlackJack_game/requirements.txt index 3320ad5cf21..2c07f3d2aec 100644 --- a/BlackJack_game/requirements.txt +++ b/BlackJack_game/requirements.txt @@ -1,2 +1,2 @@ -time random +time diff --git a/BoardGame-CLI/python.py b/BoardGame-CLI/python.py index 40183159ec1..49929a775ce 100644 --- a/BoardGame-CLI/python.py +++ b/BoardGame-CLI/python.py @@ -2,16 +2,35 @@ # Define the game board with snakes and ladders snakes_and_ladders = { - 2: 38, 7: 14, 8: 31, 15: 26, 16: 6, 21: 42, - 28: 84, 36: 44, 46: 25, 49: 11, 51: 67, 62: 19, - 64: 60, 71: 91, 74: 53, 78: 98, 87: 94, 89: 68, - 92: 88, 95: 75, 99: 80 + 2: 38, + 7: 14, + 8: 31, + 15: 26, + 16: 6, + 21: 42, + 28: 84, + 36: 44, + 46: 25, + 49: 11, + 51: 67, + 62: 19, + 64: 60, + 71: 91, + 74: 53, + 78: 98, + 87: 94, + 89: 68, + 92: 88, + 95: 75, + 99: 80, } + # Function to roll a six-sided die def roll_die(): return random.randint(1, 6) + # Function to simulate a single turn def take_turn(current_position, player_name): # Roll the die @@ -36,6 +55,7 @@ def take_turn(current_position, player_name): return new_position + # Main game loop def play_snakes_and_ladders(): player1_position = 1 @@ -65,5 +85,6 @@ def play_snakes_and_ladders(): elif player2_position == 100: print(f"{player2_name} won!") + # Start the game play_snakes_and_ladders() diff --git a/BoardGame-CLI/snakeLadder.py b/BoardGame-CLI/snakeLadder.py index d8892ed4339..6fdde16383a 100644 --- a/BoardGame-CLI/snakeLadder.py +++ b/BoardGame-CLI/snakeLadder.py @@ -43,14 +43,14 @@ def play(): global imp while imp: - print("/"*20) + print("/" * 20) print("1 -> roll the dice (or enter)") print("2 -> start new game") print("3 -> exit the game") - print("/"*20) + print("/" * 20) for i in players: - n = input("{}'s turn: ".format(i)) or 1 + n = input(f"{i}'s turn: ") or 1 n = int(n) if players[i] < 100: @@ -70,7 +70,7 @@ def play(): looproll = roll() temp1 += looproll print(f"you got {looproll} ") - if counter_6 == 3 : + if counter_6 == 3: temp1 -= 18 print("Three consectutives 6 got cancelled") print("") @@ -116,19 +116,19 @@ def move(a, i): # snake bite code def snake(c, i): - if (c == 32): + if c == 32: players[i] = 10 - elif (c == 36): + elif c == 36: players[i] = 6 - elif (c == 48): + elif c == 48: players[i] = 26 - elif (c == 63): + elif c == 63: players[i] = 18 - elif (c == 88): + elif c == 88: players[i] = 24 - elif (c == 95): + elif c == 95: players[i] = 56 - elif (c == 97): + elif c == 97: players[i] = 78 else: return players[i] @@ -141,21 +141,21 @@ def snake(c, i): def ladder(a, i): global players - if (a == 4): + if a == 4: players[i] = 14 - elif (a == 8): + elif a == 8: players[i] = 30 - elif (a == 20): + elif a == 20: players[i] = 38 - elif (a == 40): + elif a == 40: players[i] = 42 - elif (a == 28): + elif a == 28: players[i] = 76 - elif (a == 50): + elif a == 50: players[i] = 67 - elif (a == 71): + elif a == 71: players[i] = 92 - elif (a == 88): + elif a == 88: players[i] = 99 else: return players[i] @@ -165,9 +165,9 @@ def ladder(a, i): # while run: -print("/"*40) +print("/" * 40) print("Welcome to the snake ladder game !!!!!!!") -print("/"*40) +print("/" * 40) player_input() diff --git a/BoardGame-CLI/uno.py b/BoardGame-CLI/uno.py index 4f36372a5f8..6eb6df43657 100644 --- a/BoardGame-CLI/uno.py +++ b/BoardGame-CLI/uno.py @@ -1,6 +1,7 @@ # uno game # import random + """ Generate the UNO deck of 108 cards. Parameters: None @@ -16,7 +17,7 @@ def buildDeck(): wilds = ["Wild", "Wild Draw Four"] for colour in colours: for value in values: - cardVal = "{} {}".format(colour, value) + cardVal = f"{colour} {value}" deck.append(cardVal) if value != 0: deck.append(cardVal) @@ -62,12 +63,12 @@ def drawCards(numCards): def showHand(player, playerHand): - print("Player {}'s Turn".format(players_name[player])) + print(f"Player {players_name[player]}'s Turn") print("Your Hand") print("------------------") y = 1 for card in playerHand: - print("{}) {}".format(y, card)) + print(f"{y}) {card}") y += 1 print("") @@ -99,9 +100,10 @@ def canPlay(colour, value, playerHand): numPlayers = int(input("How many players?")) while numPlayers < 2 or numPlayers > 4: numPlayers = int( - input("Invalid. Please enter a number between 2-4.\nHow many players?")) + input("Invalid. Please enter a number between 2-4.\nHow many players?"), + ) for player in range(numPlayers): - players_name.append(input("Enter player {} name: ".format(player+1))) + players_name.append(input(f"Enter player {player + 1} name: ")) players.append(drawCards(5)) @@ -118,14 +120,17 @@ def canPlay(colour, value, playerHand): while playing: showHand(playerTurn, players[playerTurn]) - print("Card on top of discard pile: {}".format(discards[-1])) + print(f"Card on top of discard pile: {discards[-1]}") if canPlay(currentColour, cardVal, players[playerTurn]): cardChosen = int(input("Which card do you want to play?")) - while not canPlay(currentColour, cardVal, [players[playerTurn][cardChosen-1]]): + while not canPlay( + currentColour, cardVal, [players[playerTurn][cardChosen - 1]] + ): cardChosen = int( - input("Not a valid card. Which card do you want to play?")) - print("You played {}".format(players[playerTurn][cardChosen-1])) - discards.append(players[playerTurn].pop(cardChosen-1)) + input("Not a valid card. Which card do you want to play?"), + ) + print(f"You played {players[playerTurn][cardChosen - 1]}") + discards.append(players[playerTurn].pop(cardChosen - 1)) # cheak if player won if len(players[playerTurn]) == 0: @@ -142,13 +147,15 @@ def canPlay(colour, value, playerHand): cardVal = splitCard[1] if currentColour == "Wild": for x in range(len(colours)): - print("{}) {}".format(x+1, colours[x])) + print(f"{x + 1}) {colours[x]}") newColour = int( - input("What colour would you like to choose? ")) + input("What colour would you like to choose? "), + ) while newColour < 1 or newColour > 4: newColour = int( - input("Invalid option. What colour would you like to choose")) - currentColour = colours[newColour-1] + input("Invalid option. What colour would you like to choose"), + ) + currentColour = colours[newColour - 1] if cardVal == "Reverse": playDirection = playDirection * -1 elif cardVal == "Skip": @@ -156,20 +163,20 @@ def canPlay(colour, value, playerHand): if playerTurn >= numPlayers: playerTurn = 0 elif playerTurn < 0: - playerTurn = numPlayers-1 + playerTurn = numPlayers - 1 elif cardVal == "Draw Two": - playerDraw = playerTurn+playDirection + playerDraw = playerTurn + playDirection if playerDraw == numPlayers: playerDraw = 0 elif playerDraw < 0: - playerDraw = numPlayers-1 + playerDraw = numPlayers - 1 players[playerDraw].extend(drawCards(2)) elif cardVal == "Draw Four": - playerDraw = playerTurn+playDirection + playerDraw = playerTurn + playDirection if playerDraw == numPlayers: playerDraw = 0 elif playerDraw < 0: - playerDraw = numPlayers-1 + playerDraw = numPlayers - 1 players[playerDraw].extend(drawCards(4)) print("") else: @@ -180,7 +187,7 @@ def canPlay(colour, value, playerHand): if playerTurn >= numPlayers: playerTurn = 0 elif playerTurn < 0: - playerTurn = numPlayers-1 + playerTurn = numPlayers - 1 print("Game Over") -print("{} is the Winner!".format(winner)) +print(f"{winner} is the Winner!") diff --git a/BruteForce.py b/BruteForce.py index 46b17844e26..27f10255e58 100644 --- a/BruteForce.py +++ b/BruteForce.py @@ -78,7 +78,10 @@ def testFunction(password): # Obtém a senha encontrada e o múmero de tentativas password, attempts = findPassword( - chars, testFunction, show=1000, format_=" Trying %s" + chars, + testFunction, + show=1000, + format_=" Trying %s", ) t = datetime.timedelta(seconds=int(time.process_time() - t)) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 24cde27bebc..019119b64b1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,19 +1,19 @@ # Contributing Notepad Sorting When contributing to this repository, please first discuss the change you wish to make via issue, -email, or any other method with the owners of this repository before making a change. +email, or any other method with the owners of this repository before making a change. Please note we have a code of conduct, please follow it in all your interactions with the project. ## Pull Request Process -1. Ensure any install or build dependencies are removed before the end of the layer when doing a +1. Ensure any install or build dependencies are removed before the end of the layer when doing a build. -2. Update the README.md with details of changes to the interface, this includes new environment +2. Update the README.md with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters. 3. Increase the version numbers in any examples files and the README.md to the new version that this Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). -4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you +4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you do not have permission to do that, you may request the second reviewer to merge it for you. ## Code of Conduct diff --git a/CRC/crc.py b/CRC/crc.py index d3d302244b7..b0653fc3acc 100644 --- a/CRC/crc.py +++ b/CRC/crc.py @@ -42,7 +42,7 @@ def crc_check(data, div): print("Sent data: ", original_data + crc_str) sent_data = original_data + crc_str print( - "If again applying CRC algorithm, the remainder/CRC must be zero if errorless." + "If again applying CRC algorithm, the remainder/CRC must be zero if errorless.", ) crc = crc_check(sent_data, div) remainder = crc diff --git a/Caesar Cipher Encoder & Decoder.py b/Caesar Cipher Encoder & Decoder.py index 63097b39e17..1df020bd03d 100644 --- a/Caesar Cipher Encoder & Decoder.py +++ b/Caesar Cipher Encoder & Decoder.py @@ -6,6 +6,7 @@ # Improved by: OfficialAhmed (https://github.com/OfficialAhmed) + def get_int() -> int: """ Get integer, otherwise redo @@ -19,6 +20,7 @@ def get_int() -> int: return key + def main(): print("[>] CAESAR CIPHER DECODER!!! \n") @@ -42,9 +44,9 @@ def encode(): encoded_cipher = "" text = input("Enter text to encode: ") key = get_int() - + for char in text: - + ascii = ord(char) + key encoded_cipher += chr(ascii) @@ -64,5 +66,5 @@ def decode(): print(decoded_cipher) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/Calculate resistance.py b/Calculate resistance.py index 10c7a5ad3e2..605d4390214 100644 --- a/Calculate resistance.py +++ b/Calculate resistance.py @@ -1,12 +1,14 @@ def res(R1, R2): - sum = R1 + R2 - if (option =="series"): - return sum - else: - return (R1 * R2)/(R1 + R2) + sum = R1 + R2 + if option == "series": + return sum + else: + return (R1 * R2) / (R1 + R2) + + Resistance1 = int(input("Enter R1 : ")) Resistance2 = int(input("Enter R2 : ")) option = str(input("Enter series or parallel :")) print("\n") -R = res(Resistance1,Resistance2 ) +R = res(Resistance1, Resistance2) print("The total resistance is", R) diff --git a/Calendar (GUI).py b/Calendar (GUI).py index 1649a78785d..a4b1093b2cf 100644 --- a/Calendar (GUI).py +++ b/Calendar (GUI).py @@ -1,5 +1,5 @@ -from tkinter import * import calendar +from tkinter import * root = Tk() # root.geometry("400x300") @@ -7,6 +7,7 @@ # Function + def text(): month_int = int(month.get()) year_int = int(year.get()) diff --git a/Cat/cat.py b/Cat/cat.py index 552ed6c1e7a..0c9ba120255 100644 --- a/Cat/cat.py +++ b/Cat/cat.py @@ -20,8 +20,10 @@ David Costell (DontEatThemCookies on GitHub) v2 - 03/12/2022 """ + import sys + def with_files(files): """Executes when file(s) is/are specified.""" try: @@ -35,6 +37,7 @@ def with_files(files): for contents in file_contents: sys.stdout.write(contents) + def no_files(): """Executes when no file(s) is/are specified.""" try: @@ -47,6 +50,7 @@ def no_files(): except EOFError: exit() + def main(): """Entry point of the cat program.""" # Read the arguments passed to the program @@ -55,5 +59,6 @@ def main(): else: with_files(sys.argv[1:]) + if __name__ == "__main__": main() diff --git a/Cat/text_b.txt b/Cat/text_b.txt index 359622ed342..98d677979fb 100644 --- a/Cat/text_b.txt +++ b/Cat/text_b.txt @@ -5,4 +5,4 @@ The knights who say ni! Lines of Text! -This file does not end with a newline. \ No newline at end of file +This file does not end with a newline. diff --git a/Checker_game_by_dz/first.py b/Checker_game_by_dz/first.py index 55c572e3629..8f520015ae6 100644 --- a/Checker_game_by_dz/first.py +++ b/Checker_game_by_dz/first.py @@ -3,12 +3,13 @@ """ -# import libraries -import pygame as pg from modules import statics as st -from modules.statics import * -from modules.checker_board import * from modules.checker import * +from modules.checker_board import * +from modules.statics import * + +# import libraries +import pygame as pg # static variables for this perticular file fps = 60 @@ -16,6 +17,7 @@ WIN = pg.display.set_mode((st.width, st.height)) pg.display.set_caption("Checkers") + # get row and col for mouse def get_row_col_mouse(pos): x, y = pos diff --git a/Checker_game_by_dz/modules/checker.py b/Checker_game_by_dz/modules/checker.py index 8525435aef0..70a7f4e1327 100644 --- a/Checker_game_by_dz/modules/checker.py +++ b/Checker_game_by_dz/modules/checker.py @@ -4,9 +4,10 @@ """ import pygame as pg + from .checker_board import * -from .statics import * from .pieces import * +from .statics import * class checker: diff --git a/Checker_game_by_dz/modules/checker_board.py b/Checker_game_by_dz/modules/checker_board.py index b14df11b360..59e88a41062 100644 --- a/Checker_game_by_dz/modules/checker_board.py +++ b/Checker_game_by_dz/modules/checker_board.py @@ -4,8 +4,10 @@ """ import pygame as pg -from .statics import * + from .pieces import * +from .statics import * + # checker board creation class checker_board: @@ -22,7 +24,9 @@ def draw_cubes(self, window): for row in range(rows): for col in range(row % 2, cols, 2): pg.draw.rect( - window, yellow, (row * sq_size, col * sq_size, sq_size, sq_size) + window, + yellow, + (row * sq_size, col * sq_size, sq_size, sq_size), ) def move(self, piece, row, col): @@ -72,18 +76,18 @@ def get_valid_moves(self, piece): if piece.color == black or piece.king: moves.update( - self._traverse_l(row - 1, max(row - 3, -1), -1, piece.color, l) + self._traverse_l(row - 1, max(row - 3, -1), -1, piece.color, l), ) moves.update( - self._traverse_r(row - 1, max(row - 3, -1), -1, piece.color, r) + self._traverse_r(row - 1, max(row - 3, -1), -1, piece.color, r), ) if piece.color == white or piece.king: moves.update( - self._traverse_l(row + 1, min(row + 3, rows), 1, piece.color, l) + self._traverse_l(row + 1, min(row + 3, rows), 1, piece.color, l), ) moves.update( - self._traverse_r(row + 1, min(row + 3, rows), 1, piece.color, r) + self._traverse_r(row + 1, min(row + 3, rows), 1, piece.color, r), ) return moves @@ -126,10 +130,10 @@ def _traverse_l(self, start, stop, step, color, l, skip=[]): else: row = min(r + 3, rows) moves.update( - self._traverse_l(r + step, row, step, color, l - 1, skip=last) + self._traverse_l(r + step, row, step, color, l - 1, skip=last), ) moves.update( - self._traverse_r(r + step, row, step, color, l + 1, skip=last) + self._traverse_r(r + step, row, step, color, l + 1, skip=last), ) break @@ -163,13 +167,23 @@ def _traverse_r(self, start, stop, step, color, right, skip=[]): row = min(r + 3, rows) moves.update( self._traverse_l( - r + step, row, step, color, right - 1, skip=last - ) + r + step, + row, + step, + color, + right - 1, + skip=last, + ), ) moves.update( self._traverse_r( - r + step, row, step, color, right + 1, skip=last - ) + r + step, + row, + step, + color, + right + 1, + skip=last, + ), ) break diff --git a/Checker_game_by_dz/modules/pieces.py b/Checker_game_by_dz/modules/pieces.py index 2a0b2de413f..2db643f8f06 100644 --- a/Checker_game_by_dz/modules/pieces.py +++ b/Checker_game_by_dz/modules/pieces.py @@ -3,9 +3,10 @@ """ -from .statics import * import pygame as pg +from .statics import * + class pieces: diff --git a/Chrome Dino Automater.py b/Chrome Dino Automater.py index eca256a1202..ccedae45911 100644 --- a/Chrome Dino Automater.py +++ b/Chrome Dino Automater.py @@ -1,9 +1,9 @@ -import pyautogui # pip install pyautogui -from PIL import Image, ImageGrab # pip install pillow - # from numpy import asarray import time +import pyautogui # pip install pyautogui +from PIL import Image, ImageGrab # pip install pillow + def hit(key): pyautogui.press(key) diff --git a/Classification_human_or_horse.py b/Classification_human_or_horse.py index 4aa069a855a..11b4c6b6552 100644 --- a/Classification_human_or_horse.py +++ b/Classification_human_or_horse.py @@ -5,7 +5,10 @@ model = tf.keras.models.Sequential( [ tf.keras.layers.Conv2D( - 16, (3, 3), activation="relu", input_shape=(200, 200, 3) + 16, + (3, 3), + activation="relu", + input_shape=(200, 200, 3), ), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(16, (3, 3), activation="relu"), @@ -15,7 +18,7 @@ tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation="relu"), tf.keras.layers.Dense(1, activation="sigmoid"), - ] + ], ) model.summary() from tensorflow.keras.optimizers import RMSprop @@ -36,8 +39,9 @@ from tkinter import Tk from tkinter.filedialog import askopenfilename -from keras.preprocessing import image + import numpy as np +from keras.preprocessing import image Tk().withdraw() filename = askopenfilename() diff --git a/CliYoutubeDownloader.py b/CliYoutubeDownloader.py index 7b9d3d4bf1d..be8d66fbd29 100644 --- a/CliYoutubeDownloader.py +++ b/CliYoutubeDownloader.py @@ -1,26 +1,31 @@ -from pytube import * import sys +from pytube import * + class YouTubeDownloder: def __init__(self): self.url = str(input("Enter the url of video : ")) self.youtube = YouTube( - self.url, on_progress_callback=YouTubeDownloder.onProgress + self.url, + on_progress_callback=YouTubeDownloder.onProgress, ) self.showTitle() def showTitle(self): - print("title : {0}\n".format(self.youtube.title)) + print(f"title : {self.youtube.title}\n") self.showStreams() def showStreams(self): self.streamNo = 1 for stream in self.youtube.streams: print( - "{0} => resolation:{1}/fps:{2}/type:{3}".format( - self.streamNo, stream.resolution, stream.fps, stream.type - ) + "{} => resolation:{}/fps:{}/type:{}".format( + self.streamNo, + stream.resolution, + stream.fps, + stream.type, + ), ) self.streamNo += 1 self.chooseStream() @@ -47,13 +52,13 @@ def getFileSize(self): def getPermisionToContinue(self): print( - "\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format( + "\n title : {} \n author : {} \n size : {:.2f}MB \n resolution : {} \n fps : {} \n ".format( self.youtube.title, self.youtube.author, file_size, self.stream.resolution, self.stream.fps, - ) + ), ) if input("do you want it ?(defualt = (y)es) or (n)o ") == "n": self.showStreams() diff --git a/CliYoutubeDownloader/CliYoutubeDownloader.py b/CliYoutubeDownloader/CliYoutubeDownloader.py index 81c35a81ad8..dc6a8bf8ee0 100644 --- a/CliYoutubeDownloader/CliYoutubeDownloader.py +++ b/CliYoutubeDownloader/CliYoutubeDownloader.py @@ -1,28 +1,33 @@ # libraraies -import pytube import sys +import pytube + class YouTubeDownloder: def __init__(self): self.url = str(input("Enter the url of video : ")) self.youtube = pytube.YouTube( - self.url, on_progress_callback=YouTubeDownloder.onProgress + self.url, + on_progress_callback=YouTubeDownloder.onProgress, ) self.showTitle() def showTitle(self): - print("title : {0}\n".format(self.youtube.title)) + print(f"title : {self.youtube.title}\n") self.showStreams() def showStreams(self): self.streamNo = 1 for stream in self.youtube.streams: print( - "{0} => resolution:{1}/fps:{2}/type:{3}".format( - self.streamNo, stream.resolution, stream.fps, stream.type - ) + "{} => resolution:{}/fps:{}/type:{}".format( + self.streamNo, + stream.resolution, + stream.fps, + stream.type, + ), ) self.streamNo += 1 self.chooseStream() @@ -49,13 +54,13 @@ def getFileSize(self): def getPermisionToContinue(self): print( - "\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format( + "\n title : {} \n author : {} \n size : {:.2f}MB \n resolution : {} \n fps : {} \n ".format( self.youtube.title, self.youtube.author, file_size, self.stream.resolution, self.stream.fps, - ) + ), ) if input("do you want it ?(defualt = (y)es) or (n)o ") == "n": self.showStreams() diff --git a/Colors/pixel_sort.py b/Colors/pixel_sort.py index 3c3c06ea616..ee34e63c165 100644 --- a/Colors/pixel_sort.py +++ b/Colors/pixel_sort.py @@ -1,17 +1,17 @@ """Pixel Sorting""" # Importing Libraries -import cv2 -import numpy as np -import math +import argparse import colorsys -import pandas as pd +import math import os -import argparse -from tqdm import tqdm +import cv2 +import numpy as np +import pandas as pd # Importing the external file Library import sound +from tqdm import tqdm # Taking arguments from command line parser = argparse.ArgumentParser() # you iniatize as such @@ -30,6 +30,7 @@ total = 0 dict, final, img_list = {}, [], [] + # Create dataframe and save it as an excel file def createDataSet(val=0, data=[]): global dict @@ -72,7 +73,9 @@ def step(bgr, repetitions=1): # conversion of rgb to hsv values h, s, v = colorsys.rgb_to_hsv( - r, g, b + r, + g, + b, ) # h,s,v is a better option for classifying each color # Repetitions are taken to decrease the noise @@ -130,7 +133,8 @@ def main(): color.append(val) thresh = findThreshold( - color, add + color, + add, ) # setting the threshold value for every row in the frame # For the specific row , if all the values are non-zero then it is sorted with color @@ -156,13 +160,14 @@ def main(): # Writing down the final sorted image cv2.imwrite( - "Image_sort/" + str(args.f) + "/" + str(args.f) + ".jpg", img + "Image_sort/" + str(args.f) + "/" + str(args.f) + ".jpg", + img, ) # Displaying the final picture print("\n>>> Formation of the Video progress of the pixel-sorted image") makeVideo() sound.main( - args.f + args.f, ) # Calling the external python file to create the audio of the pixel-sorted image diff --git a/Compression_Analysis/PSNR.py b/Compression_Analysis/PSNR.py index b3148c64c77..15a713eb8e6 100644 --- a/Compression_Analysis/PSNR.py +++ b/Compression_Analysis/PSNR.py @@ -34,7 +34,7 @@ def main(): # MSR = error_sum/(height*width) PSNR = -(10 * math.log10(error / (255 * 255))) - print("PSNR value is {}".format(PSNR)) + print(f"PSNR value is {PSNR}") if __name__ == "__main__": diff --git a/CountMillionCharacter.py b/CountMillionCharacter.py index c1aa7825a19..c26644ab370 100644 --- a/CountMillionCharacter.py +++ b/CountMillionCharacter.py @@ -6,9 +6,10 @@ Credit to William J. Turkel and Adam Crymble for the word frequency code used below. I just merged the two ideas. """ + import re -pattern = re.compile("\W") # re is used to compile the expression more than once +pattern = re.compile(r"\W") # re is used to compile the expression more than once # wordstring consisting of a million characters wordstring = """SCENE I. Yorkshire. Gaultree Forest. Enter the ARCHBISHOP OF YORK, MOWBRAY, LORD HASTINGS, and others @@ -308,7 +309,7 @@ wordlist.count(w) for w in wordlist ] # counts frequency of a letter in the given list -print("String\n {} \n".format(wordstring)) -print("List\n {} \n".format(str(wordlist))) -print("Frequencies\n {} \n".format(str(wordfreq))) -print("Pairs\n {}".format(str(dict(zip(wordlist, wordfreq))))) +print(f"String\n {wordstring} \n") +print(f"List\n {str(wordlist)} \n") +print(f"Frequencies\n {str(wordfreq)} \n") +print(f"Pairs\n {str(dict(zip(wordlist, wordfreq)))}") diff --git a/CountMillionCharacters-2.0.py b/CountMillionCharacters-2.0.py index a7f37a969dc..c1c9c1f2eb5 100644 --- a/CountMillionCharacters-2.0.py +++ b/CountMillionCharacters-2.0.py @@ -11,7 +11,7 @@ def main(): file_input = input("File Name: ") try: - with open(file_input, "r") as info: + with open(file_input) as info: count = collections.Counter(info.read().upper()) except FileNotFoundError: print("Please enter a valid file name.") diff --git a/Crack_password.py b/Crack_password.py index b32af07afd6..2cae1721b18 100644 --- a/Crack_password.py +++ b/Crack_password.py @@ -1,11 +1,39 @@ from random import * + user_pass = input("Enter your password: ") -password = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v','w', 'x', 'y', 'z',] +password = [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", +] guess = "" -while (guess != user_pass): +while guess != user_pass: guess = "" for letter in range(len(user_pass)): guess_letter = password[randint(0, 25)] guess = str(guess_letter) + str(guess) print(guess) -print("Your password is",guess) +print("Your password is", guess) diff --git a/Credit_Card_Validator.py b/Credit_Card_Validator.py index 08100e781fd..41b1a365424 100644 --- a/Credit_Card_Validator.py +++ b/Credit_Card_Validator.py @@ -16,7 +16,7 @@ def company(self): "67", "58", "63", - ) + ), ): comp = "Maestro Card" elif str(self.card_no).startswith("5"): diff --git a/Cricket_score.py b/Cricket_score.py index 22b8f05e319..6ce7aca591d 100644 --- a/Cricket_score.py +++ b/Cricket_score.py @@ -1,9 +1,8 @@ from urllib import request +import bs4 # Beautiful Soup for Web Scraping # import os import pyttsx3 - -import bs4 # Beautiful Soup for Web Scraping from win10toast import ToastNotifier toaster = ToastNotifier() diff --git a/Day_of_week.py b/Day_of_week.py index f0f9fd6f3b5..b7a9086f9b4 100644 --- a/Day_of_week.py +++ b/Day_of_week.py @@ -1,8 +1,8 @@ # Python program to Find day of # the week for a given date -import re # regular expressions import calendar # module of python to provide useful fucntions related to calendar import datetime # module of python to get the date and time +import re # regular expressions def process_date(user_input): @@ -13,7 +13,8 @@ def process_date(user_input): def find_day(date): born = datetime.datetime.strptime( - date, "%d %m %Y" + date, + "%d %m %Y", ).weekday() # this statement returns an integer corresponding to the day of the week return calendar.day_name[ born diff --git a/Decimal_To_Binary.py b/Decimal_To_Binary.py index a8e85097a14..da29312fe73 100644 --- a/Decimal_To_Binary.py +++ b/Decimal_To_Binary.py @@ -47,6 +47,7 @@ def dtbconverter(num): THis program accepts fractional values, the accuracy can be set below: """ + # Function to convert decimal number # to binary using recursion def DecimalToBinary(num): diff --git a/Divide Operator.py b/Divide Operator.py index 3e6468f6daf..7a2c8a2ed65 100644 --- a/Divide Operator.py +++ b/Divide Operator.py @@ -1,5 +1,5 @@ class DivisionOperation: - INT_MAX = float('inf') + INT_MAX = float("inf") def __init__(self, num1, num2): self.num1 = num1 diff --git a/Downloaded Files Organizer/obs.py b/Downloaded Files Organizer/obs.py index c084dfa15ec..3d5a89d3443 100644 --- a/Downloaded Files Organizer/obs.py +++ b/Downloaded Files Organizer/obs.py @@ -1,11 +1,12 @@ def watcher(path): # python script to observe changes in a folder + import os import sys import time - import os - from watchdog.observers import Observer - from watchdog.events import FileSystemEventHandler + from move_to_directory import add_to_dir + from watchdog.events import FileSystemEventHandler + from watchdog.observers import Observer class Handler(FileSystemEventHandler): def on_created(self, event): diff --git a/Downloaded Files Organizer/readme.md b/Downloaded Files Organizer/readme.md index 910f2789d20..d91ea542741 100644 --- a/Downloaded Files Organizer/readme.md +++ b/Downloaded Files Organizer/readme.md @@ -1,18 +1,18 @@ -# Downloaded files organizer using python +# Downloaded files organizer using python ##### Operating System : Windows Only ### Modules used -1.Built-in Modules: -sys,os,time -2.External Modules: -download the following modules using pip: +1.Built-in Modules: +sys,os,time +2.External Modules: +download the following modules using pip: psutil,watchdog ### How to use -1.After installing above modules,run browser_status.py.In browser_status.py makesure correct download path is given in this script. +1.After installing above modules,run browser_status.py.In browser_status.py makesure correct download path is given in this script. 2.Make sure that all the three python scripts reside in same directory ### Working -Whenever a file is downloaded,when this script is running ,it automatically categorize the file based on the file extension -For example, if a python script is downloaded which has ".py" extension, it goes into "code" folder automatically. +Whenever a file is downloaded,when this script is running ,it automatically categorize the file based on the file extension +For example, if a python script is downloaded which has ".py" extension, it goes into "code" folder automatically. -The file extensions and categories are collected from -https://github.com/dyne/file-extension-list +The file extensions and categories are collected from +https://github.com/dyne/file-extension-list diff --git a/Downloaded Files Organizer/requirements.txt b/Downloaded Files Organizer/requirements.txt index 0f0482e781e..f566fc48d28 100644 --- a/Downloaded Files Organizer/requirements.txt +++ b/Downloaded Files Organizer/requirements.txt @@ -1,5 +1,5 @@ -sys os -time psutil +sys +time watchdog diff --git a/Droplistmenu/GamesCalender.py b/Droplistmenu/GamesCalender.py index 990a164bd93..f4fb9db8a9e 100644 --- a/Droplistmenu/GamesCalender.py +++ b/Droplistmenu/GamesCalender.py @@ -1,22 +1,23 @@ - -from tkinter import * -from tkcalendar import Calendar import tkinter as tk +from tkinter import * +from tkcalendar import Calendar window = tk.Tk() # Adjust size window.geometry("600x500") -gameList =["Game List:"] +gameList = ["Game List:"] + + # Change the label text def show(): - game = selected1.get() + " vs " + selected2.get()+" on "+cal.get_date() + game = selected1.get() + " vs " + selected2.get() + " on " + cal.get_date() gameList.append(game) - #print(gameList) + # print(gameList) gameListshow = "\n".join(gameList) - #print(gameList) + # print(gameList) label.config(text=gameListshow) @@ -27,7 +28,7 @@ def show(): "Team 3", "Team 4", "Team 5", - "Team 6" + "Team 6", ] # datatype of menu text @@ -53,19 +54,22 @@ def show(): drop2.place(x=100, y=110) # Add Calendar -cal = Calendar(window, selectmode='day', - year=2022, month=12, - day=1) +cal = Calendar( + window, + selectmode="day", + year=2022, + month=12, + day=1, +) cal.place(x=300, y=20) - # Create button, it will change label text -button = Button( window, text="Add to calender", command=show).place(x=100,y=200) +button = Button(window, text="Add to calender", command=show).place(x=100, y=200) # Create Label label = Label(window, text=" ") label.place(x=150, y=250) -window.mainloop() \ No newline at end of file +window.mainloop() diff --git a/Electronics_Algorithms/resistance.py b/Electronics_Algorithms/resistance.py index c088732d90c..d3a8fe4714c 100644 --- a/Electronics_Algorithms/resistance.py +++ b/Electronics_Algorithms/resistance.py @@ -1,69 +1,64 @@ -def resistance_calculator(material:str, lenght:float, section:float, temperature:float): - """ - material is a string indicating the material of the wire - - lenght is a floating value indicating the lenght of the wire in meters +def resistance_calculator( + material: str, lenght: float, section: float, temperature: float +): + """ + material is a string indicating the material of the wire - diameter is a floating value indicating the diameter of the wire in millimeters + lenght is a floating value indicating the lenght of the wire in meters - temperature is a floating value indicating the temperature at which the wire is operating in °C + diameter is a floating value indicating the diameter of the wire in millimeters - Available materials: - - silver - - copper - - aluminium - - tungsten - - iron - - steel - - zinc - - solder""" + temperature is a floating value indicating the temperature at which the wire is operating in °C - materials = { - "silver": { - "rho": 0.0163, - "coefficient": 0.0038 - }, + Available materials: + - silver + - copper + - aluminium + - tungsten + - iron + - steel + - zinc + - solder""" - "copper": { - "rho": 0.0178, - "coefficient": 0.00381 - }, + materials = { + "silver": { + "rho": 0.0163, + "coefficient": 0.0038, + }, + "copper": { + "rho": 0.0178, + "coefficient": 0.00381, + }, + "aluminium": { + "rho": 0.0284, + "coefficient": 0.004, + }, + "tungsten": { + "rho": 0.055, + "coefficient": 0.0045, + }, + "iron": { + "rho": 0.098, + "coefficient": 0.006, + }, + "steel": { + "rho": 0.15, + "coefficient": 0.0047, + }, + "zinc": { + "rho": 0.06, + "coefficient": 0.0037, + }, + "solder": { + "rho": 0.12, + "coefficient": 0.0043, + }, + } - "aluminium": { - "rho": 0.0284, - "coefficient": 0.004 - }, + rho_20deg = materials[material]["rho"] + temp_coefficient = materials[material]["coefficient"] - "tungsten": { - "rho": 0.055, - "coefficient": 0.0045 - }, + rho = rho_20deg * (1 + temp_coefficient * (temperature - 20)) + resistance = rho * lenght / section - "iron": { - "rho": 0.098, - "coefficient": 0.006 - }, - - "steel": { - "rho": 0.15, - "coefficient": 0.0047 - }, - - "zinc": { - "rho": 0.06, - "coefficient": 0.0037 - }, - - "solder": { - "rho": 0.12, - "coefficient": 0.0043 - } - } - - rho_20deg = materials[material]["rho"] - temp_coefficient = materials[material]["coefficient"] - - rho = rho_20deg * (1 + temp_coefficient * (temperature - 20)) - resistance = rho * lenght / section - - return f"{resistance}Ω" + return f"{resistance}Ω" diff --git a/Emoji Dictionary/emoji_dictionary.py b/Emoji Dictionary/emoji_dictionary.py index 04949946c9c..16edf3d5427 100644 --- a/Emoji Dictionary/emoji_dictionary.py +++ b/Emoji Dictionary/emoji_dictionary.py @@ -2,9 +2,10 @@ # ----------------------------------------------------------------------------------------------------- import io # used for dealing with input and output -from tkinter import * # importing the necessary libraries -import tkinter.messagebox as mbox import tkinter as tk # imported tkinter as tk +import tkinter.messagebox as mbox +from tkinter import * # importing the necessary libraries + import emoji # ----------------------------------------------------------------------------------------------- @@ -244,12 +245,16 @@ def search_emoji(): # for writing Dictionary label, at the top of window dic = tk.Label( - text="EMOJI DICTIONARY", font=("Arial", 50, "underline"), fg="magenta" + text="EMOJI DICTIONARY", + font=("Arial", 50, "underline"), + fg="magenta", ) # same way bg dic.place(x=160, y=10) start1 = tk.Label( - text="Enter any Emoji you want to search...", font=("Arial", 30), fg="green" + text="Enter any Emoji you want to search...", + font=("Arial", 30), + fg="green", ) # same way bg start1.place(x=160, y=120) @@ -269,7 +274,12 @@ def on_inputentry_click(event): # Taking input from TextArea # inputentry = Entry(window,font=("Arial", 35), width=33, border=2) inputentry = Entry( - window, font=("Arial", 35), width=28, border=2, bg="light yellow", fg="brown" + window, + font=("Arial", 35), + width=28, + border=2, + bg="light yellow", + fg="brown", ) inputentry.place(x=120, y=180) @@ -314,6 +324,7 @@ def on_inputentry_click(event): ) outputtxt.place(x=120, y=400) + # function for exiting def exit_win(): if mbox.askokcancel("Exit", "Do you want to exit?"): diff --git a/Emoji Dictionary/requirements.txt b/Emoji Dictionary/requirements.txt index 840507a2445..90c5c1d93f0 100644 --- a/Emoji Dictionary/requirements.txt +++ b/Emoji Dictionary/requirements.txt @@ -1,3 +1,3 @@ -tkinter -messagebox emoji +messagebox +tkinter diff --git a/Encryption using base64.py b/Encryption using base64.py index a5d874e00e2..6e2bc924f1f 100644 --- a/Encryption using base64.py +++ b/Encryption using base64.py @@ -1,14 +1,15 @@ import base64 -#Encryption + +# Encryption message = input() -message_bytes = message.encode('ascii') +message_bytes = message.encode("ascii") base64_bytes = base64.b64encode(message_bytes) -base64_message = base64_bytes.decode('ascii') +base64_message = base64_bytes.decode("ascii") print(base64_message) -#Decryption -base64_bytes = base64_message.encode('ascii') +# Decryption +base64_bytes = base64_message.encode("ascii") message_bytes = base64.b64decode(base64_bytes) -message = message_bytes.decode('ascii') +message = message_bytes.decode("ascii") print(message) diff --git a/EncryptionTool.py b/EncryptionTool.py index f6600752fa6..4e0f8da1f38 100644 --- a/EncryptionTool.py +++ b/EncryptionTool.py @@ -2,7 +2,6 @@ # Simple encryption script for text # This was one my first versions of this script # 09/07/2017 -from __future__ import print_function import math @@ -46,7 +45,7 @@ def decrypt(enc_text): def readAndDecrypt(filename): - file = open(filename, "r") + file = open(filename) data = file.read() datalistint = [] actualdata = [] @@ -62,7 +61,7 @@ def readAndDecrypt(filename): def readAndEncrypt(filename): - file = open(filename, "r") + file = open(filename) data = file.read() datalist = list(data) encrypted_list = list() diff --git a/Exception_Handling_in_Python.py b/Exception_Handling_in_Python.py index 17f0e5ca1c0..54b8e3616e6 100644 --- a/Exception_Handling_in_Python.py +++ b/Exception_Handling_in_Python.py @@ -83,7 +83,7 @@ try: # Instead of aaa.txt lets try opening abc.txt - f = open("abc.txt", "r") + f = open("abc.txt") except FileNotFoundError: print("Incorrect file name used") @@ -105,7 +105,7 @@ finally: print( - "Handled multiples errors at one go with no need of knowing names of the errors." + "Handled multiples errors at one go with no need of knowing names of the errors.", ) diff --git a/Extract-Table-from-pdf-txt-docx/Parent/Child1/Text_Child1.txt b/Extract-Table-from-pdf-txt-docx/Parent/Child1/Text_Child1.txt index 44c8d0e41aa..934797d0d98 100644 --- a/Extract-Table-from-pdf-txt-docx/Parent/Child1/Text_Child1.txt +++ b/Extract-Table-from-pdf-txt-docx/Parent/Child1/Text_Child1.txt @@ -1 +1 @@ -AB,DF,G,DF,SDF,ADA,QW,WE,ER,FD 2,45,56,7,8,9,65,3,5436,78 12,34,345,667,56,5657,768,45,46,67 67,89,8,9,89,8,78,9,67,67 1,23,4,5,65,76,8,6,45,67 \ No newline at end of file +AB,DF,G,DF,SDF,ADA,QW,WE,ER,FD 2,45,56,7,8,9,65,3,5436,78 12,34,345,667,56,5657,768,45,46,67 67,89,8,9,89,8,78,9,67,67 1,23,4,5,65,76,8,6,45,67 diff --git a/Extract-Table-from-pdf-txt-docx/Parent/Child2/Text_Child2.txt b/Extract-Table-from-pdf-txt-docx/Parent/Child2/Text_Child2.txt index 59047f30d2b..66f18c8bad1 100644 --- a/Extract-Table-from-pdf-txt-docx/Parent/Child2/Text_Child2.txt +++ b/Extract-Table-from-pdf-txt-docx/Parent/Child2/Text_Child2.txt @@ -1 +1 @@ -AC,DXFC,GB,DCF,SCDF,BADA,QB,W,R,F,C 2,45,56,7,8,9,65,3,5436,78,34 12,34,345,667,56,5657,768,45,46,67,34 67,89,8,9,89,8,78,9,67,67,43 1,23,4,5,65,76,8,6,45,67,61 \ No newline at end of file +AC,DXFC,GB,DCF,SCDF,BADA,QB,W,R,F,C 2,45,56,7,8,9,65,3,5436,78,34 12,34,345,667,56,5657,768,45,46,67,34 67,89,8,9,89,8,78,9,67,67,43 1,23,4,5,65,76,8,6,45,67,61 diff --git a/Extract-Table-from-pdf-txt-docx/Parent/Child3/Text_Child3.txt b/Extract-Table-from-pdf-txt-docx/Parent/Child3/Text_Child3.txt index ec47af5c872..7320181fc26 100644 --- a/Extract-Table-from-pdf-txt-docx/Parent/Child3/Text_Child3.txt +++ b/Extract-Table-from-pdf-txt-docx/Parent/Child3/Text_Child3.txt @@ -1 +1 @@ -AF,FC,GFB,DW,SF,BA,Q,WS,RR,FR,CW 2,45,56,7,8,9,65,3,5436,78,34 12,34,345,667,56,5657,768,45,46,67,34 67,89,8,9,89,8,78,9,67,67,43 1,23,4,5,65,76,8,6,45,67,61 \ No newline at end of file +AF,FC,GFB,DW,SF,BA,Q,WS,RR,FR,CW 2,45,56,7,8,9,65,3,5436,78,34 12,34,345,667,56,5657,768,45,46,67,34 67,89,8,9,89,8,78,9,67,67,43 1,23,4,5,65,76,8,6,45,67,61 diff --git a/Extract-Table-from-pdf-txt-docx/main.py b/Extract-Table-from-pdf-txt-docx/main.py index d74649cd054..32428de8dd0 100644 --- a/Extract-Table-from-pdf-txt-docx/main.py +++ b/Extract-Table-from-pdf-txt-docx/main.py @@ -1,6 +1,7 @@ # %% -import pandas as pd import os + +import pandas as pd import tabula from docx.api import Document diff --git a/ExtractThumbnailFromVideo/README.md b/ExtractThumbnailFromVideo/README.md index 2726afa84dd..90a11975416 100644 --- a/ExtractThumbnailFromVideo/README.md +++ b/ExtractThumbnailFromVideo/README.md @@ -31,7 +31,7 @@ Here's an example of how to use the function: from thumbnail_extractor import extract_thumbnail # Extract a thumbnail from 'my_video.mp4' with dimensions (320, 240) -extract_thumbnail('my_video.mp4', (320, 240)) +extract_thumbnail("my_video.mp4", (320, 240)) # Replace 'my_video.mp4' with the path to your own video file and (320, 240) with your desired thumbnail dimensions. ## Required Packages @@ -45,5 +45,3 @@ To use this function, you need the following package: ``` This function is useful for generating thumbnail images from videos. It simplifies the process of creating video thumbnails for various applications. - - diff --git a/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py b/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py index 76ca3b43eb7..5896ed9c03c 100644 --- a/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py +++ b/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py @@ -1,6 +1,8 @@ -import cv2 import os +import cv2 + + def extract_thumbnail(video_path, frame_size): """ Extracts a thumbnail frame from a video and saves it as an image file. @@ -18,22 +20,30 @@ def extract_thumbnail(video_path, frame_size): Example: extract_thumbnail('my_video.mp4', (320, 240)) - + Required Packages: cv2 (pip install cv2) - + This function is useful for generating thumbnail images from videos. """ video_capture = cv2.VideoCapture(video_path) # Open the video file for reading - total_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) # Get the total number of frames in the video + total_frames = int( + video_capture.get(cv2.CAP_PROP_FRAME_COUNT) + ) # Get the total number of frames in the video middle_frame_index = total_frames // 2 # Calculate the index of the middle frame - video_capture.set(cv2.CAP_PROP_POS_FRAMES, middle_frame_index) # Seek to the middle frame + video_capture.set( + cv2.CAP_PROP_POS_FRAMES, middle_frame_index + ) # Seek to the middle frame success, frame = video_capture.read() # Read the middle frame video_capture.release() # Release the video capture object if success: - frame = cv2.resize(frame, frame_size) # Resize the frame to the specified dimensions + frame = cv2.resize( + frame, frame_size + ) # Resize the frame to the specified dimensions thumbnail_filename = f"{os.path.basename(video_path)}_thumbnail.jpg" # Create a filename for the thumbnail cv2.imwrite(thumbnail_filename, frame) # Save the thumbnail frame as an image else: - raise Exception("Could not extract frame") # Raise an exception if frame extraction fails + raise Exception( + "Could not extract frame" + ) # Raise an exception if frame extraction fails diff --git a/FIND FACTORIAL OF A NUMBER.py b/FIND FACTORIAL OF A NUMBER.py index 37bc7cd8c01..2ad83891877 100644 --- a/FIND FACTORIAL OF A NUMBER.py +++ b/FIND FACTORIAL OF A NUMBER.py @@ -1,13 +1,18 @@ # Python program to find the factorial of a number provided by the user. + def factorial(n): - if n < 0: # factorial of number less than 0 is not possible - return "Oops!Factorial Not Possible" - elif n == 0: # 0! = 1; when n=0 it returns 1 to the function which is calling it previously. - return 1 - else: - return n*factorial(n-1) -#Recursive function. At every iteration "n" is getting reduced by 1 until the "n" is equal to 0. - -n = int(input("Enter a number: ")) # asks the user for input -print(factorial(n)) # function call + if n < 0: # factorial of number less than 0 is not possible + return "Oops!Factorial Not Possible" + elif ( + n == 0 + ): # 0! = 1; when n=0 it returns 1 to the function which is calling it previously. + return 1 + else: + return n * factorial(n - 1) + + +# Recursive function. At every iteration "n" is getting reduced by 1 until the "n" is equal to 0. + +n = int(input("Enter a number: ")) # asks the user for input +print(factorial(n)) # function call diff --git a/FTP in python b/FTP in python index 60cf2c2458f..5d3007bf9fe 100644 --- a/FTP in python +++ b/FTP in python @@ -1,13 +1,13 @@ How to use FTP in Python Overview This article will show how you can use FTP in Python with the help of the -ftplib module. +ftplib module. Ftplib The ftplib module in Python allows you to write Python programs that perform a variety of automated FTP jobs. You can easily connect to a FTP server to retrieve files and process them locally. -To use the ftplib module in Python, you first have to import it into your script. +To use the ftplib module in Python, you first have to import it into your script. Open a Connection To "open" a connection to the FTP Server, you have to create the object. @@ -17,7 +17,7 @@ module. Several methods are available in two flavors: one for handling text files and another for binary files. -You can easily navigate the directory structure, manage and download files. +You can easily navigate the directory structure, manage and download files. How do I use it? This program will first connect to a FTP server (ftp.cwi.nl) and then list the files and directories in the FTP server root directory using the LIST() method. @@ -27,20 +27,20 @@ ftp = FTP('ftp.cwi.nl') # connect to host, default port ftp.login() # user anonymous, passwd anonymous@ -ftp.retrlines('LIST') # list directory contents +ftp.retrlines('LIST') # list directory contents Our second program opens a connection to 'ftp.sunet.se' as the user 'anonymous' with an email address of 'anonymous@sunet.se' It then lists the files and directories on the FTP server by using the dir() method. -The output is saved to the 'files' variable. +The output is saved to the 'files' variable. -I then use print to see the files on screen. +I then use print to see the files on screen. If I want I to change directory I would just use ftp.cwd(path) to do so. -To close the FTP connection, use the quit() method. +To close the FTP connection, use the quit() method. import ftplib ftp = ftplib.FTP('ftp.sunet.se', 'anonymous', 'anonymous@sunet.se') @@ -55,58 +55,58 @@ ftp.cwd("/pub/unix") #changing to /pub/unix Common FTP Methods FTP.connect(host[, port[, timeout]]) -Connect to the given host and port. +Connect to the given host and port. -The default port number is 21, as specified by the FTP protocol specification. +The default port number is 21, as specified by the FTP protocol specification. -It is rarely needed to specify a different port number. +It is rarely needed to specify a different port number. -This function should be called only once for each instance +This function should be called only once for each instance -It should not be called at all if a host was given when the instance was created. +It should not be called at all if a host was given when the instance was created. All other methods can only be used after a connection has been made. The optional timeout parameter specifies a timeout in seconds for the connection -attempt. +attempt. If no timeout is passed, the global default timeout setting will be used. FTP.getwelcome() -Return the welcome message sent by the server in reply to the initial connection. +Return the welcome message sent by the server in reply to the initial connection. This message sometimes contains disclaimers or help information that may be relevant to the user FTP.login([user[, passwd[, acct]]]) -Log in as the given user. +Log in as the given user. -The passwd and acct parameters are optional and default to the empty string. +The passwd and acct parameters are optional and default to the empty string. -If no user is specified, it defaults to 'anonymous'. +If no user is specified, it defaults to 'anonymous'. -If user is 'anonymous', the default passwd is 'anonymous@'. +If user is 'anonymous', the default passwd is 'anonymous@'. -This function should be called only once for each instance, after a connection -has been established. +This function should be called only once for each instance, after a connection +has been established. It should not be called at all if a host and user were given when the instance -was created. +was created. -Most FTP commands are only allowed after the client has logged in. +Most FTP commands are only allowed after the client has logged in. The acct parameter supplies “accounting information”; few systems implement this. FTP.retrbinary(command, callback[, maxblocksize[, rest]]) - -Retrieve a file in binary transfer mode. -Command should be an appropriate RETR command: 'RETR filename'. +Retrieve a file in binary transfer mode. + +Command should be an appropriate RETR command: 'RETR filename'. The callback function is called for each block of data received, with a single -string argument giving the data block. +string argument giving the data block. The optional maxblocksize argument specifies the maximum chunk size to read on the low-level socket object created to do the actual transfer. @@ -115,20 +115,20 @@ A reasonable default is chosen. rest means the same thing as in the transfercmd( method. FTP.retrlines(command[, callback]) -Retrieve a file or directory listing in ASCII transfer mode. +Retrieve a file or directory listing in ASCII transfer mode. -Command should be an appropriate RETR command or a command such as LIST, NLST or +Command should be an appropriate RETR command or a command such as LIST, NLST or MLSD. -LIST retrieves a list of files and information about those files. +LIST retrieves a list of files and information about those files. -NLST retrieves a list of file names. +NLST retrieves a list of file names. On some servers, MLSD retrieves a machine readable list of files and information -about those files. +about those files. The callback function is called for each line with a string argument containing -the line with the trailing CRLF stripped. +the line with the trailing CRLF stripped. The default callback prints the line to sys.stdout. FTP.dir(argument[, ...]) @@ -137,19 +137,19 @@ Produce a directory listing as returned by the LIST command, printing it to standard output. The optional argument is a directory to list (default is the current server -directory). +directory). -Multiple arguments can be used to pass non-standard options to the LIST command. +Multiple arguments can be used to pass non-standard options to the LIST command. -If the last argument is a function, it is used as a callback function as for -retrlines(); the default prints to sys.stdout. +If the last argument is a function, it is used as a callback function as for +retrlines(); the default prints to sys.stdout. This method returns None. FTP.delete(filename) -Remove the file named filename from the server. +Remove the file named filename from the server. -If successful, returns the text of the response, otherwise raises error_perm on +If successful, returns the text of the response, otherwise raises error_perm on permission errors or error_reply on other errors. FTP.cwd(pathname) @@ -162,19 +162,19 @@ FTP.pwd() Return the pathname of the current directory on the server. FTP.quit() -Send a QUIT command to the server and close the connection. +Send a QUIT command to the server and close the connection. This is the “polite” way to close a connection, but it may raise an exception if -the server responds with an error to the QUIT command. +the server responds with an error to the QUIT command. This implies a call to the close() method which renders the FTP instance useless for subsequent calls. FTP.close() -Close the connection unilaterally. +Close the connection unilaterally. -This should not be applied to an already closed connection such as after a -successful call to quit(). +This should not be applied to an already closed connection such as after a +successful call to quit(). After this call the FTP instance should not be used any more. diff --git a/Face and eye Recognition/face_recofnation_first.py b/Face and eye Recognition/face_recofnation_first.py index c60faba84db..e50e6fa24f3 100644 --- a/Face and eye Recognition/face_recofnation_first.py +++ b/Face and eye Recognition/face_recofnation_first.py @@ -49,4 +49,4 @@ def detect_faces_and_eyes(): if __name__ == "__main__": # Call the main function - detect_faces_and_eyes() \ No newline at end of file + detect_faces_and_eyes() diff --git a/Face_Mask_detection (haarcascade)/mask_detection.py b/Face_Mask_detection (haarcascade)/mask_detection.py index 9ba4c34734b..4ba103c21ca 100644 --- a/Face_Mask_detection (haarcascade)/mask_detection.py +++ b/Face_Mask_detection (haarcascade)/mask_detection.py @@ -1,7 +1,7 @@ +import cv2 +import numpy as np import tensorflow.keras from PIL import Image, ImageOps -import numpy as np -import cv2 # import os @@ -22,7 +22,7 @@ cv2.imshow("webcam", img) faces = faceCascade.detectMultiScale(img, 1.1, 4) - for (x, y, w, h) in faces: + for x, y, w, h in faces: crop_img = img[y : y + h, x : x + w] crop_img = cv2.resize(crop_img, (224, 224)) normalized_image_array = (crop_img.astype(np.float32) / 127.0) - 1 diff --git a/FibonacciNumbersWithGenerators.py b/FibonacciNumbersWithGenerators.py index 5d090a0a7ea..15771630222 100644 --- a/FibonacciNumbersWithGenerators.py +++ b/FibonacciNumbersWithGenerators.py @@ -1,10 +1,10 @@ -def fibonacci_generator(n = None): +def fibonacci_generator(n=None): """ - Generating function up to n fibonacci numbers iteratively - Params: - n: int - Return: - int + Generating function up to n fibonacci numbers iteratively + Params: + n: int + Return: + int """ f0, f1 = 0, 1 yield f1 @@ -14,5 +14,6 @@ def fibonacci_generator(n = None): f0, f1 = f1, fn n -= 1 + for n_fibo in fibonacci_generator(7): print(n_fibo) diff --git a/Find current weather of any city using openweathermap API.py b/Find current weather of any city using openweathermap API.py index cb2659c122f..06407b6f1a8 100644 --- a/Find current weather of any city using openweathermap API.py +++ b/Find current weather of any city using openweathermap API.py @@ -1,72 +1,76 @@ -# Python program to find current -# weather details of any city -# using openweathermap api +# Python program to find current +# weather details of any city +# using openweathermap api -# import required modules -import requests, json +import json -# Enter your API key here +# import required modules +import requests + +# Enter your API key here api_key = "Your_API_Key" -# base_url variable to store url +# base_url variable to store url base_url = "http://api.openweathermap.org/data/2.5/weather?" -# Give city name -city_name = input("Enter city name : ") - -# complete_url variable to store -# complete url address -complete_url = base_url + "appid=" + api_key + "&q=" + city_name - -# get method of requests module -# return response object -response = requests.get(complete_url) - -# json method of response object -# convert json format data into -# python format data -x = response.json() - -# Now x contains list of nested dictionaries -# Check the value of "cod" key is equal to -# "404", means city is found otherwise, -# city is not found -if x["cod"] != "404": - - # store the value of "main" - # key in variable y - y = x["main"] - - # store the value corresponding - # to the "temp" key of y - current_temperature = y["temp"] - - # store the value corresponding - # to the "pressure" key of y - current_pressure = y["pressure"] - - # store the value corresponding - # to the "humidity" key of y - current_humidiy = y["humidity"] - - # store the value of "weather" - # key in variable z - z = x["weather"] - - # store the value corresponding - # to the "description" key at - # the 0th index of z - weather_description = z[0]["description"] - - # print following values - print(" Temperature (in kelvin unit) = " + - str(current_temperature) + - "\n atmospheric pressure (in hPa unit) = " + - str(current_pressure) + - "\n humidity (in percentage) = " + - str(current_humidiy) + - "\n description = " + - str(weather_description)) - -else: - print(" City Not Found ") +# Give city name +city_name = input("Enter city name : ") + +# complete_url variable to store +# complete url address +complete_url = base_url + "appid=" + api_key + "&q=" + city_name + +# get method of requests module +# return response object +response = requests.get(complete_url) + +# json method of response object +# convert json format data into +# python format data +x = response.json() + +# Now x contains list of nested dictionaries +# Check the value of "cod" key is equal to +# "404", means city is found otherwise, +# city is not found +if x["cod"] != "404": + + # store the value of "main" + # key in variable y + y = x["main"] + + # store the value corresponding + # to the "temp" key of y + current_temperature = y["temp"] + + # store the value corresponding + # to the "pressure" key of y + current_pressure = y["pressure"] + + # store the value corresponding + # to the "humidity" key of y + current_humidiy = y["humidity"] + + # store the value of "weather" + # key in variable z + z = x["weather"] + + # store the value corresponding + # to the "description" key at + # the 0th index of z + weather_description = z[0]["description"] + + # print following values + print( + " Temperature (in kelvin unit) = " + + str(current_temperature) + + "\n atmospheric pressure (in hPa unit) = " + + str(current_pressure) + + "\n humidity (in percentage) = " + + str(current_humidiy) + + "\n description = " + + str(weather_description), + ) + +else: + print(" City Not Found ") diff --git a/FindingResolutionOfAnImage.py b/FindingResolutionOfAnImage.py index 9c6336d8d1d..333a1effb2a 100644 --- a/FindingResolutionOfAnImage.py +++ b/FindingResolutionOfAnImage.py @@ -1,24 +1,25 @@ def jpeg_res(filename): - """"This function prints the resolution of the jpeg image file passed into it""" + """ "This function prints the resolution of the jpeg image file passed into it""" - # open image for reading in binary mode - with open(filename,'rb') as img_file: + # open image for reading in binary mode + with open(filename, "rb") as img_file: - # height of image (in 2 bytes) is at 164th position - img_file.seek(163) + # height of image (in 2 bytes) is at 164th position + img_file.seek(163) - # read the 2 bytes - a = img_file.read(2) + # read the 2 bytes + a = img_file.read(2) - # calculate height - height = (a[0] << 8) + a[1] + # calculate height + height = (a[0] << 8) + a[1] - # next 2 bytes is width - a = img_file.read(2) + # next 2 bytes is width + a = img_file.read(2) - # calculate width - width = (a[0] << 8) + a[1] + # calculate width + width = (a[0] << 8) + a[1] + + print("The resolution of the image is", width, "x", height) - print("The resolution of the image is",width,"x",height) jpeg_res("img1.jpg") diff --git a/FizzBuzz.py b/FizzBuzz.py index 59c78fad2a9..cf8caba4c4e 100644 --- a/FizzBuzz.py +++ b/FizzBuzz.py @@ -18,5 +18,4 @@ def FizzBuzz(num): print(i) - FizzBuzz(20) # prints FizzBuzz up to 20 diff --git a/Flappy Bird - created with tkinter/.gitignore b/Flappy Bird - created with tkinter/.gitignore index 45f6d8e74e1..0b7088ec633 100644 --- a/Flappy Bird - created with tkinter/.gitignore +++ b/Flappy Bird - created with tkinter/.gitignore @@ -1 +1 @@ -Data \ No newline at end of file +Data diff --git a/Flappy Bird - created with tkinter/Background.py b/Flappy Bird - created with tkinter/Background.py index 78dc415a9f4..48254e19dfe 100644 --- a/Flappy Bird - created with tkinter/Background.py +++ b/Flappy Bird - created with tkinter/Background.py @@ -1,4 +1,4 @@ -from tkinter import Tk, Canvas +from tkinter import Canvas, Tk from PIL.Image import open as openImage from PIL.ImageTk import PhotoImage @@ -28,7 +28,10 @@ def __init__(self, tk_instance, *geometry, fp="background.png", animation_speed= # Inicializa o construtor da classe Canvas Canvas.__init__( - self, master=tk_instance, width=self.__width, height=self.__height + self, + master=tk_instance, + width=self.__width, + height=self.__height, ) # Carrega a imagem que será usada no plano de fundo @@ -41,21 +44,25 @@ def __init__(self, tk_instance, *geometry, fp="background.png", animation_speed= # Cria uma imagem que será fixa, ou seja, que não fará parte da animação e serve em situações de bugs na animação self.__background_default = self.create_image( - self.__width // 2, self.__height // 2, image=self.__bg_image + self.__width // 2, + self.__height // 2, + image=self.__bg_image, ) # Cria as imagens que serão utilizadas na animação do background self.__background.append( self.create_image( - self.__width // 2, self.__height // 2, image=self.__bg_image - ) + self.__width // 2, + self.__height // 2, + image=self.__bg_image, + ), ) self.__background.append( self.create_image( self.__width + (self.__width // 2), self.__height // 2, image=self.__bg_image, - ) + ), ) def getBackgroundID(self): @@ -66,7 +73,11 @@ def getBackgroundID(self): @staticmethod def getPhotoImage( - image=None, image_path=None, width=None, height=None, closeAfter=False + image=None, + image_path=None, + width=None, + height=None, + closeAfter=False, ): """ Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image @@ -127,21 +138,25 @@ def reset(self): # Cria uma imagem que será fixa, ou seja, que não fará parte da animação e serve em situações de bugs na animação self.__background_default = self.create_image( - self.__width // 2, self.__height // 2, image=self.__bg_image + self.__width // 2, + self.__height // 2, + image=self.__bg_image, ) # Cria as imagens que serão utilizadas na animação do background self.__background.append( self.create_image( - self.__width // 2, self.__height // 2, image=self.__bg_image - ) + self.__width // 2, + self.__height // 2, + image=self.__bg_image, + ), ) self.__background.append( self.create_image( self.__width + (self.__width // 2), self.__height // 2, image=self.__bg_image, - ) + ), ) def run(self): @@ -168,7 +183,7 @@ def run(self): # Cria uma nova imagem a partir da última imagem da animação width = self.bbox(self.__background[0])[2] + self.__width // 2 self.__background.append( - self.create_image(width, self.__height // 2, image=self.__bg_image) + self.create_image(width, self.__height // 2, image=self.__bg_image), ) # Executa novamente o método depois de um certo tempo diff --git a/Flappy Bird - created with tkinter/Bird.py b/Flappy Bird - created with tkinter/Bird.py index 56fdcd1d31c..541bca8f5c3 100644 --- a/Flappy Bird - created with tkinter/Bird.py +++ b/Flappy Bird - created with tkinter/Bird.py @@ -27,14 +27,14 @@ def __init__( *screen_geometry, fp="bird.png", event="", - descend_speed=5 + descend_speed=5, ): # Verifica se "background" é uma instância de Background e se o "gamerover_method" é chamável if not isinstance(background, Background): raise TypeError( - "The background argument must be an instance of Background." + "The background argument must be an instance of Background.", ) if not callable(gameover_function): raise TypeError("The gameover_method argument must be a callable object.") @@ -139,7 +139,11 @@ def getTag(self): @staticmethod def getPhotoImage( - image=None, image_path=None, width=None, height=None, closeAfter=False + image=None, + image_path=None, + width=None, + height=None, + closeAfter=False, ): """ Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image diff --git a/Flappy Bird - created with tkinter/Flappy Bird.py b/Flappy Bird - created with tkinter/Flappy Bird.py index 308a7c6ea70..5c49b622d6e 100644 --- a/Flappy Bird - created with tkinter/Flappy Bird.py +++ b/Flappy Bird - created with tkinter/Flappy Bird.py @@ -4,7 +4,7 @@ import os.path from datetime import timedelta from time import time -from tkinter import Tk, Button +from tkinter import Button, Tk from Background import Background from Bird import Bird @@ -43,7 +43,7 @@ def __init__(self): # Configura a janela do programa self.title(self.window_name) - self.geometry("{}x{}".format(self.__width, self.__height)) + self.geometry(f"{self.__width}x{self.__height}") self.resizable(*self.window_rz) self.attributes("-fullscreen", self.window_fullscreen) self["bg"] = "black" @@ -52,7 +52,7 @@ def __init__(self): for file in self.images_fp: if not os.path.exists(file): raise FileNotFoundError( - "The following file was not found:\n{}".format(file) + f"The following file was not found:\n{file}", ) # Carrega a imagem do botão para começar o jogo @@ -144,7 +144,7 @@ def createMenuButtons(self): (self.__width // 2) - width // 1.5, int(self.__height / 100 * self.button_position_y), window=startButton, - ) + ), ) # Cria um botão para sair do jogo @@ -164,7 +164,7 @@ def createMenuButtons(self): (self.__width // 2) + width // 1.5, int(self.__height / 100 * self.button_position_y), window=exitButton, - ) + ), ) def createScoreBoard(self): @@ -304,7 +304,8 @@ def init(self): self.__background.focus_force() # Define evento para trocar o modo de janela para "fullscreen" ou "window" self.__background.bind( - self.window_fullscreen_event, self.changeFullscreenOption + self.window_fullscreen_event, + self.changeFullscreenOption, ) # Define evento para começar o jogo self.__background.bind(self.window_start_event, self.start) diff --git a/Flappy Bird - created with tkinter/README.md b/Flappy Bird - created with tkinter/README.md index 25dbb8e6060..285b1319d3d 100644 --- a/Flappy Bird - created with tkinter/README.md +++ b/Flappy Bird - created with tkinter/README.md @@ -4,7 +4,7 @@ Enjoy and do give feedback
Warning: If the game is too slow, lower the game resolution in Data/settings.json # Requirements: -Tkinter +Tkinter ```bash pip install tkinter ``` diff --git a/Flappy Bird - created with tkinter/Settings.py b/Flappy Bird - created with tkinter/Settings.py index 33eb2c1da6f..923826f3ce6 100644 --- a/Flappy Bird - created with tkinter/Settings.py +++ b/Flappy Bird - created with tkinter/Settings.py @@ -1,9 +1,8 @@ import os -from json import dumps -from json import loads +from json import dumps, loads -class Settings(object): +class Settings: """ Classe com todas as configurações do jogo """ @@ -81,7 +80,7 @@ def setOptions(self): # Tenta abrir o arquivo parar leitura try: - file = open(self.settings_fp, "r") + file = open(self.settings_fp) data = loads(file.read()) file.close() diff --git a/Flappy Bird - created with tkinter/Tubes.py b/Flappy Bird - created with tkinter/Tubes.py index a6021f69ef5..b2fbcfa929c 100644 --- a/Flappy Bird - created with tkinter/Tubes.py +++ b/Flappy Bird - created with tkinter/Tubes.py @@ -23,17 +23,17 @@ def __init__( score_function=None, *screen_geometry, fp=("tube.png", "tube_mourth"), - animation_speed=50 + animation_speed=50, ): # Verifica os parâmetros passados e lança um erro caso algo esteja incorreto if not isinstance(background, Background): raise TypeError( - "The background argument must be an instance of Background." + "The background argument must be an instance of Background.", ) if not len(fp) == 2: raise TypeError( - "The parameter fp should be a sequence containing the path of the images of the tube body and the tube mouth." + "The parameter fp should be a sequence containing the path of the images of the tube body and the tube mouth.", ) if not isinstance(bird, Bird): raise TypeError("The birdargument must be an instance of Bird.") @@ -76,7 +76,7 @@ def __init__( width=self.__imageWidth, height=self.__imageHeight, closeAfter=True, - )[0] + )[0], ) # Carrega imagem do corpo do tubo @@ -85,7 +85,7 @@ def __init__( image_path=self.image_path[0], width=self.__imageWidth, height=self.__imageHeight, - )[1] + )[1], ) # Calcula a distância mínima inicial entre os tubos @@ -116,8 +116,10 @@ def createNewTubes(self): # Cria e adiciona à lista do corpo do tubo de cima, a boca do tubo tube1.append( self.__background.create_image( - width, height, image=self.__background.tubeImages[1] - ) + width, + height, + image=self.__background.tubeImages[1], + ), ) # Cria uma nova imagem na lista de imagens com a altura sendo igual a posição Y do tubo de cima @@ -128,7 +130,7 @@ def createNewTubes(self): width=self.__imageWidth, height=height, )[0], - ] + ], ) # Define a posição Y do corpo do tubo de cima @@ -137,8 +139,10 @@ def createNewTubes(self): # Cria e adiciona à lista do corpo do tubo de cima, o corpo do tubo tube1.append( self.__background.create_image( - width, y, image=self.__background.tubeImages[0][-1][0] - ) + width, + y, + image=self.__background.tubeImages[0][-1][0], + ), ) ############################################################################################################### @@ -153,8 +157,10 @@ def createNewTubes(self): # Cria e adiciona à lista do corpo do tubo de baixo, a boca do tubo tube2.append( self.__background.create_image( - width, height, image=self.__background.tubeImages[1] - ) + width, + height, + image=self.__background.tubeImages[1], + ), ) # Define a altura da imagem do corpo do tubo de baixo @@ -166,7 +172,7 @@ def createNewTubes(self): image=self.__background.tubeImages[2], width=self.__imageWidth, height=height, - )[0] + )[0], ) # Define a posição Y do corpo do tubo de baixo @@ -175,8 +181,10 @@ def createNewTubes(self): # Cria e adiciona à lista do corpo do tubo de baixo, o corpo do tubo tube2.append( self.__background.create_image( - width, y, image=self.__background.tubeImages[0][-1][1] - ) + width, + y, + image=self.__background.tubeImages[0][-1][1], + ), ) # Adiciona à lista de tubos os tubos de cima e de baixo da posição X @@ -201,7 +209,11 @@ def deleteAll(self): @staticmethod def getPhotoImage( - image=None, image_path=None, width=None, height=None, closeAfter=False + image=None, + image_path=None, + width=None, + height=None, + closeAfter=False, ): """ Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image diff --git a/Generate a random number between 0 to 9.py b/Generate a random number between 0 to 9.py index a035d9f8502..c304fa85b1d 100644 --- a/Generate a random number between 0 to 9.py +++ b/Generate a random number between 0 to 9.py @@ -3,4 +3,4 @@ # importing the random module import random -print(random.randint(0,9)) +print(random.randint(0, 9)) diff --git a/Google_Image_Downloader/create_dir.py b/Google_Image_Downloader/create_dir.py index 0734f836802..dab579db1e4 100644 --- a/Google_Image_Downloader/create_dir.py +++ b/Google_Image_Downloader/create_dir.py @@ -10,14 +10,9 @@ project directory. """ -from os import chdir -from os import makedirs -from os import removedirs -from os import rename -from os.path import exists -from os.path import pardir -from shutil import copytree -from shutil import move +from os import chdir, makedirs, removedirs, rename +from os.path import exists, pardir +from shutil import copytree, move # Creates a directory diff --git a/Google_Image_Downloader/image_grapper.py b/Google_Image_Downloader/image_grapper.py index a922894a8d0..f39e8b4f2f8 100644 --- a/Google_Image_Downloader/image_grapper.py +++ b/Google_Image_Downloader/image_grapper.py @@ -1,20 +1,16 @@ #!/usr/bin/python -# -*- coding: utf-8 -*- # importing required libraries import json -from os import chdir, system -from os import walk -from os.path import curdir -from os.path import pardir +import ssl +from os import chdir, system, walk +from os.path import curdir, pardir from urllib.parse import urlencode -from urllib.request import urlopen, Request +from urllib.request import Request, urlopen import requests -import ssl from bs4 import BeautifulSoup from create_dir import create_directory - ssl._create_default_https_context = ssl._create_unverified_context GOOGLE_IMAGE = ( @@ -94,7 +90,7 @@ def download_wallpapers_1080p(): # print('https://wallpaperscraft.com/image/' + re[31:-10] + '_' + re[-9:] + '.jpg') temp.add( - "https://wallpaperscraft.com/image/" + re[31:-10] + "_" + re[-9:] + ".jpg" + "https://wallpaperscraft.com/image/" + re[31:-10] + "_" + re[-9:] + ".jpg", ) # Goes to Each link and downloads high resolution images @@ -113,7 +109,7 @@ def download_wallpapers_1080p(): ################### def view_images_directory(): - for (folders, subfolder, files) in walk(curdir): + for folders, subfolder, files in walk(curdir): for folder in subfolder: print(folder) return True @@ -135,7 +131,7 @@ def quit(): print( """ -------------------------***Thank You For Using***------------------------- - """ + """, ) return False @@ -145,7 +141,7 @@ def quit(): print( """ ***********[First Creating Folder To Save Your Images}*********** - """ + """, ) create_directory("Images") @@ -162,7 +158,7 @@ def quit(): 4. Set directory 5. Exit -------------------------*******------------------------- - """ + """, ) choice = input() try: diff --git a/Grocery calculator.py b/Grocery calculator.py index eedb5c7ea15..6ab49fc1b8b 100644 --- a/Grocery calculator.py +++ b/Grocery calculator.py @@ -1,45 +1,47 @@ -'''This will be a Python script that functions as a grocery calculator. It will take in key-value pairs for items +"""This will be a Python script that functions as a grocery calculator. It will take in key-value pairs for items and their prices, and return the subtotal and total, and can print out the list for you for when you're ready to -take it to the store!''' +take it to the store!""" -'''Algorithm: +"""Algorithm: 1. User enters key-value pairs that are added into a dict. -2. Users tells script to return total, subtotal, and key-value pairs in a nicely formatted list.''' +2. Users tells script to return total, subtotal, and key-value pairs in a nicely formatted list.""" -#Object = GroceryList -#Methods = addToList, Total, Subtotal, returnList + +# Object = GroceryList +# Methods = addToList, Total, Subtotal, returnList class GroceryList(dict): - def __init__(self): - self = {} + def __init__(self): + self = {} + + def addToList(self, item, price): + + self.update({item: price}) - def addToList(self, item, price): - - self.update({item:price}) + def Total(self): + total = 0 + for items in self: + total += (self[items]) * 0.07 + (self[items]) + return total - def Total(self): - total = 0 - for items in self: - total += (self[items])*.07 + (self[items]) - return total + def Subtotal(self): + subtotal = 0 + for items in self: + subtotal += self[items] + return subtotal - def Subtotal(self): - subtotal = 0 - for items in self: - subtotal += self[items] - return subtotal + def returnList(self): + return self - def returnList(self): - return self -'''Test list should return: +"""Test list should return: Total = 10.70 Subtotal = 10 returnList = {"milk":4, "eggs":3, "kombucha":3} -''' +""" List1 = GroceryList() -List1.addToList("milk",4) +List1.addToList("milk", 4) List1.addToList("eggs", 3) List1.addToList("kombucha", 3) @@ -48,16 +50,16 @@ def returnList(self): print(List1.Subtotal()) print(List1.returnList()) -#***************************************************** +# ***************************************************** print() -#***************************************************** +# ***************************************************** List2 = GroceryList() -List2.addToList('cheese', 7.49) -List2.addToList('wine', 25.36) -List2.addToList('steak', 17.64) +List2.addToList("cheese", 7.49) +List2.addToList("wine", 25.36) +List2.addToList("steak", 17.64) print(List2.Total()) print(List2.Subtotal()) diff --git a/GroupSms_Way2.py b/GroupSms_Way2.py index 04f9f562249..8cd542736f8 100644 --- a/GroupSms_Way2.py +++ b/GroupSms_Way2.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import sys from getpass import getpass @@ -21,7 +19,7 @@ # Logging into the SMS Site url = "http://site24.way2sms.com/Login1.action?" -data = "username={0}&password={1}&Submit=Sign+in".format(username, passwd) +data = f"username={username}&password={passwd}&Submit=Sign+in" # For Cookies: cj = cookielib.CookieJar() @@ -33,12 +31,12 @@ "User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 " "Safari/537.36", - ) + ), ] try: usock = opener.open(url, data) -except IOError: +except OSError: print("Error while logging in.") sys.exit(1) @@ -46,18 +44,20 @@ send_sms_url = "http://site24.way2sms.com/smstoss.action?" opener.addheaders = [ - ("Referer", "http://site25.way2sms.com/sendSMS?Token=%s" % jession_id) + ("Referer", "http://site25.way2sms.com/sendSMS?Token=%s" % jession_id), ] try: for number in num: send_sms_data = ( - "ssaction=ss&Token={0}&mobile={1}&message={2}&msgLen=136".format( - jession_id, number, message + "ssaction=ss&Token={}&mobile={}&message={}&msgLen=136".format( + jession_id, + number, + message, ) ) sms_sent_page = opener.open(send_sms_url, send_sms_data) -except IOError: +except OSError: print("Error while sending message") print("SMS has been sent.") diff --git a/Guessing_Game.py b/Guessing_Game.py index aaeb895384b..292f59ec7b4 100644 --- a/Guessing_Game.py +++ b/Guessing_Game.py @@ -32,12 +32,12 @@ def guessing_game(GUESS_RANGE, GUESS_LIMIT): elif GUESS_LIMIT == 0 and not done: # Last chance to guess if GUESS == RANDOM: print( - f"You nailed it! However, it took you all the {ATTEMPTS_ALLOWED} attempts." + f"You nailed it! However, it took you all the {ATTEMPTS_ALLOWED} attempts.", ) else: print( f"GAME OVER! It took you more than {ATTEMPTS_ALLOWED} attempts. " - f"The correct number is {RANDOM}." + f"The correct number is {RANDOM}.", ) diff --git a/Hand-Motion-Detection/hand_motion_recognizer.py b/Hand-Motion-Detection/hand_motion_recognizer.py index 59efb53c8ef..501bdcee3d1 100644 --- a/Hand-Motion-Detection/hand_motion_recognizer.py +++ b/Hand-Motion-Detection/hand_motion_recognizer.py @@ -1,48 +1,54 @@ -import mediapipe as mp import cv2 +import mediapipe as mp mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands cap = cv2.VideoCapture(0) -with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5) as hands: +with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5) as hands: while cap.isOpened(): ret, frame = cap.read() - + # BGR 2 RGB image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) - + # Flip on horizontal image = cv2.flip(image, 1) - + # Set flag image.flags.writeable = False - + # Detections results = hands.process(image) - + # Set flag to true image.flags.writeable = True - + # RGB 2 BGR image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) - + # Detections print(results) - + # Rendering results if results.multi_hand_landmarks: for num, hand in enumerate(results.multi_hand_landmarks): - mp_drawing.draw_landmarks(image, hand, mp_hands.HAND_CONNECTIONS, - mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4), - mp_drawing.DrawingSpec(color=(250, 44, 250), thickness=2, circle_radius=2), - ) - - - cv2.imshow('Hand Tracking', image) - - if cv2.waitKey(10) & 0xFF == ord('q'): + mp_drawing.draw_landmarks( + image, + hand, + mp_hands.HAND_CONNECTIONS, + mp_drawing.DrawingSpec( + color=(121, 22, 76), thickness=2, circle_radius=4 + ), + mp_drawing.DrawingSpec( + color=(250, 44, 250), thickness=2, circle_radius=2 + ), + ) + + cv2.imshow("Hand Tracking", image) + + if cv2.waitKey(10) & 0xFF == ord("q"): break cap.release() diff --git a/Hand-Motion-Detection/requirements.txt b/Hand-Motion-Detection/requirements.txt index 9777fd9bba9..42a5712900b 100644 --- a/Hand-Motion-Detection/requirements.txt +++ b/Hand-Motion-Detection/requirements.txt @@ -1,3 +1,3 @@ +mediapipe==0.10.9 numpy==1.26.4 opencv_python==4.9.0.80 -mediapipe==0.10.9 diff --git a/HangMan Game b/HangMan Game index 56d106f8c88..d8a16ab2661 100644 --- a/HangMan Game +++ b/HangMan Game @@ -19,13 +19,13 @@ while True: print(incl.won+'\a') break inp=input('\nGuess an Alphabet or a Sequence of Alphabets: ').upper() - + if inp in inp_lst: print('......................................................................Already Tried') continue else: inp_lst.append(inp) - + t=0 indx=[] if inp in name: @@ -37,13 +37,13 @@ while True: temp=temp[t:] else: break - + for j in range(len(indx)): for i in range(len(inp)): result_lst[indx[j]]=inp[i]+' ' indx[j]+=1 i+=1 - + result_str=str().join(result_lst) print('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Excellent~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print(f'\nYou have to Guess a Human Name of {len(name)} Alphabets:\t{result_str}\n') @@ -54,7 +54,7 @@ while True: print(f'\nYou have to Guess a Human Name of {len(name)} Alphabets:\t{result_str}\n') print(incl.draw[chances]) chances=chances-1 - + if chances!=0: print('Tried Inputs:',tuple(sorted(set(inp_lst)))) print(f'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~You were left with {chances} Chances~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') @@ -62,7 +62,7 @@ while True: print(f'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Correct Answer: {name} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print(incl.lose+'\a') break - + try: if int(input('To play the Game Again Press "1" & "0" to Quit: '))!=1: exit('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Thank You~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') diff --git a/Hangman.py b/Hangman.py index 27b82db2c4a..9f25514c4b6 100644 --- a/Hangman.py +++ b/Hangman.py @@ -1,8 +1,7 @@ # importing the time module -import time - # importing the random module import random +import time # welcoming the user name = input("What is your name? ") @@ -15,8 +14,8 @@ print("Start guessing...\nHint:It is a fruit") time.sleep(0.5) -someWords = """apple banana mango strawberry -orange grape pineapple apricot lemon coconut watermelon +someWords = """apple banana mango strawberry +orange grape pineapple apricot lemon coconut watermelon cherry papaya berry peach lychee muskmelon""" someWords = someWords.split(" ") diff --git a/Hotel-Management.py b/Hotel-Management.py index edfdec0934a..6b147d66c7d 100644 --- a/Hotel-Management.py +++ b/Hotel-Management.py @@ -1,36 +1,30 @@ - def menu(): options = { - 1 : { - "title" : "Add new customer details", - "method": lambda : add() - }, - - 2 : { - "title" : "Modify already existing customer details", - "method": lambda : modify() - }, - - 3 : { - "title" : "Search customer details", - "method": lambda : search() - }, - - 4 : { - "title" : "View all customer details", - "method": lambda : view() - }, - - 5 : { - "title" : "Delete customer details", - "method": lambda : remove() - }, - - 6 : { - "title" : "Exit the program", - "method": lambda : exit() - } + 1: { + "title": "Add new customer details", + "method": lambda: add(), + }, + 2: { + "title": "Modify already existing customer details", + "method": lambda: modify(), + }, + 3: { + "title": "Search customer details", + "method": lambda: search(), + }, + 4: { + "title": "View all customer details", + "method": lambda: view(), + }, + 5: { + "title": "Delete customer details", + "method": lambda: remove(), + }, + 6: { + "title": "Exit the program", + "method": lambda: exit(), + }, } print(f"\n\n{' '*25}Welcome to Hotel Database Management Software\n\n") @@ -39,7 +33,7 @@ def menu(): print(f"{num}: {option.get('title')}") print() - options.get( int(input("Enter your choice(1-6): ")) ).get("method")() + options.get(int(input("Enter your choice(1-6): "))).get("method")() def add(): @@ -87,7 +81,7 @@ def add(): print("Online payment") print("") - with open("Management.txt", "r") as File: + with open("Management.txt") as File: string = File.read() string = string.replace("'", '"') dictionary = json.loads(string) @@ -123,8 +117,8 @@ def add(): exit_menu() -import os import json +import os filecheck = os.path.isfile("Management.txt") if not filecheck: @@ -143,7 +137,7 @@ def add(): def modify(): - with open("Management.txt", "r") as File: + with open("Management.txt") as File: string = File.read() string = string.replace("'", '"') dictionary = json.loads(string) @@ -167,7 +161,7 @@ def modify(): print() with open("Management.txt", "w", encoding="utf-8") as File: - + match choice: case 1: category = "First_Name" diff --git a/ImageDownloader/img_downloader.py b/ImageDownloader/img_downloader.py index 9844635cdaf..506e9f6608c 100644 --- a/ImageDownloader/img_downloader.py +++ b/ImageDownloader/img_downloader.py @@ -2,7 +2,10 @@ def ImageDownloader(url): - import os, re, requests + import os + import re + + import requests response = requests.get(url) text = response.text @@ -11,14 +14,14 @@ def ImageDownloader(url): img_addrs = re.findall(p, text) for i in img_addrs: - os.system("wget {}".format(i)) + os.system(f"wget {i}") return "DONE" # USAGE print("Hey!! Welcome to the Image downloader...") -link=input("Please enter the url from where you want to download the image..") +link = input("Please enter the url from where you want to download the image..") # now you can give the input at run time and get download the images. # https://www.123rf.com/stock-photo/spring_color.html?oriSearch=spring&ch=spring&sti=oazo8ueuz074cdpc48 ImageDownloader(link) diff --git a/Image_resize.py b/Image_resize.py index 9c6336d8d1d..333a1effb2a 100644 --- a/Image_resize.py +++ b/Image_resize.py @@ -1,24 +1,25 @@ def jpeg_res(filename): - """"This function prints the resolution of the jpeg image file passed into it""" + """ "This function prints the resolution of the jpeg image file passed into it""" - # open image for reading in binary mode - with open(filename,'rb') as img_file: + # open image for reading in binary mode + with open(filename, "rb") as img_file: - # height of image (in 2 bytes) is at 164th position - img_file.seek(163) + # height of image (in 2 bytes) is at 164th position + img_file.seek(163) - # read the 2 bytes - a = img_file.read(2) + # read the 2 bytes + a = img_file.read(2) - # calculate height - height = (a[0] << 8) + a[1] + # calculate height + height = (a[0] << 8) + a[1] - # next 2 bytes is width - a = img_file.read(2) + # next 2 bytes is width + a = img_file.read(2) - # calculate width - width = (a[0] << 8) + a[1] + # calculate width + width = (a[0] << 8) + a[1] + + print("The resolution of the image is", width, "x", height) - print("The resolution of the image is",width,"x",height) jpeg_res("img1.jpg") diff --git a/Industrial_developed_hangman/Makefile b/Industrial_developed_hangman/Makefile index e4e05f18fb2..4686cd40b9b 100644 --- a/Industrial_developed_hangman/Makefile +++ b/Industrial_developed_hangman/Makefile @@ -11,4 +11,4 @@ build: python src/hangman/main.py install: pip install poetry - poetry install \ No newline at end of file + poetry install diff --git a/Industrial_developed_hangman/README.md b/Industrial_developed_hangman/README.md index 71fb5bd5724..614b58851ce 100644 --- a/Industrial_developed_hangman/README.md +++ b/Industrial_developed_hangman/README.md @@ -9,4 +9,4 @@ example of programm run: ![img.png](recorces/img.png) -also makefile have lint command to lint source code \ No newline at end of file +also makefile have lint command to lint source code diff --git a/Industrial_developed_hangman/src/hangman/main.py b/Industrial_developed_hangman/src/hangman/main.py index b2a7e780ac3..5365f8db20e 100644 --- a/Industrial_developed_hangman/src/hangman/main.py +++ b/Industrial_developed_hangman/src/hangman/main.py @@ -11,7 +11,7 @@ DEBUG = False success_code = 200 request_timeout = 1000 -data_path = Path(__file__).parent.parent.parent / 'Data' +data_path = Path(__file__).parent.parent.parent / "Data" year = 4800566455 @@ -43,7 +43,9 @@ def print_right(text: str, print_function: Callable[[str], None]) -> None: print_function(Style.RESET_ALL + Fore.GREEN + text) -def parse_word_from_local(choice_function: Callable[[List[str]], str] = random.choice) -> str: +def parse_word_from_local( + choice_function: Callable[[list[str]], str] = random.choice +) -> str: # noqa: DAR201 """ Parse word from local file. @@ -53,13 +55,15 @@ def parse_word_from_local(choice_function: Callable[[List[str]], str] = random.c :raises FileNotFoundError: file to read words not found. """ try: - with open(data_path / 'local_words.txt', encoding='utf8') as words_file: - return choice_function(words_file.read().split('\n')) + with open(data_path / "local_words.txt", encoding="utf8") as words_file: + return choice_function(words_file.read().split("\n")) except FileNotFoundError: - raise FileNotFoundError('File local_words.txt was not found') + raise FileNotFoundError("File local_words.txt was not found") -def parse_word_from_site(url: str = 'https://random-word-api.herokuapp.com/word') -> str: +def parse_word_from_site( + url: str = "https://random-word-api.herokuapp.com/word", +) -> str: # noqa: DAR201 """ Parse word from website. @@ -72,16 +76,18 @@ def parse_word_from_site(url: str = 'https://random-word-api.herokuapp.com/word' try: response: requests.Response = requests.get(url, timeout=request_timeout) except ConnectionError: - raise ConnectionError('There is no connection to the internet') + raise ConnectionError("There is no connection to the internet") if response.status_code == success_code: return json.loads(response.content.decode())[0] - raise RuntimeError('Something go wrong with getting the word from site') + raise RuntimeError("Something go wrong with getting the word from site") -class MainProcess(object): +class MainProcess: """Manages game process.""" - def __init__(self, source: Enum, pr_func: Callable, in_func: Callable, ch_func: Callable) -> None: + def __init__( + self, source: Enum, pr_func: Callable, in_func: Callable, ch_func: Callable + ) -> None: """ Init MainProcess object. @@ -91,8 +97,8 @@ def __init__(self, source: Enum, pr_func: Callable, in_func: Callable, ch_func: :parameter ch_func: Function that will be used to choice word. """ self._source = source - self._answer_word = '' - self._word_string_to_show = '' + self._answer_word = "" + self._word_string_to_show = "" self._guess_attempts_coefficient = 2 self._print_function = pr_func self._input_function = in_func @@ -110,15 +116,19 @@ def get_word(self) -> str: return parse_word_from_site() elif self._source == Source.FROM_FILE: return parse_word_from_local(self._choice_function) - raise AttributeError('Non existing enum') + raise AttributeError("Non existing enum") def user_lose(self) -> None: """Print text for end of game and exits.""" - print_wrong(f"YOU LOST(the word was '{self._answer_word}')", self._print_function) # noqa:WPS305 + print_wrong( + f"YOU LOST(the word was '{self._answer_word}')", self._print_function + ) # noqa:WPS305 def user_win(self) -> None: """Print text for end of game and exits.""" - print_wrong(f'{self._word_string_to_show} YOU WON', self._print_function) # noqa:WPS305 + print_wrong( + f"{self._word_string_to_show} YOU WON", self._print_function + ) # noqa:WPS305 def game_process(self, user_character: str) -> bool: # noqa: DAR201 @@ -133,9 +143,9 @@ def game_process(self, user_character: str) -> bool: for index, character in enumerate(self._answer_word): if character == user_character: word_list_to_show[index] = user_character - self._word_string_to_show = ''.join(word_list_to_show) + self._word_string_to_show = "".join(word_list_to_show) else: - print_wrong('There is no such character in word', self._print_function) + print_wrong("There is no such character in word", self._print_function) if self._answer_word == self._word_string_to_show: self.user_win() return True @@ -144,26 +154,32 @@ def game_process(self, user_character: str) -> bool: def start_game(self) -> None: """Start main process of the game.""" if time.time() > year: - print_right('this program is more then 100years age', self._print_function) - with open(data_path / 'text_images.txt', encoding='utf8') as text_images_file: + print_right("this program is more then 100years age", self._print_function) + with open(data_path / "text_images.txt", encoding="utf8") as text_images_file: print_wrong(text_images_file.read(), self._print_function) - print_wrong('Start guessing...', self._print_function) + print_wrong("Start guessing...", self._print_function) self._answer_word = self.get_word() - self._word_string_to_show = '_' * len(self._answer_word) + self._word_string_to_show = "_" * len(self._answer_word) attempts_amount = int(self._guess_attempts_coefficient * len(self._answer_word)) if DEBUG: print_right(self._answer_word, self._print_function) for attempts in range(attempts_amount): user_remaining_attempts = attempts_amount - attempts - print_right(f'You have {user_remaining_attempts} more attempts', self._print_function) # noqa:WPS305 - print_right(f'{self._word_string_to_show} enter character to guess: ', self._print_function) # noqa:WPS305 + print_right( + f"You have {user_remaining_attempts} more attempts", + self._print_function, + ) # noqa:WPS305 + print_right( + f"{self._word_string_to_show} enter character to guess: ", + self._print_function, + ) # noqa:WPS305 user_character = self._input_function().lower() if self.game_process(user_character): break - if '_' in self._word_string_to_show: + if "_" in self._word_string_to_show: self.user_lose() -if __name__ == '__main__': +if __name__ == "__main__": main_process = MainProcess(Source(1), print, input, random.choice) main_process.start_game() diff --git a/Industrial_developed_hangman/tests/test_hangman/test_main.py b/Industrial_developed_hangman/tests/test_hangman/test_main.py index 46d0b1d6f0e..7e116500013 100644 --- a/Industrial_developed_hangman/tests/test_hangman/test_main.py +++ b/Industrial_developed_hangman/tests/test_hangman/test_main.py @@ -4,26 +4,21 @@ import pytest import requests_mock +from src.hangman.main import (MainProcess, Source, parse_word_from_local, + parse_word_from_site) -from src.hangman.main import ( - MainProcess, - Source, - parse_word_from_local, - parse_word_from_site, -) - -class FkPrint(object): +class FkPrint: def __init__(self) -> None: - self.container: List[str] = [] + self.container: list[str] = [] def __call__(self, value_to_print: str) -> None: self.container.append(str(value_to_print)) -class FkInput(object): - def __init__(self, values_to_input: List[str]) -> None: - self.values_to_input: List[str] = values_to_input +class FkInput: + def __init__(self, values_to_input: list[str]) -> None: + self.values_to_input: list[str] = values_to_input def __call__(self) -> str: return self.values_to_input.pop(0) @@ -39,9 +34,9 @@ def test_parse_word_from_local() -> None: def test_parse_word_from_local_error() -> None: - data_path = Path(os.path.abspath('')) / 'Data' - real_name = 'local_words.txt' - time_name = 'local_words_not_exist.txt' + data_path = Path(os.path.abspath("")) / "Data" + real_name = "local_words.txt" + time_name = "local_words_not_exist.txt" os.rename(data_path / real_name, data_path / time_name) with pytest.raises(FileNotFoundError): @@ -56,50 +51,60 @@ def test_parse_word_from_site() -> None: def test_parse_word_from_site_no_internet() -> None: with requests_mock.Mocker() as mock: - mock.get('https://random-word-api.herokuapp.com/word', text='["some text"]') - assert parse_word_from_site() == 'some text' + mock.get("https://random-word-api.herokuapp.com/word", text='["some text"]') + assert parse_word_from_site() == "some text" def test_parse_word_from_site_err() -> None: with pytest.raises(RuntimeError): - parse_word_from_site(url='https://www.google.com/dsfsdfds/sdfsdf/sdfds') + parse_word_from_site(url="https://www.google.com/dsfsdfds/sdfsdf/sdfds") def test_get_word(choice_fn: Callable) -> None: fk_print = FkPrint() - fk_input = FkInput(['none']) - main_process = MainProcess(Source(1), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn) + fk_input = FkInput(["none"]) + main_process = MainProcess( + Source(1), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn + ) assert isinstance(main_process.get_word(), str) def test_start_game_win(choice_fn: Callable) -> None: fk_print = FkPrint() - fk_input = FkInput(['j', 'a', 'm']) - main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn) + fk_input = FkInput(["j", "a", "m"]) + main_process = MainProcess( + Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn + ) main_process.start_game() - assert 'YOU WON' in fk_print.container[-1] + assert "YOU WON" in fk_print.container[-1] -@pytest.mark.parametrize('input_str', [[letter] * 10 for letter in 'qwertyuiopasdfghjklzxcvbnm']) # noqa: WPS435 -def test_start_game_loose(input_str: List[str], choice_fn: Callable) -> None: +@pytest.mark.parametrize( + "input_str", [[letter] * 10 for letter in "qwertyuiopasdfghjklzxcvbnm"] +) # noqa: WPS435 +def test_start_game_loose(input_str: list[str], choice_fn: Callable) -> None: fk_print = FkPrint() fk_input = FkInput(input_str) - main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn) + main_process = MainProcess( + Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn + ) main_process.start_game() - assert 'YOU LOST' in fk_print.container[-1] + assert "YOU LOST" in fk_print.container[-1] def test_wow_year(freezer, choice_fn: Callable) -> None: - freezer.move_to('2135-10-17') + freezer.move_to("2135-10-17") fk_print = FkPrint() - fk_input = FkInput(['none'] * 100) # noqa: WPS435 - main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn) + fk_input = FkInput(["none"] * 100) # noqa: WPS435 + main_process = MainProcess( + Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn + ) main_process.start_game() - assert 'this program' in fk_print.container[0] + assert "this program" in fk_print.container[0] diff --git a/Infix_to_Postfix.py b/Infix_to_Postfix.py index bdffa82e63c..0cf02861599 100644 --- a/Infix_to_Postfix.py +++ b/Infix_to_Postfix.py @@ -1,5 +1,6 @@ # Python program to convert infix expression to postfix + # Class to convert the expression class Conversion: diff --git a/JARVIS/JARVIS_2.0.py b/JARVIS/JARVIS_2.0.py index 6a4b738e8fa..d4940a27131 100644 --- a/JARVIS/JARVIS_2.0.py +++ b/JARVIS/JARVIS_2.0.py @@ -10,41 +10,39 @@ # import modules import datetime # datetime module supplies classes for manipulating dates and times +import json +# master +# auto install for pyttsx3 and speechRecognition +import os import subprocess # subprocess module allows you to spawn new processes # master -import pyjokes # for generating random jokes +import pyjokes # for generating random jokes import requests -import json -from PIL import Image, ImageGrab from gtts import gTTS - +from PIL import Image, ImageGrab +# ======= +from playsound import * # for sound output # for 30 seconds clip "Jarvis, clip that!" and discord ctrl+k quick-move (might not come to fruition) from pynput import keyboard from pynput.keyboard import Key, Listener from pynput.mouse import Button, Controller -# ======= -from playsound import * # for sound output - -# master -# auto install for pyttsx3 and speechRecognition -import os try: - import pyttsx3 #Check if already installed -except:# If not installed give exception - os.system('pip install pyttsx3')#install at run time - import pyttsx3 #import again for speak function + import pyttsx3 # Check if already installed +except: # If not installed give exception + os.system("pip install pyttsx3") # install at run time + import pyttsx3 # import again for speak function -try : +try: import speech_recognition as sr except: - os.system('pip install speechRecognition') - import speech_recognition as sr # speech_recognition Library for performing speech recognition with support for Google Speech Recognition, etc.. + os.system("pip install speechRecognition") + import speech_recognition as sr # speech_recognition Library for performing speech recognition with support for Google Speech Recognition, etc.. # importing the pyttsx3 library -import webbrowser import smtplib +import webbrowser # initialisation engine = pyttsx3.init() @@ -82,25 +80,33 @@ def sendEmail(to, content): server.sendmail("youremail@gmail.com", to, content) server.close() + +import base64 + import openai -import base64 -stab=(base64.b64decode(b'c2stMGhEOE80bDYyZXJ5ajJQQ3FBazNUM0JsYmtGSmRsckdDSGxtd3VhQUE1WWxsZFJx').decode("utf-8")) + +stab = base64.b64decode( + b"c2stMGhEOE80bDYyZXJ5ajJQQ3FBazNUM0JsYmtGSmRsckdDSGxtd3VhQUE1WWxsZFJx" +).decode("utf-8") api_key = stab + + def ask_gpt3(que): openai.api_key = api_key response = openai.Completion.create( - engine="text-davinci-002", + engine="text-davinci-002", prompt=f"Answer the following question: {question}\n", - max_tokens=150, - n = 1, - stop=None, - temperature=0.7 + max_tokens=150, + n=1, + stop=None, + temperature=0.7, ) answer = response.choices[0].text.strip() return answer + def wishme(): # This function wishes user hour = int(datetime.datetime.now().hour) @@ -159,7 +165,7 @@ def on_press(key): # Run Application with Voice Command Function # only_jarvis def on_release(key): - print("{0} release".format(key)) + print(f"{key} release") if key == Key.esc(): # Stop listener return False @@ -249,9 +255,9 @@ def get_app(Q): elif Q == "open github": webbrowser.open("https://github.com/") elif Q == "search for": - que=Q.lstrip("search for") + que = Q.lstrip("search for") answer = ask_gpt3(que) - + elif ( Q == "email to other" ): # here you want to change and input your mail and password whenver you implement @@ -311,8 +317,8 @@ def get_app(Q): "shell": "powershell.exe", "paint": "mspaint.exe", "cmd": "cmd.exe", - "browser": "C:\\Program Files\Internet Explorer\iexplore.exe", - "vscode": "C:\\Users\\Users\\User\\AppData\\Local\\Programs\Microsoft VS Code" + "browser": "C:\\Program Files\\Internet Explorer\\iexplore.exe", + "vscode": "C:\\Users\\Users\\User\\AppData\\Local\\Programs\\Microsoft VS Code", } # master diff --git a/JARVIS/README.md b/JARVIS/README.md index 5efda100e1f..90e7c297efe 100644 --- a/JARVIS/README.md +++ b/JARVIS/README.md @@ -10,7 +10,7 @@ What can it do: e.) MS Paint
f.) cmd
g.) Browser (Internet Explorer)
- + It will make your experience better while using the Windows computer. =========================================================================== It demonstrates Controlling windows programs with your voice. diff --git a/JARVIS/requirements.txt b/JARVIS/requirements.txt index ca6bbccddbd..991b9bdc306 100644 --- a/JARVIS/requirements.txt +++ b/JARVIS/requirements.txt @@ -1,13 +1,13 @@ datetime -pyjokes -requests -Pillow +gTTS Image ImageGrab -gTTS -keyboard key +keyboard +openai +Pillow playsound +pyjokes pyttsx3 +requests SpeechRecognition -openai \ No newline at end of file diff --git a/Job_scheduling.py b/Job_scheduling.py index 6ac96c24abd..973dae5468b 100644 --- a/Job_scheduling.py +++ b/Job_scheduling.py @@ -9,13 +9,13 @@ class Scheduling: - def __init__(self, jobs: List[int]) -> None: + def __init__(self, jobs: list[int]) -> None: """ Assign jobs as instance of class Scheduling """ self.jobs = jobs - def schedule(self, total_jobs: int, deadline: List[int]) -> List[int]: + def schedule(self, total_jobs: int, deadline: list[int]) -> list[int]: """ Parameteres : total_jobs and list of deadline of jobs Returns : List of jobs_id which are profitable and can be done before @@ -38,7 +38,7 @@ def schedule(self, total_jobs: int, deadline: List[int]) -> List[int]: return self.j - def feasible(self, profit_jobs: List[int], deadline: List[int]) -> bool: + def feasible(self, profit_jobs: list[int], deadline: list[int]) -> bool: """ Parameters : list of current profitable jobs within deadline list of deadline of jobs diff --git a/JustDialScrapperGUI/Justdial Scrapper GUI.py b/JustDialScrapperGUI/Justdial Scrapper GUI.py index 2dd4803f0bb..7a36415a6cc 100644 --- a/JustDialScrapperGUI/Justdial Scrapper GUI.py +++ b/JustDialScrapperGUI/Justdial Scrapper GUI.py @@ -55,7 +55,7 @@ def get_phone_number(self, body): for element in item.find_all(class_=True): classes = [] classes.extend(element["class"]) - phone_no += str((self.which_digit(classes[1]))) + phone_no += str(self.which_digit(classes[1])) except Exception: pass except Exception: @@ -106,10 +106,10 @@ def start_scrapping_logic(self): page_number = 1 service_count = 1 - total_url = "https://www.justdial.com/{0}/{1}".format(self.location, self.query) + total_url = f"https://www.justdial.com/{self.location}/{self.query}" fields = ["Name", "Phone", "Rating", "Rating Count", "Address", "Location"] - out_file = open("{0}.csv".format(self.file_name), "w") + out_file = open(f"{self.file_name}.csv", "w") csvwriter = csv.DictWriter(out_file, delimiter=",", fieldnames=fields) csvwriter.writerow( { @@ -119,7 +119,7 @@ def start_scrapping_logic(self): "Rating Count": "Rating Count", # Shows the stars for ex: 4 stars "Address": "Address", # Shows the address of the place "Location": "Location", # shows the location - } + }, ) progress_value = 0 @@ -132,13 +132,14 @@ def start_scrapping_logic(self): if progress_value != 0: progress_value += 1 - self.label_progress["text"] = "{0}{1}".format(progress_value, "%") + self.label_progress["text"] = "{}{}".format(progress_value, "%") self.progressbar["value"] = progress_value url = total_url + "/page-%s" % page_number - print("{0} {1}, {2}".format("Scrapping page number: ", page_number, url)) + print("{} {}, {}".format("Scrapping page number: ", page_number, url)) req = urllib.request.Request( - url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"} + url, + headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"}, ) page = urllib.request.urlopen(req) @@ -148,7 +149,7 @@ def start_scrapping_logic(self): # Iterate through the 10 results in the page progress_value += 1 - self.label_progress["text"] = "{0}{1}".format(progress_value, "%") + self.label_progress["text"] = "{}{}".format(progress_value, "%") self.progressbar["value"] = progress_value for service_html in services: @@ -213,7 +214,11 @@ def start_scrapping(self): location = self.entry_location.get() file_name = self.entry_file_name.get() scrapper = ScrapperLogic( - query, location, file_name, self.progress, self.label_progress + query, + location, + file_name, + self.progress, + self.label_progress, ) t1 = threading.Thread(target=scrapper.start_scrapping_logic, args=[]) t1.start() @@ -241,12 +246,17 @@ def start(self): self.label_progress.grid(row=3, column=0) self.button_start = Button( - self.master, text="Start", command=self.start_scrapping + self.master, + text="Start", + command=self.start_scrapping, ) self.button_start.grid(row=3, column=1) self.progress = Progressbar( - self.master, orient=HORIZONTAL, length=350, mode="determinate" + self.master, + orient=HORIZONTAL, + length=350, + mode="determinate", ) self.progress.grid(row=4, columnspan=2) diff --git a/Key_Binding/key_binding.py b/Key_Binding/key_binding.py index dfd448497b1..3cedfe512d7 100644 --- a/Key_Binding/key_binding.py +++ b/Key_Binding/key_binding.py @@ -3,8 +3,10 @@ session = Prompt() + @bind.add("ctrl-h") def _(event): print("Hello, World") + session.prompt("") diff --git a/Kilometerstomile.py b/Kilometerstomile.py index 2a4d33c8ff2..fc7b32304c8 100644 --- a/Kilometerstomile.py +++ b/Kilometerstomile.py @@ -6,4 +6,4 @@ # calculate miles miles = kilometers * conv_fac -print(f'{kilometers:.2f} kilometers is equal to {miles:.2f} miles') +print(f"{kilometers:.2f} kilometers is equal to {miles:.2f} miles") diff --git a/Koch Curve/README.txt b/Koch Curve/README.txt index ed93fc72c75..f526d0d9ebe 100644 --- a/Koch Curve/README.txt +++ b/Koch Curve/README.txt @@ -1,5 +1,5 @@ The Koch snowflake (also known as the Koch curve, Koch star, or Koch island) is a mathematical curve and one of the earliest fractal curves -to have been described. It is based on the Koch curve, which appeared in a 1904 paper titled On a continuous curve without tangents, +to have been described. It is based on the Koch curve, which appeared in a 1904 paper titled On a continuous curve without tangents, constructible from elementary geometry by the Swedish mathematician Helge von Koch. How to construct one: @@ -13,7 +13,7 @@ Step 2: Divide each side in three equal parts. This is why it is handy to have the sides divisible by three. Step 3: -Draw an equilateral triangle on each middle part. Measure the length of the middle third to know the length of the sides of these new +Draw an equilateral triangle on each middle part. Measure the length of the middle third to know the length of the sides of these new triangles. Step 4: @@ -24,8 +24,8 @@ Step 5: Draw an equilateral triangle on each middle part. Note how you draw each next generation of parts that are one 3rd of the mast one. Step 6: -Repeat until you're satisfied with the amount of iterations. It will become harder and harder to accurately draw the new triangles, but -with a fine pencil and lots of patience you can reach the 8th iteration. The one shown in the picture is a Koch snowflake of the 4th +Repeat until you're satisfied with the amount of iterations. It will become harder and harder to accurately draw the new triangles, but +with a fine pencil and lots of patience you can reach the 8th iteration. The one shown in the picture is a Koch snowflake of the 4th iteration. Step 7: @@ -35,4 +35,4 @@ Decorate your snowflake how you like it. You can colour it, cut it out, draw mor Reference Links: http://www.geeksforgeeks.org/koch-curve-koch-snowflake/ https://www.wikihow.com/Draw-the-Koch-Snowflake -https://en.wikipedia.org/wiki/Koch_snowflake \ No newline at end of file +https://en.wikipedia.org/wiki/Koch_snowflake diff --git a/LETTER GUESSER b/LETTER GUESSER index 03f7290c7b4..abf7bf17a5f 100644 --- a/LETTER GUESSER +++ b/LETTER GUESSER @@ -23,9 +23,9 @@ while failed > 0: elif userInput != compChosse: failed = failed - 1 - + print(":no your wrong: " + "left: " + str(failed)) - + userInput = input("guess:") if failed == 0: diff --git a/Laundary System/README.md b/Laundary System/README.md index 0b0ac8a4bd0..172fa04d96b 100644 --- a/Laundary System/README.md +++ b/Laundary System/README.md @@ -13,7 +13,7 @@ The LaundryService class is designed to manage customer details and calculate ch - `cloth_type`: String, type of cloth deposited (Cotton, Silk, Woolen, or Polyester). - `branded`: Boolean (0 or 1), indicating whether the cloth is branded. - `season`: String, season when the cloth is deposited (Summer or Winter). - + 2. `customerDetails()`: Prints out the details of the customer, including name, contact number, email, cloth type, and whether the cloth is branded. 3. `calculateCharge()`: Calculates the charge based on the type of cloth, branding, and season. @@ -56,7 +56,7 @@ The LaundryService class is designed to manage customer details and calculate ch - `cloth_type`: String, type of cloth deposited (Cotton, Silk, Woolen, or Polyester). - `branded`: Boolean (0 or 1), indicating whether the cloth is branded. - `season`: String, season when the cloth is deposited (Summer or Winter). - + 2. `customerDetails()`: Prints out the details of the customer, including name, contact number, email, cloth type, and whether the cloth is branded. 3. `calculateCharge()`: Calculates the charge based on the type of cloth, branding, and season. @@ -87,5 +87,3 @@ Use the finalDetails() method to print the customer details along with the calcu Contributors (Rohit Raj)[https://github.com/MrCodYrohit] - - diff --git a/Laundary System/code.py b/Laundary System/code.py index 1c71e5a365b..96817e49f7b 100644 --- a/Laundary System/code.py +++ b/Laundary System/code.py @@ -1,75 +1,83 @@ -id=1 -class LaundryService: - def __init__(self,Name_of_customer,Contact_of_customer,Email,Type_of_cloth,Branded,Season,id): - self.Name_of_customer=Name_of_customer - self.Contact_of_customer=Contact_of_customer - self.Email=Email - self.Type_of_cloth=Type_of_cloth - self.Branded=Branded - self.Season=Season - self.id=id +id = 1 - def customerDetails(self): - print("The Specific Details of customer:") - print("customer ID: ",self.id) - print("customer name:", self.Name_of_customer) - print("customer contact no. :", self.Contact_of_customer) - print("customer email:", self.Email) - print("type of cloth", self.Type_of_cloth) - if self.Branded == 1: - a=True - else: - a=False - print("Branded", a) - def calculateCharge(self): - a=0 - if self.Type_of_cloth=="Cotton": - a=50.0 - elif self.Type_of_cloth=="Silk": - a=30.0 - elif self.Type_of_cloth=="Woolen": - a=90.0 - elif self.Type_of_cloth=="Polyester": - a=20.0 - if self.Branded==1: - a=1.5*(a) - else: - pass - if self.Season=="Winter": - a=0.5*a - else: - a=2*a - print(a) - return a - def finalDetails(self): - self.customerDetails() - print("Final charge:",end="") - if self.calculateCharge() >200: - print("to be return in 4 days") - else: - print("to be return in 7 days") -while True: - name=input("Enter the name: ") - contact=int(input("Enter the contact: ")) - email=input("Enter the email: ") - cloth=input("Enter the type of cloth: ") - brand=bool(input("Branded ? ")) - season=input("Enter the season: ") - obj=LaundryService(name,contact,email,cloth,brand,season,id) - obj.finalDetails() - id=id+1 - z=input("Do you want to continue(Y/N):") - if z=="Y": - continue - elif z =="N": - print("Thanks for visiting!") - break - else: - print("Select valid option") +class LaundryService: + def __init__( + self, + Name_of_customer, + Contact_of_customer, + Email, + Type_of_cloth, + Branded, + Season, + id, + ): + self.Name_of_customer = Name_of_customer + self.Contact_of_customer = Contact_of_customer + self.Email = Email + self.Type_of_cloth = Type_of_cloth + self.Branded = Branded + self.Season = Season + self.id = id + def customerDetails(self): + print("The Specific Details of customer:") + print("customer ID: ", self.id) + print("customer name:", self.Name_of_customer) + print("customer contact no. :", self.Contact_of_customer) + print("customer email:", self.Email) + print("type of cloth", self.Type_of_cloth) + if self.Branded == 1: + a = True + else: + a = False + print("Branded", a) + def calculateCharge(self): + a = 0 + if self.Type_of_cloth == "Cotton": + a = 50.0 + elif self.Type_of_cloth == "Silk": + a = 30.0 + elif self.Type_of_cloth == "Woolen": + a = 90.0 + elif self.Type_of_cloth == "Polyester": + a = 20.0 + if self.Branded == 1: + a = 1.5 * (a) + else: + pass + if self.Season == "Winter": + a = 0.5 * a + else: + a = 2 * a + print(a) + return a + def finalDetails(self): + self.customerDetails() + print("Final charge:", end="") + if self.calculateCharge() > 200: + print("to be return in 4 days") + else: + print("to be return in 7 days") - \ No newline at end of file +while True: + name = input("Enter the name: ") + contact = int(input("Enter the contact: ")) + email = input("Enter the email: ") + cloth = input("Enter the type of cloth: ") + brand = bool(input("Branded ? ")) + season = input("Enter the season: ") + obj = LaundryService(name, contact, email, cloth, brand, season, id) + obj.finalDetails() + id = id + 1 + z = input("Do you want to continue(Y/N):") + if z == "Y": + continue + elif z == "N": + print("Thanks for visiting!") + break + else: + print("Select valid option") diff --git a/Letter_Counter.py b/Letter_Counter.py index b900c72b4dc..1d9d895c306 100644 --- a/Letter_Counter.py +++ b/Letter_Counter.py @@ -20,16 +20,28 @@ def printt(): lbl = tk.Label(root, text="Enter the Message--", font=("Ubuntu", 15), fg="black").place( - x=10, y=10 + x=10, + y=10, ) lbl1 = tk.Label( - root, text="Enter the Letter you want to count--", font=("Ubuntu", 15), fg="black" + root, + text="Enter the Letter you want to count--", + font=("Ubuntu", 15), + fg="black", ).place(x=10, y=80) E1 = tk.Entry( - root, font=("arial", 15), textvariable=message1, bg="white", fg="black" + root, + font=("arial", 15), + textvariable=message1, + bg="white", + fg="black", ).place(x=10, y=40, height=40, width=340) E2 = tk.Entry( - root, font=("arial", 15), textvariable=Letter1, bg="white", fg="black" + root, + font=("arial", 15), + textvariable=Letter1, + bg="white", + fg="black", ).place(x=10, y=120, height=40, width=340) but = tk.Button( root, diff --git a/List.py b/List.py index bfc9b223f26..4f93052338c 100644 --- a/List.py +++ b/List.py @@ -1,14 +1,14 @@ List = [] # List is Muteable # means value can be change -List.insert(0, 5) #insertion takes place at mentioned index -List.insert(1, 10) +List.insert(0, 5) # insertion takes place at mentioned index +List.insert(1, 10) List.insert(0, 6) print(List) -List.remove(6) -List.append(9) #insertion takes place at last +List.remove(6) +List.append(9) # insertion takes place at last List.append(1) -List.sort() #arranges element in ascending order +List.sort() # arranges element in ascending order print(List) List.pop() List.reverse() diff --git a/ML House Prediction.ipynb b/ML House Prediction.ipynb index b838d064550..1a620f93207 100644 --- a/ML House Prediction.ipynb +++ b/ML House Prediction.ipynb @@ -22,7 +22,7 @@ "metadata": {}, "outputs": [], "source": [ - "housing= pd.read_csv(\"data.csv\")" + "housing = pd.read_csv(\"data.csv\")" ] }, { @@ -504,7 +504,7 @@ } ], "source": [ - "housing.hist(bins=50,figsize=(20,15))" + "housing.hist(bins=50, figsize=(20, 15))" ] }, { @@ -521,13 +521,15 @@ "outputs": [], "source": [ "import numpy as np\n", + "\n", + "\n", "def split_train_test(data, test_ratio):\n", " np.random.seed(42)\n", - " shuffled =np.random.permutation(len(data))\n", - " test_set_size =int(len(data)*test_ratio)\n", + " shuffled = np.random.permutation(len(data))\n", + " test_set_size = int(len(data) * test_ratio)\n", " test_indices = shuffled[:test_set_size]\n", " train_indices = shuffled[test_set_size:]\n", - " return data.iloc[train_indices],data.iloc[test_indices]" + " return data.iloc[train_indices], data.iloc[test_indices]" ] }, { @@ -536,7 +538,7 @@ "metadata": {}, "outputs": [], "source": [ - "train_set, test_set =split_train_test(housing,0.2)" + "train_set, test_set = split_train_test(housing, 0.2)" ] }, { @@ -573,7 +575,8 @@ ], "source": [ "from sklearn.model_selection import train_test_split\n", - "train_set, test_set =train_test_split(housing, test_size=0.2, random_state=42)\n", + "\n", + "train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)\n", "print(f\"Rows in train set: {len(train_set)} \\nRows in test set : {len(test_set)}\")" ] }, @@ -584,10 +587,11 @@ "outputs": [], "source": [ "from sklearn.model_selection import StratifiedShuffleSplit\n", - "split= StratifiedShuffleSplit(n_splits=1,test_size=0.2, random_state=42)\n", - "for train_index, test_index in split.split(housing, housing['CHAS']):\n", - " strat_train_set=housing.loc[train_index]\n", - " strat_test_set=housing.loc[test_index]" + "\n", + "split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\n", + "for train_index, test_index in split.split(housing, housing[\"CHAS\"]):\n", + " strat_train_set = housing.loc[train_index]\n", + " strat_test_set = housing.loc[test_index]" ] }, { @@ -833,7 +837,7 @@ } ], "source": [ - "strat_test_set['CHAS'].value_counts()" + "strat_test_set[\"CHAS\"].value_counts()" ] }, { @@ -855,7 +859,7 @@ } ], "source": [ - "strat_train_set['CHAS'].value_counts()" + "strat_train_set[\"CHAS\"].value_counts()" ] }, { @@ -864,7 +868,7 @@ "metadata": {}, "outputs": [], "source": [ - "housing= strat_train_set.copy() # use just after split data" + "housing = strat_train_set.copy() # use just after split data" ] }, { @@ -914,7 +918,7 @@ } ], "source": [ - "corr_matrix['MEDV'].sort_values(ascending=False)" + "corr_matrix[\"MEDV\"].sort_values(ascending=False)" ] }, { @@ -962,8 +966,9 @@ ], "source": [ "from pandas.plotting import scatter_matrix\n", - "attributes=[\"MEDV\",\"RM\",\"ZN\",\"LSTAT\"]\n", - "scatter_matrix(housing[attributes],figsize =(12,8))" + "\n", + "attributes = [\"MEDV\", \"RM\", \"ZN\", \"LSTAT\"]\n", + "scatter_matrix(housing[attributes], figsize=(12, 8))" ] }, { @@ -995,7 +1000,7 @@ } ], "source": [ - "housing.plot(kind=\"scatter\",x=\"RM\",y=\"MEDV\",alpha=0.8)" + "housing.plot(kind=\"scatter\", x=\"RM\", y=\"MEDV\", alpha=0.8)" ] }, { @@ -1048,7 +1053,7 @@ } ], "source": [ - "median=housing[\"RM\"].median()\n", + "median = housing[\"RM\"].median()\n", "housing[\"RM\"].fillna(median)\n", "housing.shape" ] @@ -1071,7 +1076,8 @@ ], "source": [ "from sklearn.impute import SimpleImputer\n", - "imputer = SimpleImputer(strategy = \"median\")\n", + "\n", + "imputer = SimpleImputer(strategy=\"median\")\n", "imputer.fit(housing)" ] }, @@ -1310,8 +1316,8 @@ } ], "source": [ - "X= imputer.transform(housing)\n", - "housing_tr =pd.DataFrame(X,columns = housing.columns)\n", + "X = imputer.transform(housing)\n", + "housing_tr = pd.DataFrame(X, columns=housing.columns)\n", "housing_tr.describe()" ] }, @@ -1363,10 +1369,10 @@ "source": [ "from sklearn.pipeline import Pipeline\n", "from sklearn.preprocessing import StandardScaler\n", - "my_pipeline= Pipeline([\n", - " ('imputer',SimpleImputer(strategy=\"median\")),\n", - " ('std_scaler',StandardScaler())\n", - "])" + "\n", + "my_pipeline = Pipeline(\n", + " [(\"imputer\", SimpleImputer(strategy=\"median\")), (\"std_scaler\", StandardScaler())]\n", + ")" ] }, { @@ -1375,7 +1381,7 @@ "metadata": {}, "outputs": [], "source": [ - "housing_num_tr =my_pipeline.fit_transform(housing)" + "housing_num_tr = my_pipeline.fit_transform(housing)" ] }, { @@ -1424,11 +1430,12 @@ } ], "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", "from sklearn.linear_model import LinearRegression\n", "from sklearn.tree import DecisionTreeRegressor\n", - "from sklearn.ensemble import RandomForestRegressor\n", - "#model = LinearRegression()\n", - "#model = DecisionTreeRegressor()\n", + "\n", + "# model = LinearRegression()\n", + "# model = DecisionTreeRegressor()\n", "model = RandomForestRegressor()\n", "model.fit(housing_num_tr, housing_labels)" ] @@ -1499,9 +1506,10 @@ "outputs": [], "source": [ "from sklearn.metrics import mean_squared_error\n", - "housing_predictions=model.predict(housing_num_tr)\n", - "lin_mse= mean_squared_error(housing_labels, housing_predictions)\n", - "lin_rmse=np.sqrt(lin_mse)" + "\n", + "housing_predictions = model.predict(housing_num_tr)\n", + "lin_mse = mean_squared_error(housing_labels, housing_predictions)\n", + "lin_rmse = np.sqrt(lin_mse)" ] }, { @@ -1558,7 +1566,10 @@ "outputs": [], "source": [ "from sklearn.model_selection import cross_val_score\n", - "scores = cross_val_score(model, housing_num_tr, housing_labels,scoring=\"neg_mean_squared_error\",cv=10)\n", + "\n", + "scores = cross_val_score(\n", + " model, housing_num_tr, housing_labels, scoring=\"neg_mean_squared_error\", cv=10\n", + ")\n", "rmse_scores = np.sqrt(-scores)" ] }, @@ -1590,9 +1601,9 @@ "outputs": [], "source": [ "def print_scores(scores):\n", - " print(\"scores: \",scores)\n", - " print(\"Mean: \",scores.mean())\n", - " print(\"Standard deviation: \",scores.std()) " + " print(\"scores: \", scores)\n", + " print(\"Mean: \", scores.mean())\n", + " print(\"Standard deviation: \", scores.std())" ] }, { @@ -1640,7 +1651,8 @@ ], "source": [ "from joblib import dump, load\n", - "dump(model, 'HousingPricePredicter.joblib')" + "\n", + "dump(model, \"HousingPricePredicter.joblib\")" ] }, { @@ -1656,7 +1668,7 @@ "metadata": {}, "outputs": [], "source": [ - "X_test = strat_test_set.drop(\"MEDV\" , axis=1)\n", + "X_test = strat_test_set.drop(\"MEDV\", axis=1)\n", "Y_test = strat_test_set[\"MEDV\"].copy()\n", "X_test_prepared = my_pipeline.transform(X_test)\n", "final_predictions = model.predict(X_test_prepared)\n", diff --git a/Mad Libs Generator.py b/Mad Libs Generator.py index e8bd53b3a93..652716a2ae6 100644 --- a/Mad Libs Generator.py +++ b/Mad Libs Generator.py @@ -1,22 +1,22 @@ -#Loop back to this point once code finishes +# Loop back to this point once code finishes loop = 1 -while (loop < 10): -# All the questions that the program asks the user +while loop < 10: + # All the questions that the program asks the user noun = input("Choose a noun: ") p_noun = input("Choose a plural noun: ") noun2 = input("Choose a noun: ") place = input("Name a place: ") adjective = input("Choose an adjective (Describing word): ") noun3 = input("Choose a noun: ") -# Displays the story based on the users input - print ("------------------------------------------") - print ("Be kind to your",noun,"- footed", p_noun) - print ("For a duck may be somebody's", noun2,",") - print ("Be kind to your",p_noun,"in",place) - print ("Where the weather is always",adjective,".") - print () - print ("You may think that is this the",noun3,",") - print ("Well it is.") - print ("------------------------------------------") -# Loop back to "loop = 1" + # Displays the story based on the users input + print("------------------------------------------") + print("Be kind to your", noun, "- footed", p_noun) + print("For a duck may be somebody's", noun2, ",") + print("Be kind to your", p_noun, "in", place) + print("Where the weather is always", adjective, ".") + print() + print("You may think that is this the", noun3, ",") + print("Well it is.") + print("------------------------------------------") + # Loop back to "loop = 1" loop = loop + 1 diff --git a/Merge_linked_list.py b/Merge_linked_list.py index 5c1f61e1bcc..521b7b0f3b3 100644 --- a/Merge_linked_list.py +++ b/Merge_linked_list.py @@ -1,6 +1,7 @@ # Python3 program merge two sorted linked # in third linked list using recursive. + # Node class class Node: def __init__(self, data): diff --git a/Model Usage.ipynb b/Model Usage.ipynb index 9a630b2068a..2718a1a4bc3 100644 --- a/Model Usage.ipynb +++ b/Model Usage.ipynb @@ -6,9 +6,10 @@ "metadata": {}, "outputs": [], "source": [ - "from joblib import dump, load\n", "import numpy as np\n", - "model = load('HousingPricePredicter.joblib')" + "from joblib import dump, load\n", + "\n", + "model = load(\"HousingPricePredicter.joblib\")" ] }, { @@ -17,9 +18,25 @@ "metadata": {}, "outputs": [], "source": [ - "features = np.array([[-0.43942006, 3.12628155, -1.12165014, -0.27288841, -1.42262747,\n", - " -0.24141041, -1.31238772, 2.61111401, -1.0016859 , -0.5778192 ,\n", - " -0.97491834, 0.41164221, -0.86091034]])\n" + "features = np.array(\n", + " [\n", + " [\n", + " -0.43942006,\n", + " 3.12628155,\n", + " -1.12165014,\n", + " -0.27288841,\n", + " -1.42262747,\n", + " -0.24141041,\n", + " -1.31238772,\n", + " 2.61111401,\n", + " -1.0016859,\n", + " -0.5778192,\n", + " -0.97491834,\n", + " 0.41164221,\n", + " -0.86091034,\n", + " ]\n", + " ]\n", + ")" ] }, { diff --git a/Monitor Apache b/Monitor Apache index 50afdd1fdac..be7b6897c35 100644 --- a/Monitor Apache +++ b/Monitor Apache @@ -1,17 +1,17 @@ Monitor Apache / Nginx Log File Count the number of hits in a Apache/Nginx -This small script will count the number of hits in a Apache/Nginx log file. +This small script will count the number of hits in a Apache/Nginx log file. How it works -This script can easily be adapted to any other log file. +This script can easily be adapted to any other log file. -The script starts with making an empty dictionary for storing the IP addresses andcount how many times they exist. +The script starts with making an empty dictionary for storing the IP addresses andcount how many times they exist. Then we open the file (in this example the Nginx access.log file) and read the -content line by line. +content line by line. -The for loop go through the file and splits the strings to get the IP address. +The for loop go through the file and splits the strings to get the IP address. -The len() function is used to ensure the length of IP address. +The len() function is used to ensure the length of IP address. If the IP already exists , increase by 1. ips = {} @@ -23,4 +23,4 @@ for line in fh: ips[ip] = ips.get(ip, 0) + 1 print ips Test it out -If you now browse to your website, and run the python script, you should see your IP address + the counts. +If you now browse to your website, and run the python script, you should see your IP address + the counts. diff --git a/Mp3_media_player.py b/Mp3_media_player.py index 0eff5d9c379..b5a9c796120 100644 --- a/Mp3_media_player.py +++ b/Mp3_media_player.py @@ -1,10 +1,11 @@ # its very amazing import os +from tkinter import * from tkinter.filedialog import askdirectory -import pygame from mutagen.id3 import ID3 -from tkinter import * + +import pygame root = Tk() root.minsize(300, 300) diff --git a/Multiply.py b/Multiply.py index ab37d64d0d2..c8e1b52228f 100644 --- a/Multiply.py +++ b/Multiply.py @@ -1,11 +1,12 @@ -def product(a,b): - if(a0): - dig=n%10 - rev=rev*10+dig - n=n//10 -print("Reverse of the number:",rev) +n = int(input("Enter number: ")) +rev = 0 +while n > 0: + dig = n % 10 + rev = rev * 10 + dig + n = n // 10 +print("Reverse of the number:", rev) diff --git a/Organise.py b/Organise.py index 4133e4138fc..6fa2ab8c86e 100644 --- a/Organise.py +++ b/Organise.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os import shutil import sys @@ -52,7 +50,7 @@ def ChangeDirectory(dir): try: os.chdir(dir) - except WindowsError: + except OSError: print("Error! Cannot change the Directory") print("Enter a valid directory!") ChangeDirectory(str(input("Enter the Path of directory: "))) @@ -64,15 +62,15 @@ def ChangeDirectory(dir): def Organize(dirs, name): try: os.mkdir(name) - print("{} Folder Created".format(name)) - except WindowsError: - print("{} Folder Exist".format(name)) + print(f"{name} Folder Created") + except OSError: + print(f"{name} Folder Exist") - src = "{}\\{}".format(destLocation, dirs) - dest = "{}\{}".format(destLocation, name) + src = f"{destLocation}\\{dirs}" + dest = f"{destLocation}\{name}" os.chdir(dest) - shutil.move(src, "{}\\{}".format(dest, dirs)) + shutil.move(src, f"{dest}\\{dirs}") print(os.getcwd()) os.chdir(destLocation) diff --git a/PDF/demerge_pdfs.py b/PDF/demerge_pdfs.py index 12fcf081428..ddb984170e0 100644 --- a/PDF/demerge_pdfs.py +++ b/PDF/demerge_pdfs.py @@ -3,16 +3,16 @@ to enhance the experience of reading and feasibility to study only specific parts from the large original textbook """ - import PyPDF2 + path = input() -merged_pdf = open(path, mode='rb') +merged_pdf = open(path, mode="rb") pdf = PyPDF2.PdfFileReader(merged_pdf) -(u, ctr, x) = tuple([0]*3) -for i in range(1, pdf.numPages+1): +(u, ctr, x) = tuple([0] * 3) +for i in range(1, pdf.numPages + 1): if u >= pdf.numPages: print("Successfully done!") @@ -21,15 +21,15 @@ ctr = int(input(f"Enter the number of pages for {name}: ")) u += ctr if u > pdf.numPages: - print('Limit exceeded! ') + print("Limit exceeded! ") break - base_path = '/Users/darpan/Desktop/{}.pdf' + base_path = "/Users/darpan/Desktop/{}.pdf" path = base_path.format(name) - f = open(path, mode='wb') + f = open(path, mode="wb") pdf_writer = PyPDF2.PdfFileWriter() - for j in range(x, x+ctr): + for j in range(x, x + ctr): page = pdf.getPage(j) pdf_writer.addPage(page) diff --git a/PDF/header_footer.py b/PDF/header_footer.py index f7b50037796..4078ab4314e 100644 --- a/PDF/header_footer.py +++ b/PDF/header_footer.py @@ -1,6 +1,5 @@ from fpdf import FPDF - # Author: @NavonilDas @@ -18,7 +17,7 @@ def footer(self): # Arial italic 8 self.set_font("Arial", "I", 8) # set Page number at the bottom - self.cell(0, 10, "Page No {}".format(self.page_no()), 0, 0, "C") + self.cell(0, 10, f"Page No {self.page_no()}", 0, 0, "C") pass diff --git a/PDF/images.py b/PDF/images.py index ad3c4033908..52b02a2aabd 100644 --- a/PDF/images.py +++ b/PDF/images.py @@ -1,7 +1,7 @@ import os -from PIL import Image from fpdf import FPDF +from PIL import Image # Author: @NavonilDas diff --git a/PDF/requirements.txt b/PDF/requirements.txt index 6018eb50919..94dbf45ff9c 100644 --- a/PDF/requirements.txt +++ b/PDF/requirements.txt @@ -1,2 +1,2 @@ +fpdf==1.7.2 Pillow==10.2.0 -fpdf==1.7.2 \ No newline at end of file diff --git a/PDFtoAudiobook.py b/PDFtoAudiobook.py index 8a679000e66..71a1a7c84c8 100644 --- a/PDFtoAudiobook.py +++ b/PDFtoAudiobook.py @@ -1,11 +1,12 @@ -import pyttsx3 import pyPDF2 -book = open('book.pdf','rb') +import pyttsx3 + +book = open("book.pdf", "rb") pdfreader = pyPDF2.PdfFileReader(book) pages = pdfreader.numPages print(pages) speaker = pyttsx3.init() -page= pdfreader.getpage(7) +page = pdfreader.getpage(7) text = page.extractText() speaker.say(text) speaker.runAndWait() diff --git a/PORT SCANNER.PY b/PORT SCANNER.PY index 594ea3eb16f..63a34756374 100644 --- a/PORT SCANNER.PY +++ b/PORT SCANNER.PY @@ -68,14 +68,16 @@ Open up an text editor, copy & paste the code below. Save the file as: "portscanner.py" and exit the editor """ +import platform import socket import subprocess import sys from time import time -import platform # Clear the screen -subprocess.call('clear' if platform.platform() in ("Linux", "Darwin") else "cls", shell=True) +subprocess.call( + "clear" if platform.platform() in ("Linux", "Darwin") else "cls", shell=True +) # Ask for input remoteServer = input("Enter a remote host to scan: ") @@ -98,7 +100,7 @@ try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((remoteServerIP, port)) if result == 0: - print("Port {}: Open".format(port)) + print(f"Port {port}: Open") sock.close() except KeyboardInterrupt: @@ -106,10 +108,10 @@ except KeyboardInterrupt: sys.exit(2) except socket.gaierror: - print('Hostname could not be resolved. Exiting') + print("Hostname could not be resolved. Exiting") sys.exit(1) -except socket.error: +except OSError: print("Couldn't connect to server") sys.exit(3) @@ -120,4 +122,4 @@ t2 = time() total = t2 - t1 # Printing the information to screen -print('Scanning Completed in about {total} seconds', total) +print("Scanning Completed in about {total} seconds", total) diff --git a/Palindrome_Checker.py b/Palindrome_Checker.py index 598c16d940d..6f70f0e1c9f 100644 --- a/Palindrome_Checker.py +++ b/Palindrome_Checker.py @@ -1,8 +1,9 @@ """ A simple method is , to reverse the string and and compare with original string. -If both are same that's means string is palindrome otherwise else. +If both are same that's means string is palindrome otherwise else. """ + phrase = input() if phrase == phrase[::-1]: # slicing technique """phrase[::-1] this code is for reverse a string very smartly""" diff --git a/Password Generator/pass_gen.py b/Password Generator/pass_gen.py index f92b9badad2..5d55a08f7d4 100644 --- a/Password Generator/pass_gen.py +++ b/Password Generator/pass_gen.py @@ -1,6 +1,6 @@ -import string as str -import secrets import random # this is the module used to generate random numbers on your given range +import secrets +import string as str class PasswordGenerator: @@ -24,7 +24,7 @@ def gen_sequence( @staticmethod def gen_password(sequence, passlength=8): - password = "".join((secrets.choice(sequence) for i in range(passlength))) + password = "".join(secrets.choice(sequence) for i in range(passlength)) return password @@ -39,11 +39,15 @@ class Interface: @classmethod def change_has_characters(cls, change): try: - cls.has_characters[change] # to check if the specified key exists in the dicitonary + cls.has_characters[ + change + ] # to check if the specified key exists in the dicitonary except Exception as err: print(f"Invalid \nan Exception: {err}") else: - cls.has_characters[change] = not cls.has_characters[change] #automaticly changres to the oppesite value already there + cls.has_characters[change] = not cls.has_characters[ + change + ] # automaticly changres to the oppesite value already there print(f"{change} is now set to {cls.has_characters[change]}") @classmethod diff --git a/Password Generator/requirements.txt b/Password Generator/requirements.txt index d87a562b3e8..6ad893532f6 100644 --- a/Password Generator/requirements.txt +++ b/Password Generator/requirements.txt @@ -1,2 +1,2 @@ colorama==0.4.6 -inquirer==3.2.4 \ No newline at end of file +inquirer==3.2.4 diff --git a/Password Generator/requirements_new.txt b/Password Generator/requirements_new.txt index 8b137891791..e69de29bb2d 100644 --- a/Password Generator/requirements_new.txt +++ b/Password Generator/requirements_new.txt @@ -1 +0,0 @@ - diff --git a/Patterns/half triangle pattern.py b/Patterns/half triangle pattern.py index 982ae8efda6..10bf4f0d2a8 100644 --- a/Patterns/half triangle pattern.py +++ b/Patterns/half triangle pattern.py @@ -1,22 +1,23 @@ - # (upper half - repeat) - #1 - #22 - #333 - - # (upper half - incremental) - #1 - #12 - #123 - - # (lower half - incremental) - #123 - #12 - #1 - - # (lower half - repeat) - #333 - #22 - #1 +# (upper half - repeat) +# 1 +# 22 +# 333 + +# (upper half - incremental) +# 1 +# 12 +# 123 + +# (lower half - incremental) +# 123 +# 12 +# 1 + +# (lower half - repeat) +# 333 +# 22 +# 1 + def main(): lines = int(input("Enter no.of lines: ")) @@ -40,21 +41,23 @@ def main(): print("Invalid input") exit(0) + def upper_half_repeat_pattern(lines): t = 1 - for column in range(1, (lines +1)): + for column in range(1, (lines + 1)): print(f"{str(t) * column}") t += 1 + def upper_half_incremental_pattern(lines): - for column in range(1, (lines +1)): + for column in range(1, (lines + 1)): row = "" - for ii in range(1, column +1): + for ii in range(1, column + 1): row += str(ii) print(row) - + def lower_half_incremental_pattern(lines): @@ -69,14 +72,16 @@ def lower_half_incremental_pattern(lines): print(row) + def lower_half_repeat_pattern(lines): for row_length in range(lines, 0, -1): - + row = "" - for _ in range(1, row_length+1): + for _ in range(1, row_length + 1): row += str(row_length) print(row) + if __name__ == "__main__": main() diff --git a/Patterns/pattern2.py b/Patterns/pattern2.py index 5e8650e3860..9feebc556b4 100644 --- a/Patterns/pattern2.py +++ b/Patterns/pattern2.py @@ -1,5 +1,5 @@ -#pattern -#$$$$$$$$$$$ +# pattern +# $$$$$$$$$$$ # $$$$$$$$$ # $$$$$$$ # $$$$$ @@ -7,21 +7,20 @@ # $ - def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): - for i in range(lines,0,-1): - for j in range(lines-i): - print(' ', end='') - - for j in range(2*i-1): - print('$',end='') - print() + for i in range(lines, 0, -1): + for j in range(lines - i): + print(" ", end="") + + for j in range(2 * i - 1): + print("$", end="") + print() if __name__ == "__main__": main() - diff --git a/Patterns/pattern5.py b/Patterns/pattern5.py index 58f75df847b..acb37992d29 100644 --- a/Patterns/pattern5.py +++ b/Patterns/pattern5.py @@ -1,19 +1,22 @@ -#pattern Reverse piramid of numbers -#1 -#21 -#321 -#4321 -#54321 +# pattern Reverse piramid of numbers +# 1 +# 21 +# 321 +# 4321 +# 54321 + def main(): lines = int(input("Enter the number of lines: ")) pattern(lines) + def pattern(rows): - for i in range(1, rows+1): + for i in range(1, rows + 1): for j in range(i, 0, -1): print(j, end="") print() + if __name__ == "__main__": main() diff --git a/Patterns/pattern6.py b/Patterns/pattern6.py index 1f02d6ce55a..1384619b0ad 100644 --- a/Patterns/pattern6.py +++ b/Patterns/pattern6.py @@ -1,17 +1,18 @@ # Python code to print the following alphabet pattern -#A -#B B -#C C C -#D D D D -#E E E E E +# A +# B B +# C C C +# D D D D +# E E E E E def alphabetpattern(n): num = 65 for i in range(0, n): - for j in range(0, i+1): + for j in range(0, i + 1): ch = chr(num) print(ch, end=" ") num = num + 1 print("\r") + a = 5 alphabetpattern(a) diff --git a/Patterns/patterns.py b/Patterns/patterns.py index a23b463df12..fa8f47c5b49 100644 --- a/Patterns/patterns.py +++ b/Patterns/patterns.py @@ -14,26 +14,29 @@ # * * # * + def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): for i in range(lines): - for j in range(i+1): + for j in range(i + 1): print("* ", end="") print("") print(" ") - for i in range(0,lines): - + for i in range(0, lines): + for j in range(0, (2 * (i - 1)) + 1): print(" ", end="") - + for j in range(0, lines - i): print("*", end=" ") - - print("") + + print("") + if __name__ == "__main__": - main() + main() diff --git a/PingPong/Ball.py b/PingPong/Ball.py index ec1a4a6768f..bd0591733ac 100644 --- a/PingPong/Ball.py +++ b/PingPong/Ball.py @@ -1,6 +1,8 @@ import pygame + pygame.init() + class Ball: def __init__(self, pos, vel, win, rad, minCoord, maxCoord): @@ -12,22 +14,18 @@ def __init__(self, pos, vel, win, rad, minCoord, maxCoord): self.minCoord = minCoord self.maxCoord = maxCoord - def drawBall(self): - pygame.draw.circle(self.win, (255,)*3, self.pos, self.rad, 0) - + pygame.draw.circle(self.win, (255,) * 3, self.pos, self.rad, 0) def doHorizontalFlip(self): self.vel[0] *= -1 - def doVerticalFlip(self): self.vel[1] *= -1 - def borderCollisionCheck(self): if (self.pos[0] <= self.minCoord[0]) or (self.pos[0] >= self.maxCoord[0]): @@ -38,13 +36,11 @@ def borderCollisionCheck(self): self.doVerticalFlip() - def updatePos(self): - self.pos = [self.pos[0]+self.vel[0], self.pos[1]+self.vel[1]] - + self.pos = [self.pos[0] + self.vel[0], self.pos[1] + self.vel[1]] - def checkSlabCollision(self, slabPos): # slab pos = [xmin, ymin, xmax, ymax] + def checkSlabCollision(self, slabPos): # slab pos = [xmin, ymin, xmax, ymax] if ( self.pos[0] + self.rad > slabPos[0] and self.pos[0] - self.rad < slabPos[2] @@ -55,4 +51,4 @@ def checkSlabCollision(self, slabPos): # slab pos = [xmin, ymin, xmax, ymax] if self.pos[0] < slabPos[0] or self.pos[0] > slabPos[2]: self.vel[0] *= -1 if self.pos[1] < slabPos[1] or self.pos[1] > slabPos[3]: - self.vel[1] *= -1 \ No newline at end of file + self.vel[1] *= -1 diff --git a/PingPong/Slab.py b/PingPong/Slab.py index c5fb5d70bec..17b5bbac724 100644 --- a/PingPong/Slab.py +++ b/PingPong/Slab.py @@ -1,31 +1,41 @@ import pygame + pygame.init() + class Slab: def __init__(self, win, size, pos, player, minPos, maxPos): self.win = win self.size = size self.pos = pos - self.player = player #player = 1 or 2 + self.player = player # player = 1 or 2 self.minPos = minPos self.maxPos = maxPos - def draw(self): - pygame.draw.rect(self.win, (255, 255, 255), (self.pos[0], self.pos[1], self.size[0], self.size[1])) - + pygame.draw.rect( + self.win, + (255, 255, 255), + (self.pos[0], self.pos[1], self.size[0], self.size[1]), + ) + def getCoords(self): - return [self.pos[0], self.pos[1], self.pos[0] + self.size[0], self.pos[1] + self.size[1]] - + return [ + self.pos[0], + self.pos[1], + self.pos[0] + self.size[0], + self.pos[1] + self.size[1], + ] + def updatePos(self): keys = pygame.key.get_pressed() if self.player == 1: - if keys[pygame.K_UP] and self.getCoords()[1]> self.minPos[1]: + if keys[pygame.K_UP] and self.getCoords()[1] > self.minPos[1]: self.pos[1] -= 0.3 - if keys[pygame.K_DOWN] and self.getCoords()[3]< self.maxPos[1]: + if keys[pygame.K_DOWN] and self.getCoords()[3] < self.maxPos[1]: self.pos[1] += 0.3 else: - if keys[pygame.K_w] and self.getCoords()[1]> self.minPos[1]: + if keys[pygame.K_w] and self.getCoords()[1] > self.minPos[1]: self.pos[1] -= 0.3 - if keys[pygame.K_s] and self.getCoords()[3]< self.maxPos[1]: - self.pos[1] += 0.3 \ No newline at end of file + if keys[pygame.K_s] and self.getCoords()[3] < self.maxPos[1]: + self.pos[1] += 0.3 diff --git a/PingPong/main.py b/PingPong/main.py index 2892f8c9305..70b6b17d9ea 100644 --- a/PingPong/main.py +++ b/PingPong/main.py @@ -1,20 +1,21 @@ from Ball import Ball from Slab import Slab + import pygame WIDTH = 600 HEIGHT = 600 -BLACK = (0,0,0) -WHITE = (255,)*3 +BLACK = (0, 0, 0) +WHITE = (255,) * 3 pygame.init() -win = pygame.display.set_mode((WIDTH, HEIGHT )) +win = pygame.display.set_mode((WIDTH, HEIGHT)) print("Controls: W&S for player 1 and arrow up and down for player 2") -ball = Ball([300,300 ], [0.3,0.1], win, 10, (0,0), (600,600)) -slab = Slab(win, [10,100], [500, 300], 1, (0, 0), (600, 600)) -slab2 = Slab(win, [10,100], [100, 300], 2, (0, 0), (600, 600)) +ball = Ball([300, 300], [0.3, 0.1], win, 10, (0, 0), (600, 600)) +slab = Slab(win, [10, 100], [500, 300], 1, (0, 0), (600, 600)) +slab2 = Slab(win, [10, 100], [100, 300], 2, (0, 0), (600, 600)) run = True while run: for event in pygame.event.get(): @@ -37,4 +38,4 @@ slab2.draw() pygame.display.update() -pygame.quit() \ No newline at end of file +pygame.quit() diff --git a/PongPong_Game/pong/__init__.py b/PongPong_Game/pong/__init__.py index 8b137891791..e69de29bb2d 100644 --- a/PongPong_Game/pong/__init__.py +++ b/PongPong_Game/pong/__init__.py @@ -1 +0,0 @@ - diff --git a/PongPong_Game/pong/ball.py b/PongPong_Game/pong/ball.py index a60e0bf666a..835cff98ee8 100644 --- a/PongPong_Game/pong/ball.py +++ b/PongPong_Game/pong/ball.py @@ -1,17 +1,18 @@ # ./PongPong/pong/ball.py -import pyglet import random from typing import Tuple +import pyglet + class BallObject(pyglet.shapes.Circle): def __init__(self, *args, **kwargs): - super(BallObject, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.color = (255, 180, 0) self.velocity_x, self.velocity_y = 0.0, 0.0 - def update(self, win_size: Tuple, border: Tuple, other_object, dt) -> None: + def update(self, win_size: tuple, border: tuple, other_object, dt) -> None: speed = [ 2.37, 2.49, diff --git a/PongPong_Game/pong/load.py b/PongPong_Game/pong/load.py index f06ff73da4e..51fa275ada4 100644 --- a/PongPong_Game/pong/load.py +++ b/PongPong_Game/pong/load.py @@ -1,10 +1,11 @@ # ./PongPong/pong/load.py -from . import ball, paddle, rectangle from typing import Tuple +from . import ball, paddle, rectangle + -def load_balls(win_size: Tuple, radius: float, speed: Tuple, batch=None): +def load_balls(win_size: tuple, radius: float, speed: tuple, batch=None): balls = [] ball_x = win_size[0] / 2 ball_y = win_size[1] / 2 @@ -15,11 +16,19 @@ def load_balls(win_size: Tuple, radius: float, speed: Tuple, batch=None): def load_paddles( - paddle_pos: Tuple, width: float, height: float, acc: Tuple, batch=None + paddle_pos: tuple, + width: float, + height: float, + acc: tuple, + batch=None, ): paddles = [] new_paddle = paddle.Paddle( - x=paddle_pos[0], y=paddle_pos[1], width=width, height=height, batch=batch + x=paddle_pos[0], + y=paddle_pos[1], + width=width, + height=height, + batch=batch, ) new_paddle.rightx = new_paddle.x + width new_paddle.acc_left, new_paddle.acc_right = acc[0], acc[1] @@ -27,16 +36,28 @@ def load_paddles( return paddles -def load_rectangles(win_size: Tuple, border: float, batch=None): +def load_rectangles(win_size: tuple, border: float, batch=None): rectangles = [] top = rectangle.RectangleObject( - x=0, y=win_size[1] - border, width=win_size[0], height=border, batch=batch + x=0, + y=win_size[1] - border, + width=win_size[0], + height=border, + batch=batch, ) left = rectangle.RectangleObject( - x=0, y=0, width=border, height=win_size[1], batch=batch + x=0, + y=0, + width=border, + height=win_size[1], + batch=batch, ) right = rectangle.RectangleObject( - x=win_size[0] - border, y=0, width=border, height=win_size[1], batch=batch + x=win_size[0] - border, + y=0, + width=border, + height=win_size[1], + batch=batch, ) rectangles.extend([left, top, right]) return rectangles diff --git a/PongPong_Game/pong/paddle.py b/PongPong_Game/pong/paddle.py index f7df52071b0..80394998809 100644 --- a/PongPong_Game/pong/paddle.py +++ b/PongPong_Game/pong/paddle.py @@ -1,20 +1,21 @@ # ./PongPong/pong/paddle.py +from typing import Tuple + import pyglet from pyglet.window import key -from typing import Tuple class Paddle(pyglet.shapes.Rectangle): def __init__(self, *args, **kwargs): - super(Paddle, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.acc_left, self.acc_right = 0.0, 0.0 self.rightx = 0 self.key_handler = key.KeyStateHandler() self.event_handlers = [self, self.key_handler] - def update(self, win_size: Tuple, border: float, other_object, dt): + def update(self, win_size: tuple, border: float, other_object, dt): newlx = self.x + self.acc_left newrx = self.x + self.acc_right diff --git a/PongPong_Game/pong/rectangle.py b/PongPong_Game/pong/rectangle.py index 90768633281..c2800721300 100644 --- a/PongPong_Game/pong/rectangle.py +++ b/PongPong_Game/pong/rectangle.py @@ -5,4 +5,4 @@ class RectangleObject(pyglet.shapes.Rectangle): def __init__(self, *args, **kwargs): - super(RectangleObject, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) diff --git a/PongPong_Game/pongpong.py b/PongPong_Game/pongpong.py index b9afd45bae7..52a0e401c11 100644 --- a/PongPong_Game/pongpong.py +++ b/PongPong_Game/pongpong.py @@ -19,17 +19,24 @@ class PongPongWindow(pyglet.window.Window): def __init__(self, *args, **kwargs): - super(PongPongWindow, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.win_size = (WIDTH, HEIGHT) self.paddle_pos = (WIDTH / 2 - PWIDTH / 2, 0) self.main_batch = pyglet.graphics.Batch() self.walls = load.load_rectangles(self.win_size, BORDER, batch=self.main_batch) self.balls = load.load_balls( - self.win_size, RADIUS, speed=ballspeed, batch=self.main_batch + self.win_size, + RADIUS, + speed=ballspeed, + batch=self.main_batch, ) self.paddles = load.load_paddles( - self.paddle_pos, PWIDTH, PHEIGHT, acc=paddleacc, batch=self.main_batch + self.paddle_pos, + PWIDTH, + PHEIGHT, + acc=paddleacc, + batch=self.main_batch, ) def on_draw(self): diff --git a/Program to reverse Linked List( Recursive solution).py b/Program to reverse Linked List( Recursive solution).py index 96263c6a276..76914074285 100644 --- a/Program to reverse Linked List( Recursive solution).py +++ b/Program to reverse Linked List( Recursive solution).py @@ -1,6 +1,7 @@ -from sys import stdin, setrecursionlimit +from sys import setrecursionlimit, stdin + +setrecursionlimit(10**6) -setrecursionlimit(10 ** 6) # Following is the Node class already written for the Linked List class Node: diff --git a/Python Distance.py b/Python Distance.py index 5ac0e09fc36..919f1e1528f 100644 --- a/Python Distance.py +++ b/Python Distance.py @@ -6,8 +6,8 @@ # terms = int(input("How many terms? ")) # use anonymous function -result = list(map(lambda x: 2 ** x, range(terms))) +result = list(map(lambda x: 2**x, range(terms))) -print("The total terms are:",terms) +print("The total terms are:", terms) for i in range(terms): - print("2 raised to power",i,"is",result[i]) + print("2 raised to power", i, "is", result[i]) diff --git a/Python Program for Product of unique prime factors of a number.py b/Python Program for Product of unique prime factors of a number.py index 594f032750e..1018f51be56 100644 --- a/Python Program for Product of unique prime factors of a number.py +++ b/Python Program for Product of unique prime factors of a number.py @@ -1,29 +1,29 @@ -# Python program to find sum of given -# series. - -def productPrimeFactors(n): - product = 1 - - for i in range(2, n+1): - if (n % i == 0): - isPrime = 1 - - for j in range(2, int(i/2 + 1)): - if (i % j == 0): - isPrime = 0 - break - - # condition if \'i\' is Prime number - # as well as factor of num - if (isPrime): - product = product * i - - return product - - - -# main() +# Python program to find sum of given +# series. + + +def productPrimeFactors(n): + product = 1 + + for i in range(2, n + 1): + if n % i == 0: + isPrime = 1 + + for j in range(2, int(i / 2 + 1)): + if i % j == 0: + isPrime = 0 + break + + # condition if \'i\' is Prime number + # as well as factor of num + if isPrime: + product = product * i + + return product + + +# main() n = 44 -print (productPrimeFactors(n)) +print(productPrimeFactors(n)) -# Contributed by _omg +# Contributed by _omg diff --git a/Python Program for Tower of Hanoi.py b/Python Program for Tower of Hanoi.py index 7efb1b56363..00c8eb96ce0 100644 --- a/Python Program for Tower of Hanoi.py +++ b/Python Program for Tower of Hanoi.py @@ -1,10 +1,12 @@ -# Recursive Python function to solve the tower of hanoi -def TowerOfHanoi(n , source, destination, auxiliary): - if n==1: - print("Move disk 1 from source ",source," to destination ",destination) - return - TowerOfHanoi(n-1, source, auxiliary, destination) - print("Move disk ",n," from source ",source," to destination ",destination) - TowerOfHanoi(n-1, auxiliary, destination, source) +# Recursive Python function to solve the tower of hanoi +def TowerOfHanoi(n, source, destination, auxiliary): + if n == 1: + print("Move disk 1 from source ", source, " to destination ", destination) + return + TowerOfHanoi(n - 1, source, auxiliary, destination) + print("Move disk ", n, " from source ", source, " to destination ", destination) + TowerOfHanoi(n - 1, auxiliary, destination, source) + + n = 4 -TowerOfHanoi(n,'A','B','C') +TowerOfHanoi(n, "A", "B", "C") diff --git a/Python Program for factorial of a number b/Python Program for factorial of a number index fb75b99de87..c2904e9b351 100644 --- a/Python Program for factorial of a number +++ b/Python Program for factorial of a number @@ -1,38 +1,38 @@ """ Factorial of a non-negative integer, is multiplication of -all integers smaller than or equal to n. +all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. """ """ Recursive: -Python3 program to find factorial of given number +Python3 program to find factorial of given number """ -def factorial(n): - - # single line to find factorial - return 1 if (n==1 or n==0) else n * factorial(n - 1); - -# Driver Code -num = 5; +def factorial(n): + + # single line to find factorial + return 1 if (n==1 or n==0) else n * factorial(n - 1); + +# Driver Code +num = 5; print("Factorial of",num,"is", factorial((num))) """ Iterative: Python 3 program to find factorial of given number. -""" -def factorial(n): - if n < 0: +""" +def factorial(n): + if n < 0: return 0 - elif n == 0 or n == 1: + elif n == 0 or n == 1: return 1 - else: + else: fact = 1 - while(n > 1): - fact *= n + while(n > 1): + fact *= n n -= 1 - return fact - -# Driver Code -num = 5; + return fact + +# Driver Code +num = 5; print("Factorial of",num,"is", factorial(num)) diff --git a/Python Program to Count the Number of Each Vowel.py b/Python Program to Count the Number of Each Vowel.py index 297e2488590..eb66d0967d6 100644 --- a/Python Program to Count the Number of Each Vowel.py +++ b/Python Program to Count the Number of Each Vowel.py @@ -1,19 +1,19 @@ # Program to count the number of each vowels # string of vowels -vowels = 'aeiou' +vowels = "aeiou" -ip_str = 'Hello, have you tried our tutorial section yet?' +ip_str = "Hello, have you tried our tutorial section yet?" # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 -count = {}.fromkeys(vowels,0) +count = {}.fromkeys(vowels, 0) # count the vowels for char in ip_str: - if char in count: - count[char] += 1 + if char in count: + count[char] += 1 print(count) diff --git a/Python Program to Display Fibonacci Sequence Using Recursion.py b/Python Program to Display Fibonacci Sequence Using Recursion.py index 5a70deb0e28..7bfb6b7a03a 100644 --- a/Python Program to Display Fibonacci Sequence Using Recursion.py +++ b/Python Program to Display Fibonacci Sequence Using Recursion.py @@ -1,15 +1,16 @@ def recur_fibo(n): - if n <= 1: - return n - else: - return(recur_fibo(n-1) + recur_fibo(n-2)) + if n <= 1: + return n + else: + return recur_fibo(n - 1) + recur_fibo(n - 2) + nterms = 10 # check if the number of terms is valid if nterms <= 0: - print("Please enter a positive integer") + print("Please enter a positive integer") else: - print("Fibonacci sequence:") - for i in range(nterms): - print(recur_fibo(i)) + print("Fibonacci sequence:") + for i in range(nterms): + print(recur_fibo(i)) diff --git a/Python Program to Find LCM.py b/Python Program to Find LCM.py index 6e9cf1cc8a1..573ae0557d9 100644 --- a/Python Program to Find LCM.py +++ b/Python Program to Find LCM.py @@ -1,20 +1,22 @@ # Python Program to find the L.C.M. of two input number + def compute_lcm(x, y): - # choose the greater number - if x > y: - greater = x - else: - greater = y + # choose the greater number + if x > y: + greater = x + else: + greater = y + + while True: + if (greater % x == 0) and (greater % y == 0): + lcm = greater + break + greater += 1 - while(True): - if((greater % x == 0) and (greater % y == 0)): - lcm = greater - break - greater += 1 + return lcm - return lcm num1 = 54 num2 = 24 diff --git a/Python Program to Merge Mails.py b/Python Program to Merge Mails.py index 2d18c6dbaee..8cbccc01da4 100644 --- a/Python Program to Merge Mails.py +++ b/Python Program to Merge Mails.py @@ -3,10 +3,10 @@ # Body of the mail is in body.txt # open names.txt for reading -with open("names.txt", 'r', encoding='utf-8') as names_file: +with open("names.txt", encoding="utf-8") as names_file: # open body.txt for reading - with open("body.txt", 'r', encoding='utf-8') as body_file: + with open("body.txt", encoding="utf-8") as body_file: # read entire content of the body body = body_file.read() @@ -16,6 +16,5 @@ mail = "Hello " + name.strip() + "\n" + body # write the mails to individual files - with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file: + with open(name.strip() + ".txt", "w", encoding="utf-8") as mail_file: mail_file.write(mail) - diff --git a/Python Program to Print the Fibonacci sequence.py b/Python Program to Print the Fibonacci sequence.py index 9f6b1b3d7ce..d6a70a574cd 100644 --- a/Python Program to Print the Fibonacci sequence.py +++ b/Python Program to Print the Fibonacci sequence.py @@ -8,16 +8,16 @@ # check if the number of terms is valid if nterms <= 0: - print("Please enter a positive integer") + print("Please enter a positive integer") elif nterms == 1: - print("Fibonacci sequence upto",nterms,":") - print(n1) + print("Fibonacci sequence upto", nterms, ":") + print(n1) else: - print("Fibonacci sequence:") - while count < nterms: - print(n1) - nth = n1 + n2 - # update values - n1 = n2 - n2 = nth - count += 1 + print("Fibonacci sequence:") + while count < nterms: + print(n1) + nth = n1 + n2 + # update values + n1 = n2 + n2 = nth + count += 1 diff --git a/Python Program to Remove Punctuations from a String.py b/Python Program to Remove Punctuations from a String.py index a1e750a3a4b..6154c73a11b 100644 --- a/Python Program to Remove Punctuations from a String.py +++ b/Python Program to Remove Punctuations from a String.py @@ -1,5 +1,5 @@ # define punctuation -punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' +punctuations = r"""!()-[]{};:'"\,<>./?@#$%^&*_~""" my_str = "Hello!!!, he said ---and went." @@ -9,8 +9,8 @@ # remove punctuation from the string no_punct = "" for char in my_str: - if char not in punctuations: - no_punct = no_punct + char + if char not in punctuations: + no_punct = no_punct + char # display the unpunctuated string print(no_punct) diff --git a/Python Program to Reverse a linked list.py b/Python Program to Reverse a linked list.py index c3eff50ebab..fb081b2fb59 100644 --- a/Python Program to Reverse a linked list.py +++ b/Python Program to Reverse a linked list.py @@ -1,57 +1,59 @@ -# Python program to reverse a linked list -# Time Complexity : O(n) -# Space Complexity : O(1) - -# Node class -class Node: - - # Constructor to initialize the node object - def __init__(self, data): - self.data = data - self.next = None - -class LinkedList: - - # Function to initialize head - def __init__(self): - self.head = None - - # Function to reverse the linked list - def reverse(self): - prev = None - current = self.head - while(current is not None): - next = current.next - current.next = prev - prev = current - current = next - self.head = prev - - # Function to insert a new node at the beginning - def push(self, new_data): - new_node = Node(new_data) - new_node.next = self.head - self.head = new_node - - # Utility function to print the linked LinkedList - def printList(self): - temp = self.head - while(temp): - print(temp.data) - temp = temp.next - - -# Driver program to test above functions -llist = LinkedList() -llist.push(20) -llist.push(4) -llist.push(15) -llist.push(85) +# Python program to reverse a linked list +# Time Complexity : O(n) +# Space Complexity : O(1) + + +# Node class +class Node: + + # Constructor to initialize the node object + def __init__(self, data): + self.data = data + self.next = None + + +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # Function to reverse the linked list + def reverse(self): + prev = None + current = self.head + while current is not None: + next = current.next + current.next = prev + prev = current + current = next + self.head = prev + + # Function to insert a new node at the beginning + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + # Utility function to print the linked LinkedList + def printList(self): + temp = self.head + while temp: + print(temp.data) + temp = temp.next + + +# Driver program to test above functions +llist = LinkedList() +llist.push(20) +llist.push(4) +llist.push(15) +llist.push(85) print("Given Linked List") -llist.printList() -llist.reverse() +llist.printList() +llist.reverse() print("\nReversed Linked List") -llist.printList() +llist.printList() -# This code is contributed by Nikhil Kumar Singh(nickzuck_007) +# This code is contributed by Nikhil Kumar Singh(nickzuck_007) diff --git a/Python Program to Sort Words in Alphabetic Order.py b/Python Program to Sort Words in Alphabetic Order.py index 3e4bd3564e5..737f88c5a8e 100644 --- a/Python Program to Sort Words in Alphabetic Order.py +++ b/Python Program to Sort Words in Alphabetic Order.py @@ -1,23 +1,23 @@ # Program to sort words alphabetically and put them in a dictionary with corresponding numbered keys -# We are also removing punctuation to ensure the desired output, without importing a library for assistance. +# We are also removing punctuation to ensure the desired output, without importing a library for assistance. # Declare base variables word_Dict = {} count = 0 my_str = "Hello this Is an Example With cased letters. Hello, this is a good string" -#Initialize punctuation -punctuations = '''!()-[]{};:'",<>./?@#$%^&*_~''' +# Initialize punctuation +punctuations = """!()-[]{};:'",<>./?@#$%^&*_~""" # To take input from the user -#my_str = input("Enter a string: ") +# my_str = input("Enter a string: ") # remove punctuation from the string and use an empty variable to put the alphabetic characters into no_punct = "" for char in my_str: - if char not in punctuations: - no_punct = no_punct + char + if char not in punctuations: + no_punct = no_punct + char -# Make all words in string lowercase. my_str now equals the original string without the punctuation +# Make all words in string lowercase. my_str now equals the original string without the punctuation my_str = no_punct.lower() # breakdown the string into a list of words @@ -36,7 +36,7 @@ # insert sorted words into dictionary with key for word in new_Word_List: - count+=1 + count += 1 word_Dict[count] = word print(word_Dict) diff --git a/Python Program to Transpose a Matrix.py b/Python Program to Transpose a Matrix.py index 98f6dcba024..17a0be7559d 100644 --- a/Python Program to Transpose a Matrix.py +++ b/Python Program to Transpose a Matrix.py @@ -1,15 +1,19 @@ -X = [[12,7], - [4 ,5], - [3 ,8]] +X = [ + [12, 7], + [4, 5], + [3, 8], +] -result = [[0,0,0], - [0,0,0]] +result = [ + [0, 0, 0], + [0, 0, 0], +] # iterate through rows for i in range(len(X)): - # iterate through columns - for j in range(len(X[0])): - result[j][i] = X[i][j] + # iterate through columns + for j in range(len(X[0])): + result[j][i] = X[i][j] for r in result: - print(r) + print(r) diff --git a/Python-Array-Equilibrium-Index.py b/Python-Array-Equilibrium-Index.py index 0aac8fbf995..50a7d07f11a 100644 --- a/Python-Array-Equilibrium-Index.py +++ b/Python-Array-Equilibrium-Index.py @@ -14,24 +14,28 @@ -7 1 5 2 -4 3 0 Sample Output : 3 """ -def equilibrium(arr): - - # finding the sum of whole array - total_sum = sum(arr) + + +def equilibrium(arr): + + # finding the sum of whole array + total_sum = sum(arr) leftsum = 0 - for i, num in enumerate(arr): - - # total_sum is now right sum - # for index i - total_sum -= num - - if leftsum == total_sum: - return i - leftsum += num - - # If no equilibrium index found, - # then return -1 + for i, num in enumerate(arr): + + # total_sum is now right sum + # for index i + total_sum -= num + + if leftsum == total_sum: + return i + leftsum += num + + # If no equilibrium index found, + # then return -1 return -1 + + n = int(input()) arr = [int(i) for i in input().strip().split()] print(equilibrium(arr)) diff --git a/Python_swapping.py b/Python_swapping.py index 02b9411bca9..a740662acf0 100644 --- a/Python_swapping.py +++ b/Python_swapping.py @@ -1,18 +1,20 @@ -# Python3 program to swap first -# and last element of a list - -# Swap function -def swapList(newList): - size = len(newList) - - # Swapping - temp = newList[0] - newList[0] = newList[size - 1] - newList[size - 1] = temp - - return newList - -# Driver code -newList = [12, 35, 9, 56, 24] - -print(swapList(newList)) +# Python3 program to swap first +# and last element of a list + + +# Swap function +def swapList(newList): + size = len(newList) + + # Swapping + temp = newList[0] + newList[0] = newList[size - 1] + newList[size - 1] = temp + + return newList + + +# Driver code +newList = [12, 35, 9, 56, 24] + +print(swapList(newList)) diff --git a/QR_code_generator/qrcode.py b/QR_code_generator/qrcode.py index 475f66e99fe..9415a0a6494 100755 --- a/QR_code_generator/qrcode.py +++ b/QR_code_generator/qrcode.py @@ -1,4 +1,5 @@ -import pyqrcode, png +import png +import pyqrcode from pyqrcode import QRCode # Creating QR code after given text "input" diff --git a/QuadraticCalc.py b/QuadraticCalc.py index 305f7e1665a..23f0bbccb76 100644 --- a/QuadraticCalc.py +++ b/QuadraticCalc.py @@ -38,7 +38,7 @@ def findLinear(numbers): # find a & b of linear sequence subs_diff.append((sequence[i]) - num) b, c = findLinear(subs_diff) print( - "Nth term: " + str(a) + "n^2 + " + str(b) + "n + " + str(c) + "Nth term: " + str(a) + "n^2 + " + str(b) + "n + " + str(c), ) # outputs nth term else: print("Sequence is not quadratic") diff --git a/Random Password Generator.py b/Random Password Generator.py index b13262dadf8..f420421d14b 100644 --- a/Random Password Generator.py +++ b/Random Password Generator.py @@ -1,12 +1,11 @@ import random -low="abcdefghijklmnopqrstuvwxyz" -upp="ABCDEFGHIJKLMNOPQRSTUVWXYZ" -num="0123456789" -sym="!@#$%^&*" +low = "abcdefghijklmnopqrstuvwxyz" +upp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +num = "0123456789" +sym = "!@#$%^&*" -all=low+upp+num+sym -length=8 -password="".join(random.sample(all,length)) +all = low + upp + num + sym +length = 8 +password = "".join(random.sample(all, length)) print(password) - diff --git a/RandomDice.py b/RandomDice.py index 404c4b30a72..682aaa47613 100644 --- a/RandomDice.py +++ b/RandomDice.py @@ -5,6 +5,7 @@ from random import randint from tkinter import * + # Function to rool the dice def roll(): text.delete(0.0, END) diff --git a/RandomNumberGame.py b/RandomNumberGame.py index 8b3129234a6..391a90c19b2 100644 --- a/RandomNumberGame.py +++ b/RandomNumberGame.py @@ -1,7 +1,7 @@ """ - hey everyone it is a basic game code using random . in this game computer will randomly chose an number from 1 to 100 and players will have - to guess that which number it is and game will tell him on every guss whether his/her guess is smaller or bigger than the chosen number. it is - a multi player game so it can be played with many players there is no such limitations of user till the size of list. if any one wants to modify + hey everyone it is a basic game code using random . in this game computer will randomly chose an number from 1 to 100 and players will have + to guess that which number it is and game will tell him on every guss whether his/her guess is smaller or bigger than the chosen number. it is + a multi player game so it can be played with many players there is no such limitations of user till the size of list. if any one wants to modify this game he/she is most welcomed. Thank you """ @@ -15,7 +15,7 @@ print( "\n\tRandom Number Game\n\nHello Everyone ! it is just a game of chance in which you have to guess a number" " from 0 to 100 and computer will tell whether your guess is smaller or bigger than the acctual number chossen by the computer . " - "the person with less attempts in guessing the number will be winner ." + "the person with less attempts in guessing the number will be winner .", ) x = input() os.system("cls") diff --git a/Randomnumber.py b/Randomnumber.py index 45d08b4499b..6cd29746f7c 100644 --- a/Randomnumber.py +++ b/Randomnumber.py @@ -3,4 +3,4 @@ # importing the random module from random import randint -print(randint(0,9)) +print(randint(0, 9)) diff --git a/ReadFromCSV.py b/ReadFromCSV.py index f1921bd19e0..9765533748a 100644 --- a/ReadFromCSV.py +++ b/ReadFromCSV.py @@ -1,6 +1,7 @@ __author__ = "vamsi" import pandas as pd # pandas library to read csv file -from matplotlib import pyplot as plt # matplotlib library to visualise the data +from matplotlib import \ + pyplot as plt # matplotlib library to visualise the data from matplotlib import style style.use("ggplot") @@ -8,7 +9,7 @@ """reading data from SalesData.csv file and passing data to dataframe""" -df = pd.read_csv("..\SalesData.csv") # Reading the csv file +df = pd.read_csv(r"..\SalesData.csv") # Reading the csv file x = df[ "SalesID" ].as_matrix() # casting SalesID to list #extracting the column with name SalesID diff --git a/Recursion Visulaizer/recursionVisualizer.py b/Recursion Visulaizer/recursionVisualizer.py index 4ecc495e628..8c948da0f78 100644 --- a/Recursion Visulaizer/recursionVisualizer.py +++ b/Recursion Visulaizer/recursionVisualizer.py @@ -1,5 +1,5 @@ -import turtle import random +import turtle t = turtle.Turtle() num = random.randint(1, 1000) diff --git a/SOUNDEX.py b/SOUNDEX.py index 4d49ca8272e..f16d402db0e 100644 --- a/SOUNDEX.py +++ b/SOUNDEX.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - def SOUNDEX(TERM: str): # Step 0: Covert the TERM to UpperCase diff --git a/Search_Engine/README.md b/Search_Engine/README.md index 36081b0aad8..e630b0b6785 100644 --- a/Search_Engine/README.md +++ b/Search_Engine/README.md @@ -6,4 +6,4 @@ To use directly, run To use a gui, run -```python3 frontend.py``` \ No newline at end of file +```python3 frontend.py``` diff --git a/Search_Engine/backend.py b/Search_Engine/backend.py index f716f5fa16d..2c276d23d4f 100644 --- a/Search_Engine/backend.py +++ b/Search_Engine/backend.py @@ -1,7 +1,9 @@ -import sqlite3 -import test_data import ast import json +import sqlite3 + +import test_data + class SearchEngine: """ @@ -27,9 +29,11 @@ def __init__(self): tables_exist = res.fetchone() if not tables_exist: - self.conn.execute("CREATE TABLE IdToDoc(id INTEGER PRIMARY KEY, document TEXT)") - self.conn.execute('CREATE TABLE WordToId (name TEXT, value TEXT)') - cur.execute("INSERT INTO WordToId VALUES (?, ?)", ("index", "{}",)) + self.conn.execute( + "CREATE TABLE IdToDoc(id INTEGER PRIMARY KEY, document TEXT)" + ) + self.conn.execute("CREATE TABLE WordToId (name TEXT, value TEXT)") + cur.execute("INSERT INTO WordToId VALUES (?, ?)", ("index", "{}")) def index_document(self, document): """ @@ -43,13 +47,15 @@ def index_document(self, document): - passes the document to a method to add the document to IdToDoc - retrieves the id of the inserted document - - uses the id to call the method that adds the words of + - uses the id to call the method that adds the words of the document to the reverse index WordToId if the word has not already been indexed """ row_id = self._add_to_IdToDoc(document) cur = self.conn.cursor() - reverse_idx = cur.execute("SELECT value FROM WordToId WHERE name='index'").fetchone()[0] + reverse_idx = cur.execute( + "SELECT value FROM WordToId WHERE name='index'" + ).fetchone()[0] reverse_idx = json.loads(reverse_idx) document = document.split() for word in document: @@ -60,8 +66,10 @@ def index_document(self, document): reverse_idx[word].append(row_id) reverse_idx = json.dumps(reverse_idx) cur = self.conn.cursor() - result = cur.execute("UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,)) - return("index successful") + result = cur.execute( + "UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,) + ) + return "index successful" def _add_to_IdToDoc(self, document): """ @@ -88,7 +96,9 @@ def find_documents(self, search_term): - return the result of the called method """ cur = self.conn.cursor() - reverse_idx = cur.execute("SELECT value FROM WordToId WHERE name='index'").fetchone()[0] + reverse_idx = cur.execute( + "SELECT value FROM WordToId WHERE name='index'" + ).fetchone()[0] reverse_idx = json.loads(reverse_idx) search_term = search_term.split(" ") all_docs_with_search_term = [] @@ -96,18 +106,18 @@ def find_documents(self, search_term): if term in reverse_idx: all_docs_with_search_term.append(reverse_idx[term]) - if not all_docs_with_search_term: # the search term does not exist + if not all_docs_with_search_term: # the search term does not exist return [] common_idx_of_docs = set(all_docs_with_search_term[0]) for idx in all_docs_with_search_term[1:]: common_idx_of_docs.intersection_update(idx) - if not common_idx_of_docs: # the search term does not exist + if not common_idx_of_docs: # the search term does not exist return [] return self._find_documents_with_idx(common_idx_of_docs) - + def _find_documents_with_idx(self, idxs): """ Returns - list[str]: the list of documents with the idxs @@ -119,11 +129,11 @@ def _find_documents_with_idx(self, idxs): """ idxs = list(idxs) cur = self.conn.cursor() - sql="SELECT document FROM IdToDoc WHERE id in ({seq})".format( - seq=','.join(['?']*len(idxs)) - ) + sql = "SELECT document FROM IdToDoc WHERE id in ({seq})".format( + seq=",".join(["?"] * len(idxs)), + ) result = cur.execute(sql, idxs).fetchall() - return(result) + return result if __name__ == "__main__": @@ -132,4 +142,4 @@ def _find_documents_with_idx(self, idxs): print(se.index_document("happiness is all you need")) se.index_document("no way should we be sad") se.index_document("a cheerful heart is a happy one even in Nigeria") - print(se.find_documents("happy")) \ No newline at end of file + print(se.find_documents("happy")) diff --git a/Search_Engine/frontend.py b/Search_Engine/frontend.py index 93dd7636f19..346665810c6 100644 --- a/Search_Engine/frontend.py +++ b/Search_Engine/frontend.py @@ -1,5 +1,6 @@ from tkinter import * from tkinter import messagebox + import backend @@ -8,15 +9,17 @@ def add_document(): se = backend.SearchEngine() print(se.index_document(document)) + def find_term(): term = find_term_entry.get() se = backend.SearchEngine() print(se.find_documents(term)) + if __name__ == "__main__": root = Tk() root.title("Registration Form") - root.geometry('300x300') + root.geometry("300x300") add_documents_label = Label(root, text="Add Document:") add_documents_label.pack() @@ -34,4 +37,4 @@ def find_term(): search_term_button = Button(root, text="search", command=find_term) search_term_button.pack() - root.mainloop() \ No newline at end of file + root.mainloop() diff --git a/Search_Engine/test_data.py b/Search_Engine/test_data.py index d58f43e7d17..1c6c7b043ed 100644 --- a/Search_Engine/test_data.py +++ b/Search_Engine/test_data.py @@ -2,7 +2,7 @@ "we should all strive to be happy", "happiness is all you need", "a cheerful heart is a happy one", - "no way should we be sad" + "no way should we be sad", ] -search = "happy" \ No newline at end of file +search = "happy" diff --git a/Secret message generator GUI by tkinter.py b/Secret message generator GUI by tkinter.py index ac6bfe49139..14f5c0b4291 100644 --- a/Secret message generator GUI by tkinter.py +++ b/Secret message generator GUI by tkinter.py @@ -47,10 +47,16 @@ ) b.place(x=0, y=270) t1 = tkinter.Label( - root, text="TYPE MESSAGE:", font=("arial", 20, "bold", "underline"), fg="red" + root, + text="TYPE MESSAGE:", + font=("arial", 20, "bold", "underline"), + fg="red", ) t2 = tkinter.Label( - root, text="TYPE SECRET MESSAGE:", font=("arial", 20, "bold", "underline"), fg="red" + root, + text="TYPE SECRET MESSAGE:", + font=("arial", 20, "bold", "underline"), + fg="red", ) t1.place(x=10, y=0) t2.place(x=10, y=220) diff --git a/Shortest Distance between Two Lines.py b/Shortest Distance between Two Lines.py index b60b339acda..ee3205e8ec1 100644 --- a/Shortest Distance between Two Lines.py +++ b/Shortest Distance between Two Lines.py @@ -1,4 +1,5 @@ import math + import numpy as NP LC1 = eval(input("Enter DRs of Line 1 : ")) @@ -7,10 +8,10 @@ LP2 = eval(input("Enter Coordinate through which Line 2 passes : ")) a1, b1, c1, a2, b2, c2 = LC1[0], LC1[1], LC1[2], LC2[0], LC2[1], LC2[2] x = NP.array( - [[LP2[0] - LP1[0], LP2[1] - LP1[1], LP2[2] - LP1[2]], [a1, b1, c1], [a2, b2, c2]] + [[LP2[0] - LP1[0], LP2[1] - LP1[1], LP2[2] - LP1[2]], [a1, b1, c1], [a2, b2, c2]], ) y = math.sqrt( (((b1 * c2) - (b2 * c1)) ** 2) + (((c1 * a2) - (c2 * a1)) ** 2) - + (((a1 * b2) - (b1 * a2)) ** 2) + + (((a1 * b2) - (b1 * a2)) ** 2), ) diff --git a/Snake_water_gun/main.py b/Snake_water_gun/main.py index 23d8b51f5c3..2195f5976a5 100644 --- a/Snake_water_gun/main.py +++ b/Snake_water_gun/main.py @@ -28,7 +28,7 @@ class bcolors: bcolors.OKBLUE + bcolors.BOLD + "Welcome to the game 'Snake-Water-Gun'.\nWanna play? Type Y or N: " - + bcolors.ENDC + + bcolors.ENDC, ).capitalize() if b == "N": @@ -37,7 +37,7 @@ class bcolors: break elif b == "Y" or b == "y": print( - "There will be 10 matches, and the one who wins more matches will win. Let's start." + "There will be 10 matches, and the one who wins more matches will win. Let's start.", ) break else: @@ -90,7 +90,7 @@ class bcolors: bcolors.OKGREEN + bcolors.BOLD + "Woooh!!!!!!! Congratulations you won" - + bcolors.ENDC + + bcolors.ENDC, ) elif score == 5: print("Game draws!!!!!!!") @@ -99,5 +99,5 @@ class bcolors: bcolors.FAIL + bcolors.BOLD + "You lose!!!. Better luck next time" - + bcolors.ENDC + + bcolors.ENDC, ) diff --git a/Sorting Algorithims/heapsort_linkedlist.py b/Sorting Algorithims/heapsort_linkedlist.py index 7e9584077e6..9f535d20ade 100644 --- a/Sorting Algorithims/heapsort_linkedlist.py +++ b/Sorting Algorithims/heapsort_linkedlist.py @@ -3,6 +3,7 @@ def __init__(self, data): self.data = data self.next = None + class LinkedList: def __init__(self): self.head = None @@ -64,6 +65,7 @@ def heap_sort(self): self.swap(0, i) self.heapify(i, 0) + # Example usage: linked_list = LinkedList() linked_list.push(12) diff --git a/Sorting Algorithims/mergesort_linkedlist.py b/Sorting Algorithims/mergesort_linkedlist.py index 429684b6c0c..4e833dc2e29 100644 --- a/Sorting Algorithims/mergesort_linkedlist.py +++ b/Sorting Algorithims/mergesort_linkedlist.py @@ -1,10 +1,12 @@ from __future__ import annotations + class Node: def __init__(self, data: int) -> None: self.data = data self.next = None + class LinkedList: def __init__(self): self.head = None @@ -17,13 +19,14 @@ def insert(self, new_data: int) -> None: def printLL(self) -> None: temp = self.head if temp == None: - return 'Linked List is empty' + return "Linked List is empty" while temp.next: - print(temp.data, '->', end='') + print(temp.data, "->", end="") temp = temp.next print(temp.data) return + # Merge two sorted linked lists def merge(left, right): if not left: @@ -40,6 +43,7 @@ def merge(left, right): return result + # Merge sort for linked list def merge_sort(head): if not head or not head.next: @@ -61,9 +65,12 @@ def merge_sort(head): return merge(left, right) + if __name__ == "__main__": ll = LinkedList() - print("Enter the space-separated values of numbers to be inserted in the linked list prompted below:") + print( + "Enter the space-separated values of numbers to be inserted in the linked list prompted below:" + ) arr = list(map(int, input().split())) for num in arr: ll.insert(num) @@ -73,5 +80,5 @@ def merge_sort(head): ll.head = merge_sort(ll.head) - print('Linked list after sorting:') + print("Linked list after sorting:") ll.printLL() diff --git a/Sorting Algorithims/quicksort_linkedlist.py b/Sorting Algorithims/quicksort_linkedlist.py index 97de82e2bc2..70804343a98 100644 --- a/Sorting Algorithims/quicksort_linkedlist.py +++ b/Sorting Algorithims/quicksort_linkedlist.py @@ -1,8 +1,9 @@ """ -Given a linked list with head pointer, +Given a linked list with head pointer, sort the linked list using quicksort technique without using any extra space Time complexity: O(NlogN), Space complexity: O(1) """ + from __future__ import annotations @@ -26,13 +27,14 @@ def insert(self, new_data: int) -> None: def printLL(self) -> None: temp = self.head if temp == None: - return 'Linked List is empty' + return "Linked List is empty" while temp.next: - print(temp.data, '->', end='') + print(temp.data, "->", end="") temp = temp.next print(temp.data) return + # Partition algorithm with pivot as first element @@ -65,12 +67,14 @@ def quicksort_LL(start, end): if __name__ == "__main__": ll = LinkedList() - print("Enter the space seperated values of numbers to be inserted in linkedlist prompted below:") + print( + "Enter the space seperated values of numbers to be inserted in linkedlist prompted below:" + ) arr = list(map(int, input().split())) for num in arr: ll.insert(num) print("Linkedlist before sorting:") ll.printLL() quicksort_LL(ll.head, None) - print('Linkedlist after sorting: ') + print("Linkedlist after sorting: ") ll.printLL() diff --git a/Sorting Algorithms/Bubble_sort.py b/Sorting Algorithms/Bubble_sort.py index 258c3641f00..d8a7b02cadf 100644 --- a/Sorting Algorithms/Bubble_sort.py +++ b/Sorting Algorithms/Bubble_sort.py @@ -9,7 +9,7 @@ def bubble_sort(Lists): # Lets the user enter values of an array and verify by himself/herself array = [] array_length = int( - input("Enter the number of elements of array or enter the length of array") + input("Enter the number of elements of array or enter the length of array"), ) for i in range(array_length): value = int(input("Enter the value in the array")) diff --git a/Sorting Algorithms/Counting-sort.py b/Sorting Algorithms/Counting-sort.py index 34b1667762d..0b3326b563a 100644 --- a/Sorting Algorithms/Counting-sort.py +++ b/Sorting Algorithms/Counting-sort.py @@ -7,7 +7,6 @@ def counting_sort(tlist, k, n): - """Counting sort algo with sort in place. Args: tlist: target list to sort diff --git a/Sorting Algorithms/Heap sort.py b/Sorting Algorithms/Heap sort.py index 69aa753c283..523668698a0 100644 --- a/Sorting Algorithms/Heap sort.py +++ b/Sorting Algorithms/Heap sort.py @@ -1,5 +1,6 @@ # Python program for implementation of heap Sort + # To heapify subtree rooted at index i. # n is size of heap def heapify(arr, n, i): diff --git a/Sorting Algorithms/Iterative Merge Sort.py b/Sorting Algorithms/Iterative Merge Sort.py index 63173b6bf5c..0b518478449 100644 --- a/Sorting Algorithms/Iterative Merge Sort.py +++ b/Sorting Algorithms/Iterative Merge Sort.py @@ -1,5 +1,6 @@ # Iterative Merge sort (Bottom Up) + # Iterative mergesort function to # sort arr[0...n-1] def mergeSort(a): diff --git a/Sorting Algorithms/Tim_sort.py b/Sorting Algorithms/Tim_sort.py index 9cbbb313e5d..0203d54d988 100644 --- a/Sorting Algorithms/Tim_sort.py +++ b/Sorting Algorithms/Tim_sort.py @@ -1,5 +1,5 @@ """ Author : Mohit Kumar - + Tim Sort implemented in python Time Complexity : O(n log(n)) Space Complexity :O(n) @@ -9,6 +9,7 @@ # Python3 program to perform TimSort. RUN = 32 + # This function sorts array from left index to # to right index which is of size atmost RUN def insertionSort(arr, left, right): @@ -119,13 +120,13 @@ def printArray(arr, n): print("After Sorting Array is") printArray(arr, n) -""" - OUTPUT : - +""" + OUTPUT : + Enter size of array : 5 Given Array is - 5 3 4 2 1 + 5 3 4 2 1 After Sorting Array is 1 2 3 4 5 - + """ diff --git a/String_Palindrome.py b/String_Palindrome.py index 6b8302b6477..073ab5b47e4 100644 --- a/String_Palindrome.py +++ b/String_Palindrome.py @@ -1,6 +1,6 @@ # Program to check if a string is palindrome or not -my_str = 'aIbohPhoBiA' +my_str = "aIbohPhoBiA" # make it suitable for caseless comparison my_str = my_str.casefold() @@ -10,6 +10,6 @@ # check if the string is equal to its reverse if list(my_str) == list(rev_str): - print("The string is a palindrome.") + print("The string is a palindrome.") else: - print("The string is not a palindrome.") + print("The string is not a palindrome.") diff --git a/Strings.py b/Strings.py index 9c76b0a872a..5c3689ed841 100644 --- a/Strings.py +++ b/Strings.py @@ -16,8 +16,8 @@ # Creating String with triple # Quotes allows multiple lines -String1 = """Smile - For +String1 = """Smile + For Life""" print("\nCreating a multiline String: ") print(String1) diff --git a/Sum of digits of a number.py b/Sum of digits of a number.py index c000547c7bc..4d017d57606 100644 --- a/Sum of digits of a number.py +++ b/Sum of digits of a number.py @@ -2,32 +2,42 @@ import sys + def get_integer(): - for i in range(3,0,-1): # executes the loop 3 times. Giving 3 chances to the user. + for i in range( + 3, 0, -1 + ): # executes the loop 3 times. Giving 3 chances to the user. num = input("enter a number:") - if num.isnumeric(): # checks if entered input is an integer string or not. - num = int(num) # converting integer string to integer. And returns it to where function is called. + if num.isnumeric(): # checks if entered input is an integer string or not. + num = int( + num + ) # converting integer string to integer. And returns it to where function is called. return num else: - print("enter integer only") - print(f'{i-1} chances are left' if (i-1)>1 else f'{i-1} chance is left') # prints if user entered wrong input and chances left. - continue - + print("enter integer only") + print( + f"{i-1} chances are left" if (i - 1) > 1 else f"{i-1} chance is left" + ) # prints if user entered wrong input and chances left. + continue + def addition(num): - Sum=0 - if type(num) is type(None): # Checks if number type is none or not. If type is none program exits. + Sum = 0 + if type(num) is type( + None + ): # Checks if number type is none or not. If type is none program exits. print("Try again!") sys.exit() - while num > 0: # Addition- adding the digits in the number. + while num > 0: # Addition- adding the digits in the number. digit = int(num % 10) Sum += digit num /= 10 - return Sum # Returns sum to where the function is called. - + return Sum # Returns sum to where the function is called. -if __name__ == '__main__': # this is used to overcome the problems while importing this file. +if ( + __name__ == "__main__" +): # this is used to overcome the problems while importing this file. number = get_integer() Sum = addition(number) - print(f'Sum of digits of {number} is {Sum}') # Prints the sum + print(f"Sum of digits of {number} is {Sum}") # Prints the sum diff --git a/TIC_TAC_TOE/index.py b/TIC_TAC_TOE/index.py index 7e494d0e700..5b621eae4db 100644 --- a/TIC_TAC_TOE/index.py +++ b/TIC_TAC_TOE/index.py @@ -3,19 +3,26 @@ def print_board(board): print(" | ".join(row)) print("-" * 9) + def check_winner(board, player): for i in range(3): # Check rows and columns - if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)): + if all(board[i][j] == player for j in range(3)) or all( + board[j][i] == player for j in range(3) + ): return True # Check diagonals - if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)): + if all(board[i][i] == player for i in range(3)) or all( + board[i][2 - i] == player for i in range(3) + ): return True return False + def is_full(board): return all(cell != " " for row in board for cell in row) + def main(): board = [[" " for _ in range(3)] for _ in range(3)] player = "X" @@ -42,5 +49,6 @@ def main(): else: print("Invalid move. Try again.") + if __name__ == "__main__": main() diff --git a/TTS.py b/TTS.py index a151388ce21..0076c43f61d 100644 --- a/TTS.py +++ b/TTS.py @@ -1,5 +1,5 @@ -from tkinter import * from platform import system +from tkinter import * if system() == "Windows" or "nt": import win32com.client as wincl diff --git a/TaskManager.py b/TaskManager.py index 250eb05323b..f76002aa5cf 100644 --- a/TaskManager.py +++ b/TaskManager.py @@ -1,31 +1,38 @@ -import datetime import csv +import datetime -def load_tasks(filename='tasks.csv'): + +def load_tasks(filename="tasks.csv"): tasks = [] - with open(filename, 'r', newline='') as file: + with open(filename, newline="") as file: reader = csv.reader(file) for row in reader: - tasks.append({'task': row[0], 'deadline': row[1], 'completed': row[2]}) + tasks.append({"task": row[0], "deadline": row[1], "completed": row[2]}) return tasks -def save_tasks(tasks, filename='tasks.csv'): - with open(filename, 'w', newline='') as file: + +def save_tasks(tasks, filename="tasks.csv"): + with open(filename, "w", newline="") as file: writer = csv.writer(file) for task in tasks: - writer.writerow([task['task'], task['deadline'], task['completed']]) + writer.writerow([task["task"], task["deadline"], task["completed"]]) + def add_task(task, deadline): tasks = load_tasks() - tasks.append({'task': task, 'deadline': deadline, 'completed': 'No'}) + tasks.append({"task": task, "deadline": deadline, "completed": "No"}) save_tasks(tasks) print("Task added successfully!") + def show_tasks(): tasks = load_tasks() for task in tasks: - print(f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}") + print( + f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}" + ) + # Example usage -add_task('Write daily report', '2024-04-20') +add_task("Write daily report", "2024-04-20") show_tasks() diff --git a/TaskPlanner.py b/TaskPlanner.py index 250eb05323b..f76002aa5cf 100644 --- a/TaskPlanner.py +++ b/TaskPlanner.py @@ -1,31 +1,38 @@ -import datetime import csv +import datetime -def load_tasks(filename='tasks.csv'): + +def load_tasks(filename="tasks.csv"): tasks = [] - with open(filename, 'r', newline='') as file: + with open(filename, newline="") as file: reader = csv.reader(file) for row in reader: - tasks.append({'task': row[0], 'deadline': row[1], 'completed': row[2]}) + tasks.append({"task": row[0], "deadline": row[1], "completed": row[2]}) return tasks -def save_tasks(tasks, filename='tasks.csv'): - with open(filename, 'w', newline='') as file: + +def save_tasks(tasks, filename="tasks.csv"): + with open(filename, "w", newline="") as file: writer = csv.writer(file) for task in tasks: - writer.writerow([task['task'], task['deadline'], task['completed']]) + writer.writerow([task["task"], task["deadline"], task["completed"]]) + def add_task(task, deadline): tasks = load_tasks() - tasks.append({'task': task, 'deadline': deadline, 'completed': 'No'}) + tasks.append({"task": task, "deadline": deadline, "completed": "No"}) save_tasks(tasks) print("Task added successfully!") + def show_tasks(): tasks = load_tasks() for task in tasks: - print(f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}") + print( + f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}" + ) + # Example usage -add_task('Write daily report', '2024-04-20') +add_task("Write daily report", "2024-04-20") show_tasks() diff --git a/Test-Case-Generator/test_case.py b/Test-Case-Generator/test_case.py index 05c9e77d60a..0cd7f968116 100644 --- a/Test-Case-Generator/test_case.py +++ b/Test-Case-Generator/test_case.py @@ -4,10 +4,10 @@ # _________________________________________________ ### # _________________________________________________ ### -from tkinter import * -from random import randint, choices -import webbrowser import os +import webbrowser +from random import choices, randint +from tkinter import * mycolor = "#262626" @@ -221,7 +221,11 @@ def display(self): self.x_scroll = Scrollbar(gui, orient=HORIZONTAL) self.y_scroll.grid(row=0, column=11, sticky="NS", pady=(22, 0), padx=(0, 20)) self.x_scroll.grid( - row=1, sticky="EW", columnspan=10, padx=(20, 0), pady=(0, 30) + row=1, + sticky="EW", + columnspan=10, + padx=(20, 0), + pady=(0, 30), ) self.output = Text( gui, @@ -255,7 +259,12 @@ def display(self): bd=3, ) self.copy_button.grid( - row=2, column=3, sticky="SW", ipady=10, pady=(10, 18), padx=15 + row=2, + column=3, + sticky="SW", + ipady=10, + pady=(10, 18), + padx=15, ) self.generate_button = Button( gui, @@ -288,7 +297,12 @@ def display(self): bd=3, ) self.done_button.grid( - row=3, column=3, columnspan=2, ipady=10, pady=(10, 20), padx=5 + row=3, + column=3, + columnspan=2, + ipady=10, + pady=(10, 20), + padx=5, ) self.button_exit_output = Button( gui, @@ -300,7 +314,12 @@ def display(self): command=lambda: gui.destroy(), ) self.button_exit_output.grid( - row=3, column=4, columnspan=2, ipady=10, pady=(10, 20), padx=5 + row=3, + column=4, + columnspan=2, + ipady=10, + pady=(10, 20), + padx=5, ) def try_forget(self): @@ -319,23 +338,34 @@ def try_forget(self): def get_t(self, r): self.test_case_count_label = Label( - gui, text="T = ", font=("calibre", 10, "bold"), width=17 + gui, + text="T = ", + font=("calibre", 10, "bold"), + width=17, ) # Type 1 self.test_case_count = Entry( - gui, textvariable=t, font=("calibre", 10, "normal") + gui, + textvariable=t, + font=("calibre", 10, "normal"), ) self.test_case_count_label.grid(row=r, column=0, pady=20, ipady=1) # Type 1 self.test_case_count.grid(row=r, column=1) def get_n(self, r): self.minimum_value_of_n = Entry( - gui, textvariable=n_min, font=("calibre", 10, "normal") + gui, + textvariable=n_min, + font=("calibre", 10, "normal"), ) self.min_max_values_of_n_label = Label( - gui, text=" <= n <=", font=("calibre", 10, "bold") + gui, + text=" <= n <=", + font=("calibre", 10, "bold"), ) self.maximum_value_of_n = Entry( - gui, textvariable=n_max, font=("calibre", 10, "normal") + gui, + textvariable=n_max, + font=("calibre", 10, "normal"), ) self.minimum_value_of_n.grid(row=r, column=0, padx=10, pady=10) self.min_max_values_of_n_label.grid(row=r, column=1, ipadx=5, ipady=1) @@ -343,13 +373,19 @@ def get_n(self, r): def get_m(self, r): self.minimum_value_of_m = Entry( - gui, textvariable=m_min, font=("calibre", 10, "normal") + gui, + textvariable=m_min, + font=("calibre", 10, "normal"), ) self.min_max_values_of_m_label = Label( - gui, text="<= m <=", font=("calibre", 10, "bold") + gui, + text="<= m <=", + font=("calibre", 10, "bold"), ) self.maximum_value_of_m = Entry( - gui, textvariable=m_max, font=("calibre", 10, "normal") + gui, + textvariable=m_max, + font=("calibre", 10, "normal"), ) self.minimum_value_of_m.grid(row=r, column=0, padx=10, pady=10) self.min_max_values_of_m_label.grid(row=r, column=1, padx=10, ipadx=5, ipady=1) @@ -357,13 +393,19 @@ def get_m(self, r): def get_k(self, r): self.minimum_value_of_k = Entry( - gui, textvariable=k_min, font=("calibre", 10, "normal") + gui, + textvariable=k_min, + font=("calibre", 10, "normal"), ) self.min_max_values_of_k_label = Label( - gui, text=" <= k <=", font=("calibre", 10, "bold") + gui, + text=" <= k <=", + font=("calibre", 10, "bold"), ) self.maximum_value_of_k = Entry( - gui, textvariable=k_max, font=("calibre", 10, "normal") + gui, + textvariable=k_max, + font=("calibre", 10, "normal"), ) self.minimum_value_of_k.grid(row=r, column=0, pady=10) self.min_max_values_of_k_label.grid(row=r, column=1) @@ -371,13 +413,19 @@ def get_k(self, r): def get_a(self, r): self.minimum_value_of_ai = Entry( - gui, textvariable=a_min, font=("calibre", 10, "normal") + gui, + textvariable=a_min, + font=("calibre", 10, "normal"), ) self.min_max_values_of_ai_label = Label( - gui, text=" <= Ai <=", font=("calibre", 10, "bold") + gui, + text=" <= Ai <=", + font=("calibre", 10, "bold"), ) self.maximum_value_of_ai = Entry( - gui, textvariable=a_max, font=("calibre", 10, "normal") + gui, + textvariable=a_max, + font=("calibre", 10, "normal"), ) self.minimum_value_of_ai.grid(row=r, column=0, padx=10, pady=10) self.min_max_values_of_ai_label.grid(row=r, column=1, ipadx=2, ipady=1) @@ -385,13 +433,19 @@ def get_a(self, r): def get_b(self, r): self.minimum_value_of_bi = Entry( - gui, textvariable=b_min, font=("calibre", 10, "normal") + gui, + textvariable=b_min, + font=("calibre", 10, "normal"), ) self.min_max_values_of_bi_label = Label( - gui, text=" <= Bi <= ", font=("calibre", 10, "bold") + gui, + text=" <= Bi <= ", + font=("calibre", 10, "bold"), ) self.maximum_value_of_bi = Entry( - gui, textvariable=b_max, font=("calibre", 10, "normal") + gui, + textvariable=b_max, + font=("calibre", 10, "normal"), ) self.minimum_value_of_bi.grid(row=r, column=0, pady=10) self.min_max_values_of_bi_label.grid(row=r, column=1, padx=10) @@ -399,10 +453,16 @@ def get_b(self, r): def get_char_list(self, r): self.char_list_label = Label( - gui, text=" Characters : ", font=("calibre", 10, "bold"), width=17 + gui, + text=" Characters : ", + font=("calibre", 10, "bold"), + width=17, ) self.char_list = Entry( - gui, textvariable=char_lis, font=("calibre", 10, "normal"), width=43 + gui, + textvariable=char_lis, + font=("calibre", 10, "normal"), + width=43, ) self.char_list.insert(END, "(Space separated characters)") self.char_list.bind("", lambda args: self.char_list.delete("0", "end")) @@ -418,10 +478,18 @@ def show_button(self, r): bd=3, ) self.sub_btn = Button( - gui, text=" GENERATE ", command=self.submit, font="calibre", bd=3 + gui, + text=" GENERATE ", + command=self.submit, + font="calibre", + bd=3, ) self.exit_btn = Button( - gui, text=" EXIT ", command=lambda: gui.destroy(), font="calibre", bd=3 + gui, + text=" EXIT ", + command=lambda: gui.destroy(), + font="calibre", + bd=3, ) self.back_btn.grid(row=r, column=0, pady=(20, 20), ipady=1) self.sub_btn.grid(row=r, column=1, pady=(20, 20), ipady=1) @@ -439,10 +507,12 @@ def submit(self): pass try: self.n_min = min( - int(self.minimum_value_of_n.get()), int(self.maximum_value_of_n.get()) + int(self.minimum_value_of_n.get()), + int(self.maximum_value_of_n.get()), ) self.n_max = max( - int(self.minimum_value_of_n.get()), int(self.maximum_value_of_n.get()) + int(self.minimum_value_of_n.get()), + int(self.maximum_value_of_n.get()), ) if self.n_min > self.n_max or self.n_max == 0 or self.n_max > 10000000: return @@ -452,10 +522,12 @@ def submit(self): pass try: self.m_min = min( - int(self.minimum_value_of_m.get()), int(self.maximum_value_of_m.get()) + int(self.minimum_value_of_m.get()), + int(self.maximum_value_of_m.get()), ) self.m_max = max( - int(self.minimum_value_of_m.get()), int(self.maximum_value_of_m.get()) + int(self.minimum_value_of_m.get()), + int(self.maximum_value_of_m.get()), ) if self.m_min > self.m_max or self.m_max == 0 or self.m_max > 10000000: return @@ -465,10 +537,12 @@ def submit(self): pass try: self.k_min = min( - int(self.minimum_value_of_k.get()), int(self.maximum_value_of_k.get()) + int(self.minimum_value_of_k.get()), + int(self.maximum_value_of_k.get()), ) self.k_max = max( - int(self.minimum_value_of_k.get()), int(self.maximum_value_of_k.get()) + int(self.minimum_value_of_k.get()), + int(self.maximum_value_of_k.get()), ) if self.k_min > self.k_max or self.k_max == 0 or self.k_max > 10000000: return @@ -478,10 +552,12 @@ def submit(self): pass try: self.a_min = min( - int(self.minimum_value_of_ai.get()), int(self.maximum_value_of_ai.get()) + int(self.minimum_value_of_ai.get()), + int(self.maximum_value_of_ai.get()), ) self.a_max = max( - int(self.minimum_value_of_ai.get()), int(self.maximum_value_of_ai.get()) + int(self.minimum_value_of_ai.get()), + int(self.maximum_value_of_ai.get()), ) if self.a_min > self.a_max or self.a_max == 0 or self.a_max > 10000000: return @@ -491,10 +567,12 @@ def submit(self): pass try: self.b_min = min( - int(self.minimum_value_of_bi.get()), int(self.maximum_value_of_bi.get()) + int(self.minimum_value_of_bi.get()), + int(self.maximum_value_of_bi.get()), ) self.b_max = max( - int(self.minimum_value_of_bi.get()), int(self.maximum_value_of_bi.get()) + int(self.minimum_value_of_bi.get()), + int(self.maximum_value_of_bi.get()), ) if self.b_min > self.b_max or self.b_max == 0 or self.b_max > 10000000: return @@ -589,7 +667,7 @@ def forget_testcase_take_input_screen(self, check=0): class Type1(Case): def __init__(self, master): - super(Type1, self).__init__(master) # Type 1 + super().__init__(master) # Type 1 self.forget_home() self.take_input() @@ -621,7 +699,7 @@ def generate(self): # Type 1 class Type2(Case): # Type 2 def __init__(self, master): - super(Type2, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() @@ -656,7 +734,7 @@ def generate(self): # Type 2 class Type3(Case): def __init__(self, master): - super(Type3, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() @@ -685,7 +763,7 @@ def generate(self): # Type 3 class Type4(Case): def __init__(self, master): - super(Type4, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() @@ -733,7 +811,7 @@ def generate(self): # Type 4 class Type5(Case): def __init__(self, master): - super(Type5, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() @@ -766,7 +844,7 @@ def generate(self): # Type 5 class Type6(Case): def __init__(self, master): # Type 6 - super(Type6, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() @@ -807,7 +885,7 @@ def generate(self): # Type 6 class Type7(Case): def __init__(self, master): # Type 7 - super(Type7, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() @@ -836,7 +914,7 @@ def generate(self): # Type 7 class Type8(Case): def __init__(self, master): # Type 8 - super(Type8, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() @@ -874,7 +952,7 @@ def generate(self): # Type 8 class Type9(Case): def __init__(self, master): - super(Type9, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() @@ -901,7 +979,7 @@ def generate(self): # Type 9 class Type10(Case): def __init__(self, master): - super(Type10, self).__init__(master) + super().__init__(master) self.forget_home() self.take_input() diff --git a/ThirdAI/Terms and Conditions/Readme.md b/ThirdAI/Terms and Conditions/Readme.md index da9378a8dcb..9585e2d5cd6 100644 --- a/ThirdAI/Terms and Conditions/Readme.md +++ b/ThirdAI/Terms and Conditions/Readme.md @@ -78,4 +78,3 @@ pip install thirdai ### Dependencies - `thirdai` library - diff --git a/ThirdAI/Terms and Conditions/ThirdAI.py b/ThirdAI/Terms and Conditions/ThirdAI.py index 67d3928ec4b..09443da8b33 100644 --- a/ThirdAI/Terms and Conditions/ThirdAI.py +++ b/ThirdAI/Terms and Conditions/ThirdAI.py @@ -1,4 +1,5 @@ -from thirdai import licensing, neural_db as ndb +from thirdai import licensing +from thirdai import neural_db as ndb class NeuralDBClient: @@ -26,11 +27,11 @@ def query(self, question): search_results = self.db.search( query=question, top_k=2, - on_error=lambda error_msg: print(f"Error! {error_msg}")) + on_error=lambda error_msg: print(f"Error! {error_msg}"), + ) output = "" for result in search_results: output += result.text + "\n\n" return output - diff --git a/ThirdAI/Terms and Conditions/TkinterUI.py b/ThirdAI/Terms and Conditions/TkinterUI.py index 47317636a23..a22d18d5cd9 100644 --- a/ThirdAI/Terms and Conditions/TkinterUI.py +++ b/ThirdAI/Terms and Conditions/TkinterUI.py @@ -1,7 +1,7 @@ import tkinter as tk +from tkinter import filedialog, messagebox from tkinter.font import Font -from tkinter import messagebox -from tkinter import filedialog + from ThirdAI import NeuralDBClient as Ndb @@ -9,6 +9,7 @@ class ThirdAIApp: """ A GUI application for using the ThirdAI neural database client to train and query data. """ + def __init__(self, root): """ Initialize the user interface window. @@ -19,7 +20,7 @@ def __init__(self, root): # Initialize the main window self.root = root self.root.geometry("600x500") - self.root.title('ThirdAI - T&C') + self.root.title("ThirdAI - T&C") # Initialize variables self.path = [] @@ -28,33 +29,69 @@ def __init__(self, root): # GUI elements # Labels and buttons - self.menu = tk.Label(self.root, text="Terms & Conditions", font=self.custom_font(30), fg='black', - highlightthickness=2, highlightbackground="red") + self.menu = tk.Label( + self.root, + text="Terms & Conditions", + font=self.custom_font(30), + fg="black", + highlightthickness=2, + highlightbackground="red", + ) self.menu.place(x=125, y=10) - self.insert_button = tk.Button(self.root, text="Insert File!", font=self.custom_font(15), fg='black', bg="grey", - width=10, command=self.file_input) + self.insert_button = tk.Button( + self.root, + text="Insert File!", + font=self.custom_font(15), + fg="black", + bg="grey", + width=10, + command=self.file_input, + ) self.insert_button.place(x=245, y=100) self.text_box = tk.Text(self.root, wrap=tk.WORD, width=30, height=1) self.text_box.place(x=165, y=150) - self.training_button = tk.Button(self.root, text="Training", font=self.custom_font(15), fg='black', bg="grey", - width=10, command=self.training) + self.training_button = tk.Button( + self.root, + text="Training", + font=self.custom_font(15), + fg="black", + bg="grey", + width=10, + command=self.training, + ) self.training_button.place(x=245, y=195) - self.query_label = tk.Label(self.root, text="Query", font=self.custom_font(20), fg='black') + self.query_label = tk.Label( + self.root, text="Query", font=self.custom_font(20), fg="black" + ) self.query_label.place(x=255, y=255) self.query_entry = tk.Entry(self.root, font=self.custom_font(20), width=30) self.query_entry.place(x=70, y=300) - self.processing_button = tk.Button(self.root, text="Processing", font=self.custom_font(15), fg='black', - bg="grey", width=10, command=self.processing) + self.processing_button = tk.Button( + self.root, + text="Processing", + font=self.custom_font(15), + fg="black", + bg="grey", + width=10, + command=self.processing, + ) self.processing_button.place(x=245, y=355) - self.clear_button = tk.Button(self.root, text="Clear", font=15, fg='black', bg="grey", width=10, - command=self.clear_all) + self.clear_button = tk.Button( + self.root, + text="Clear", + font=15, + fg="black", + bg="grey", + width=10, + command=self.clear_all, + ) self.clear_button.place(x=245, y=405) @staticmethod @@ -96,7 +133,9 @@ def training(self): Train the neural database client with the selected PDF file. """ if not self.path: - messagebox.showwarning("No File Selected", "Please select a PDF file before training.") + messagebox.showwarning( + "No File Selected", "Please select a PDF file before training." + ) return self.client.train(self.path[0]) diff --git a/TicTacToe.py b/TicTacToe.py index f1b61b80df9..f2e83d08799 100644 --- a/TicTacToe.py +++ b/TicTacToe.py @@ -1,183 +1,196 @@ def print_tic_tac_toe(values): print("\n") print("\t | |") - print("\t {} | {} | {}".format(values[0], values[1], values[2])) - print('\t_____|_____|_____') - + print(f"\t {values[0]} | {values[1]} | {values[2]}") + print("\t_____|_____|_____") + print("\t | |") - print("\t {} | {} | {}".format(values[3], values[4], values[5])) - print('\t_____|_____|_____') - + print(f"\t {values[3]} | {values[4]} | {values[5]}") + print("\t_____|_____|_____") + print("\t | |") - - print("\t {} | {} | {}".format(values[6], values[7], values[8])) + + print(f"\t {values[6]} | {values[7]} | {values[8]}") print("\t | |") print("\n") - - + + # Function to print the score-board def print_scoreboard(score_board): print("\t--------------------------------") print("\t SCOREBOARD ") print("\t--------------------------------") - + players = list(score_board.keys()) print("\t ", players[0], "\t ", score_board[players[0]]) print("\t ", players[1], "\t ", score_board[players[1]]) - + print("\t--------------------------------\n") - + + # Function to check if any player has won def check_win(player_pos, cur_player): - + # All possible winning combinations - soln = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]] - + soln = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [1, 4, 7], + [2, 5, 8], + [3, 6, 9], + [1, 5, 9], + [3, 5, 7], + ] + # Loop to check if any winning combination is satisfied for x in soln: if all(y in player_pos[cur_player] for y in x): - + # Return True if any winning combination satisfies return True - # Return False if no combination is satisfied - return False - + # Return False if no combination is satisfied + return False + + # Function to check if the game is drawn def check_draw(player_pos): - if len(player_pos['X']) + len(player_pos['O']) == 9: + if len(player_pos["X"]) + len(player_pos["O"]) == 9: return True - return False - + return False + + # Function for a single game of Tic Tac Toe def single_game(cur_player): - + # Represents the Tic Tac Toe - values = [' ' for x in range(9)] - + values = [" " for x in range(9)] + # Stores the positions occupied by X and O - player_pos = {'X':[], 'O':[]} - + player_pos = {"X": [], "O": []} + # Game Loop for a single game of Tic Tac Toe while True: print_tic_tac_toe(values) - + # Try exception block for MOVE input try: print("Player ", cur_player, " turn. Which box? : ", end="") - move = int(input()) + move = int(input()) except ValueError: print("Wrong Input!!! Try Again") continue - + # Sanity check for MOVE inout if move < 1 or move > 9: print("Wrong Input!!! Try Again") continue - + # Check if the box is not occupied already - if values[move-1] != ' ': + if values[move - 1] != " ": print("Place already filled. Try again!!") continue - + # Update game information - - # Updating grid status - values[move-1] = cur_player - + + # Updating grid status + values[move - 1] = cur_player + # Updating player positions player_pos[cur_player].append(move) - + # Function call for checking win if check_win(player_pos, cur_player): print_tic_tac_toe(values) - print("Player ", cur_player, " has won the game!!") + print("Player ", cur_player, " has won the game!!") print("\n") return cur_player - + # Function call for checking draw game if check_draw(player_pos): print_tic_tac_toe(values) print("Game Drawn") print("\n") - return 'D' - + return "D" + # Switch player moves - if cur_player == 'X': - cur_player = 'O' + if cur_player == "X": + cur_player = "O" else: - cur_player = 'X' - + cur_player = "X" + + if __name__ == "__main__": - + print("Player 1") player1 = input("Enter the name : ") print("\n") - + print("Player 2") player2 = input("Enter the name : ") print("\n") - + # Stores the player who chooses X and O cur_player = player1 - + # Stores the choice of players - player_choice = {'X' : "", 'O' : ""} - + player_choice = {"X": "", "O": ""} + # Stores the options - options = ['X', 'O'] - + options = ["X", "O"] + # Stores the scoreboard score_board = {player1: 0, player2: 0} print_scoreboard(score_board) - + # Game Loop for a series of Tic Tac Toe - # The loop runs until the players quit + # The loop runs until the players quit while True: - + # Player choice Menu print("Turn to choose for", cur_player) print("Enter 1 for X") print("Enter 2 for O") print("Enter 3 to Quit") - + # Try exception for CHOICE input try: - choice = int(input()) + choice = int(input()) except ValueError: print("Wrong Input!!! Try Again\n") continue - - # Conditions for player choice + + # Conditions for player choice if choice == 1: - player_choice['X'] = cur_player + player_choice["X"] = cur_player if cur_player == player1: - player_choice['O'] = player2 + player_choice["O"] = player2 else: - player_choice['O'] = player1 - + player_choice["O"] = player1 + elif choice == 2: - player_choice['O'] = cur_player + player_choice["O"] = cur_player if cur_player == player1: - player_choice['X'] = player2 + player_choice["X"] = player2 else: - player_choice['X'] = player1 - + player_choice["X"] = player1 + elif choice == 3: print("Final Scores") print_scoreboard(score_board) - break - + break + else: print("Wrong Choice!!!! Try Again\n") - + # Stores the winner in a single game of Tic Tac Toe - winner = single_game(options[choice-1]) - + winner = single_game(options[choice - 1]) + # Edits the scoreboard according to the winner - if winner != 'D' : + if winner != "D": player_won = player_choice[winner] score_board[player_won] = score_board[player_won] + 1 - + print_scoreboard(score_board) # Switch player who chooses X or O if cur_player == player1: diff --git a/Tic_Tac_Toe.py b/Tic_Tac_Toe.py index b71b5b1d290..14a93e45a6f 100644 --- a/Tic_Tac_Toe.py +++ b/Tic_Tac_Toe.py @@ -89,7 +89,8 @@ def get_player_move(board): # Let the player type in their move move = " " while move not in "1 2 3 4 5 6 7 8 9".split() or not is_space_free( - board, int(move) + board, + int(move), ): print("What is your next move? (1-9)") move = input() diff --git a/Timetable_Operations.py b/Timetable_Operations.py index 0f75e59e516..979769b9050 100644 --- a/Timetable_Operations.py +++ b/Timetable_Operations.py @@ -48,5 +48,6 @@ # add '0' to the empty spaces (caused by previous operations) in the final result! print( - "final result is :", str(Ht) + ":" + str(Mt) + ":" + str(St) + "final result is :", + str(Ht) + ":" + str(Mt) + ":" + str(St), ) # final result (formatted in clock) diff --git a/To find the largest number between 3 numbers.py b/To find the largest number between 3 numbers.py index 5e7e1575292..1c8e99e8f22 100644 --- a/To find the largest number between 3 numbers.py +++ b/To find the largest number between 3 numbers.py @@ -1,7 +1,6 @@ # Python program to find the largest number among the three input numbers -a=[] +a = [] for i in range(3): a.append(int(input())) -print("The largest among three numbers is:",max(a)) - +print("The largest among three numbers is:", max(a)) diff --git a/Translator/translator.py b/Translator/translator.py index 509be9e6410..ba620c323c7 100644 --- a/Translator/translator.py +++ b/Translator/translator.py @@ -1,6 +1,8 @@ from tkinter import * + from translate import Translator + # Translator function def translate(): translator = Translator(from_lang=lan1.get(), to_lang=lan2.get()) @@ -47,7 +49,10 @@ def translate(): # creating a button to call Translator function b = Button( - mainframe, text="Translate", command=translate, activebackground="green" + mainframe, + text="Translate", + command=translate, + activebackground="green", ).grid(row=4, column=1, columnspan=3) root.mainloop() diff --git a/Triplets with zero sum/Readme.md b/Triplets with zero sum/Readme.md index e79e6ee87d1..37ff4077eba 100644 --- a/Triplets with zero sum/Readme.md +++ b/Triplets with zero sum/Readme.md @@ -2,7 +2,7 @@ Problem : **Given an array of distinct elements. The task is to find triplets in Method : This method uses Sorting to arrive at the correct result and is solved in O(n^2) time. -Approach: +Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element. Algorithm: 1. Sort the array in ascending order. diff --git a/Triplets with zero sum/find_Triplets_with_zero_sum.py b/Triplets with zero sum/find_Triplets_with_zero_sum.py index 2a2d2b7688d..b127a837cc8 100644 --- a/Triplets with zero sum/find_Triplets_with_zero_sum.py +++ b/Triplets with zero sum/find_Triplets_with_zero_sum.py @@ -1,12 +1,12 @@ """ Author : Mohit Kumar - - Python program to find triplets in a given array whose sum is zero + + Python program to find triplets in a given array whose sum is zero """ + # function to print triplets with 0 sum def find_Triplets_with_zero_sum(arr, num): - """find triplets in a given array whose sum is zero Parameteres : @@ -71,10 +71,10 @@ def find_Triplets_with_zero_sum(arr, num): """ SAMPLE INPUT 1 : - Enter size of array : 5 + Enter size of array : 5 Enter elements of array : 0, -1, 2, -3, 1 OUTPUT : - Triplets with 0 sum are as : + Triplets with 0 sum are as : -3 1 2 -1 0 1 COMPLEXITY ANALYSIS : diff --git a/Turn your PDFs into audio books/audiobook_gen.py b/Turn your PDFs into audio books/audiobook_gen.py index cd54bc0a89a..73183634a48 100644 --- a/Turn your PDFs into audio books/audiobook_gen.py +++ b/Turn your PDFs into audio books/audiobook_gen.py @@ -4,8 +4,8 @@ book = open(input("Enter the book name: "), "rb") pg_no = int( input( - "Enter the page number from which you want the system to start reading text: " - ) + "Enter the page number from which you want the system to start reading text: ", + ), ) pdf_Reader = PyPDF2.PdfFileReader(book) diff --git a/Turtle_Star.py b/Turtle_Star.py index 49ce64cb949..d9b1a3b06ef 100644 --- a/Turtle_Star.py +++ b/Turtle_Star.py @@ -1,29 +1,29 @@ import turtle - + board = turtle.Turtle() - + # first triangle for star -board.forward(100) # draw base - +board.forward(100) # draw base + board.left(120) board.forward(100) - + board.left(120) board.forward(100) - + board.penup() board.right(150) board.forward(50) - + # second triangle for star board.pendown() board.right(90) board.forward(100) - + board.right(120) board.forward(100) - + board.right(120) board.forward(100) - + turtle.done() diff --git a/Tweet Pre-Processing.py b/Tweet Pre-Processing.py index 43d3e6c13b3..5a9f9ffaa39 100644 --- a/Tweet Pre-Processing.py +++ b/Tweet Pre-Processing.py @@ -1,14 +1,13 @@ #!/usr/bin/env python -# coding: utf-8 # In[10]: -import numpy as np -from nltk.corpus import twitter_samples -import matplotlib.pyplot as plt import random +import matplotlib.pyplot as plt +import numpy as np +from nltk.corpus import twitter_samples # In[ ]: @@ -45,7 +44,7 @@ # In[19]: -""" There are 4 basic steps in pre-processing of any text +""" There are 4 basic steps in pre-processing of any text 1.Tokenizing 2.Removing hyper links if any 3.Converting to lower case @@ -60,7 +59,6 @@ from nltk.stem import PorterStemmer from nltk.tokenize import TweetTokenizer - # In[20]: diff --git a/UI-Apps/README.md b/UI-Apps/README.md index fbcbc7ec5af..651ff8958b0 100644 --- a/UI-Apps/README.md +++ b/UI-Apps/README.md @@ -6,4 +6,4 @@ run `py clock.py` # linux user - run `python3 clock.py` \ No newline at end of file + run `python3 clock.py` diff --git a/UI-Apps/clock.py b/UI-Apps/clock.py index 544d8bdc48f..ad9c359c0b6 100644 --- a/UI-Apps/clock.py +++ b/UI-Apps/clock.py @@ -1,5 +1,4 @@ import tkinter - # retrieve system's time from time import strftime @@ -19,7 +18,10 @@ def time(): clockTime = tkinter.Label( - top, font=("calibri", 40, "bold"), background="black", foreground="white" + top, + font=("calibri", 40, "bold"), + background="black", + foreground="white", ) clockTime.pack(anchor="center") diff --git a/Untitled.ipynb b/Untitled.ipynb index 4d36111e1e4..0e68692ed47 100644 --- a/Untitled.ipynb +++ b/Untitled.ipynb @@ -6,15 +6,16 @@ "metadata": {}, "outputs": [], "source": [ - "import cv2\n", "import time\n", + "\n", + "import cv2\n", "import numpy as np\n", "\n", "## Preparation for writing the ouput video\n", - "fourcc = cv2.VideoWriter_fourcc(*'XVID')\n", - "out = cv2.VideoWriter('output.avi',fourcc,20.0, (640,480))\n", + "fourcc = cv2.VideoWriter_fourcc(*\"XVID\")\n", + "out = cv2.VideoWriter(\"output.avi\", fourcc, 20.0, (640, 480))\n", "\n", - "##reading from the webcam \n", + "##reading from the webcam\n", "cap = cv2.VideoCapture(0)\n", "\n", "## Allow the system to sleep for 3 seconds before the webcam starts\n", @@ -24,31 +25,31 @@ "\n", "## Capture the background in range of 60\n", "for i in range(60):\n", - " ret,background = cap.read()\n", - "background = np.flip(background,axis=1)\n", + " ret, background = cap.read()\n", + "background = np.flip(background, axis=1)\n", "\n", "\n", "## Read every frame from the webcam, until the camera is open\n", - "while(cap.isOpened()):\n", + "while cap.isOpened():\n", " ret, img = cap.read()\n", " if not ret:\n", " break\n", - " count+=1\n", - " img = np.flip(img,axis=1)\n", - " \n", + " count += 1\n", + " img = np.flip(img, axis=1)\n", + "\n", " ## Convert the color space from BGR to HSV\n", " hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n", "\n", " ## Generat masks to detect red color\n", - " lower_red = np.array([0,120,50])\n", - " upper_red = np.array([10,255,255])\n", - " mask1 = cv2.inRange(hsv,lower_red,upper_red)\n", + " lower_red = np.array([0, 120, 50])\n", + " upper_red = np.array([10, 255, 255])\n", + " mask1 = cv2.inRange(hsv, lower_red, upper_red)\n", "\n", - " lower_red = np.array([170,120,70])\n", - " upper_red = np.array([180,255,255])\n", - " mask2 = cv2.inRange(hsv,lower_red,upper_red)\n", + " lower_red = np.array([170, 120, 70])\n", + " upper_red = np.array([180, 255, 255])\n", + " mask2 = cv2.inRange(hsv, lower_red, upper_red)\n", "\n", - " mask1 = mask1+mask2" + " mask1 = mask1 + mask2" ] } ], diff --git a/Voice Command Calculator.py b/Voice Command Calculator.py index ccc6e6c6496..c453e1ddf8d 100644 --- a/Voice Command Calculator.py +++ b/Voice Command Calculator.py @@ -1,32 +1,38 @@ import operator + import speech_recognition as s_r -print("Your speech_recognition version is: "+s_r.__version__) + +print("Your speech_recognition version is: " + s_r.__version__) r = s_r.Recognizer() my_mic_device = s_r.Microphone(device_index=1) with my_mic_device as source: print("Say what you want to calculate, example: 3 plus 3") r.adjust_for_ambient_noise(source) audio = r.listen(source) -my_string=r.recognize_google(audio) +my_string = r.recognize_google(audio) print(my_string) + + def get_operator_fn(op): return { - '+' : operator.add, - '-' : operator.sub, - 'x' : operator.mul, - 'divided' :operator.__truediv__, - 'divided by' :operator.__truediv__, - 'divide' :operator.__truediv__, - 'Divided' :operator.__truediv__, - 'Divided by' :operator.__truediv__, - 'Divide' :operator.__truediv__, - 'Mod' : operator.mod, - 'mod' : operator.mod, - '^' : operator.xor, - }[op] + "+": operator.add, + "-": operator.sub, + "x": operator.mul, + "divided": operator.__truediv__, + "divided by": operator.__truediv__, + "divide": operator.__truediv__, + "Divided": operator.__truediv__, + "Divided by": operator.__truediv__, + "Divide": operator.__truediv__, + "Mod": operator.mod, + "mod": operator.mod, + "^": operator.xor, + }[op] + def eval_binary_expr(op1, oper, op2): - op1,op2 = int(op1), int(op2) + op1, op2 = int(op1), int(op2) return get_operator_fn(oper)(op1, op2) + print(eval_binary_expr(*(my_string.split()))) diff --git a/VoiceAssistant/DOCUMENTATION.md b/VoiceAssistant/DOCUMENTATION.md index 8aaacdb05a8..f561adaeb33 100644 --- a/VoiceAssistant/DOCUMENTATION.md +++ b/VoiceAssistant/DOCUMENTATION.md @@ -19,7 +19,7 @@ This is the main file that encapsulates the other 7 files. It is advisable to ru After giving the command to run this file to your computer, you will have to say “**Hello Python**” to activate the voice assistant. After the activation, a menu will be displayed on the screen, showing all the tasks that Voice Assistant can do. This menu is displayed with the help of the print\_menu()* function present in the menu.py module. -Speaking out the respective commands of the desired task will indicate the Voice Assistant to do the following task. Once the speech is recorded, it will be converted to ` str ` by hear() or short\_hear() function of the speakListen.py module. +Speaking out the respective commands of the desired task will indicate the Voice Assistant to do the following task. Once the speech is recorded, it will be converted to ` str ` by hear() or short\_hear() function of the speakListen.py module. For termination of the program after a task is complete, the command “**close python**” should be spoken. For abrupt termination of the program, for Windows and Linux – The ctrl + c key combination should be used. @@ -28,7 +28,7 @@ For termination of the program after a task is complete, the command “**close This is the module that contains the following functions: - 1. speak(text) – This function speaks out the ‘text’ provided as a parameter. The text is a string(str). They say() and runAndWait() functions of Engine class in pyttsx3 enable the assistant to speak. Microsoft ***SAPI5*** has provided the voice. -1. hear() – This function records the voice for 9 seconds using your microphone as source and converts speech to text using recognize\_google(). recognize\_google() performs speech recognition on ``audio\_data`` (an ``AudioData`` instance), using the Google Speech Recognition API. +1. hear() – This function records the voice for 9 seconds using your microphone as source and converts speech to text using recognize\_google(). recognize\_google() performs speech recognition on ``audio\_data`` (an ``AudioData`` instance), using the Google Speech Recognition API. 1. long\_hear(duration\_time) – This function records voice for the ‘duration\_time’ provided with 60 seconds as the default time. It too converts speech to text in a similar fashion to hear() 1. short\_hear(duration\_time) – This functions records voice similar to hear() but for 5 seconds. 1. greet(g) - Uses the datetime library to generate current time and then greets accordingly. @@ -45,11 +45,11 @@ This module mainly handles this project's ‘searching on the web’ task. It us This module is mainly related to file processing and converting text to speech. Following are the functions present in this module: - 1. ms\_word – Read out the TEXT in MS Word (.docx) file provided in the location. -1. pdf\_read – Can be used to read pdf files and more specifically eBooks. It has 3 options - 1. Read a single page - 1. Read a range of pages - 1. Read a lesson - 1. Read the whole book +1. pdf\_read – Can be used to read pdf files and more specifically eBooks. It has 3 options + 1. Read a single page + 1. Read a range of pages + 1. Read a lesson + 1. Read the whole book It can also print the index and can find out the author’s name, the title, and the total number of pages in the PDF file. @@ -58,11 +58,11 @@ It can also print the index and can find out the author’s name, the title, and 1. print\_n\_speak\_index(toc) - It is similar to print\_index(), but it also speaks out the index here. 1. book\_details(author, title, total\_pages) - Creates a table of book details like author name, title, and total pages. It uses table and console from rich library. -**IMPORTANT: The voice assistant asks you the location of your file to be read by it. It won’t detect the file if it is present in the OneDrive folder or any other protected or third-party folder. Also, it would give an error if the extension of the file is not provided.** +**IMPORTANT: The voice assistant asks you the location of your file to be read by it. It won’t detect the file if it is present in the OneDrive folder or any other protected or third-party folder. Also, it would give an error if the extension of the file is not provided.** **For example; Consider a docx file ‘***abc***’ and pdf file ‘***fgh***’ present in valid directories and folders named ‘***folder\_loc’***.** -** When location is fed as ‘* **folder\_loc \abc***’ or ‘* **folder\_loc\fgh’* **it gives an error,** +** When location is fed as ‘* **folder\_loc \abc***’ or ‘* **folder\_loc\fgh’* **it gives an error,** ** but if the location is given as** *‘folder\_loc \abc.docx’* **or ‘** *folder\_loc \fgh.pdf’***, then it won’t give an error.** @@ -73,6 +73,3 @@ This module is like the dictator function and dictates the text that we speak. S ## menu.py It prints out the menu which contains the tasks and their corresponding commands. The rich library is being used here. - - - diff --git a/VoiceAssistant/PRE-REQUISITES.md b/VoiceAssistant/PRE-REQUISITES.md index 3cddcd3c2d1..975067f1f80 100644 --- a/VoiceAssistant/PRE-REQUISITES.md +++ b/VoiceAssistant/PRE-REQUISITES.md @@ -7,7 +7,7 @@ Following are the pre-requisites to be installed in the system to use Voice Assi 1. Following libraries and packages are to be installed. The syntax for library [installation of a library and a package](https://packaging.python.org/en/latest/tutorials/installing-packages/) is: - 1. pip install (library/package\_name) or - 1. pip3 install (library/package\_name) + 1. pip3 install (library/package\_name) ## *Enter the following commands to install them*: - diff --git a/VoiceAssistant/Project_Basic_struct/TextTospeech.py b/VoiceAssistant/Project_Basic_struct/TextTospeech.py index 5c23af072e6..e04bafe31ad 100644 --- a/VoiceAssistant/Project_Basic_struct/TextTospeech.py +++ b/VoiceAssistant/Project_Basic_struct/TextTospeech.py @@ -1,15 +1,15 @@ +import os + +import win32com from gtts import gTTS from playsound import playsound -import win32com from win32com import client -import os + def tts(): - audio = 'speech.mp3' - language = 'en' + audio = "speech.mp3" + language = "en" sentence = input("Enter the text to be spoken :- ") - + speaker = win32com.client.Dispatch("SAPI.SpVoice") sp = speaker.Speak(sentence) - - diff --git a/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py b/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py index 1c2baf70897..4a742ebf06c 100644 --- a/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py +++ b/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py @@ -1,20 +1,20 @@ -from speakListen import * -from websiteWork import * -from textRead import * from dictator import * from menu import * +from speakListen import * from speechtotext import * +from textRead import * from TextTospeech import * +from websiteWork import * def main(): start = 0 end = 0 if start == 0: - print("\nSay \"Hello Python\" to activate the Voice Assistant!") + print('\nSay "Hello Python" to activate the Voice Assistant!') start += 1 while True: - + q = short_hear().lower() if "close" in q: greet("end") @@ -23,7 +23,7 @@ def main(): greet("start") print_menu() while True: - + query = hear().lower() if "close" in query: greet("end") @@ -32,34 +32,51 @@ def main(): elif "text to speech" in query: tts() time.sleep(4) - - elif "search on google" in query or "search google" in query or "google" in query: + elif ( + "search on google" in query + or "search google" in query + or "google" in query + ): google_search() time.sleep(10) - - elif "search on wikipedia" in query or "search wikipedia" in query or "wikipedia" in query: + + elif ( + "search on wikipedia" in query + or "search wikipedia" in query + or "wikipedia" in query + ): wiki_search() time.sleep(10) - + elif "word" in query: ms_word() time.sleep(5) - + elif "book" in query: pdf_read() time.sleep(10) - + elif "speech to text" in query: big_text() time.sleep(5) - + else: print("I could'nt understand what you just said!") speak("I could'nt understand what you just said!") - - print("\nDo you want to continue? if yes then say " + Fore.YELLOW + "\"YES\"" + Fore.WHITE + " else say " + Fore.YELLOW + "\"CLOSE PYTHON\"") - speak("Do you want to continue? if yes then say YES else say CLOSE PYTHON") + + print( + "\nDo you want to continue? if yes then say " + + Fore.YELLOW + + '"YES"' + + Fore.WHITE + + " else say " + + Fore.YELLOW + + '"CLOSE PYTHON"' + ) + speak( + "Do you want to continue? if yes then say YES else say CLOSE PYTHON" + ) qry = hear().lower() if "yes" in qry: print_menu() @@ -75,4 +92,5 @@ def main(): else: continue + main() diff --git a/VoiceAssistant/Project_Basic_struct/dictator.py b/VoiceAssistant/Project_Basic_struct/dictator.py index f5cb71fb014..94989c924aa 100644 --- a/VoiceAssistant/Project_Basic_struct/dictator.py +++ b/VoiceAssistant/Project_Basic_struct/dictator.py @@ -1,20 +1,27 @@ # from speakListen import hear # from speakListen import long_hear +from colorama import Back, Fore, Style from speakListen import * -from colorama import Fore, Back, Style def big_text(): - print("By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?") - speak("By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?") + print( + "By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?" + ) + speak( + "By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?" + ) print(Fore.YELLOW + "Yes or No") query = hear().lower() duration_time = 0 - if "yes" in query or "es" in query or "ye" in query or "s" in query: + if "yes" in query or "es" in query or "ye" in query or "s" in query: - print("Please enter the time(in seconds) for which I shall record your speech - ", end = '') + print( + "Please enter the time(in seconds) for which I shall record your speech - ", + end="", + ) duration_time = int(input().strip()) print("\n") @@ -24,6 +31,7 @@ def big_text(): text = long_hear(duration_time) print("\n" + Fore.LIGHTCYAN_EX + text) + def colours(): text = "Colour" print(Fore.BLACK + text) @@ -43,5 +51,6 @@ def colours(): print(Fore.LIGHTCYAN_EX + text) print(Fore.LIGHTWHITE_EX + text) -#big_text() -#colours() \ No newline at end of file + +# big_text() +# colours() diff --git a/VoiceAssistant/Project_Basic_struct/menu.py b/VoiceAssistant/Project_Basic_struct/menu.py index 8512271c0d2..4261a3cf025 100644 --- a/VoiceAssistant/Project_Basic_struct/menu.py +++ b/VoiceAssistant/Project_Basic_struct/menu.py @@ -1,13 +1,12 @@ -from rich.console import Console # pip3 install Rich +from rich.console import Console # pip3 install Rich from rich.table import Table from speakListen import * def print_menu(): - """Display a table with list of tasks and their associated commands. - """ + """Display a table with list of tasks and their associated commands.""" speak("I can do the following") - table = Table(title="\nI can do the following :- ", show_lines = True) + table = Table(title="\nI can do the following :- ", show_lines=True) table.add_column("Sr. No.", style="cyan", no_wrap=True) table.add_column("Task", style="yellow") @@ -24,4 +23,5 @@ def print_menu(): console = Console() console.print(table) -#print_menu() \ No newline at end of file + +# print_menu() diff --git a/VoiceAssistant/Project_Basic_struct/speakListen.py b/VoiceAssistant/Project_Basic_struct/speakListen.py index e16db721abb..2c6e491de39 100644 --- a/VoiceAssistant/Project_Basic_struct/speakListen.py +++ b/VoiceAssistant/Project_Basic_struct/speakListen.py @@ -1,15 +1,15 @@ -import time -from colorama import Fore, Back, Style -import speech_recognition as sr +import datetime import os +import time + import pyttsx3 -import datetime +import speech_recognition as sr +from colorama import Back, Fore, Style from rich.progress import Progress - -python = pyttsx3.init("sapi5") # name of the engine is set as Python +python = pyttsx3.init("sapi5") # name of the engine is set as Python voices = python.getProperty("voices") -#print(voices) +# print(voices) python.setProperty("voice", voices[1].id) python.setProperty("rate", 140) @@ -19,151 +19,165 @@ def speak(text): Args: text ([str]): [It is the speech to be spoken] - """ + """ python.say(text) python.runAndWait() + def greet(g): """Uses the datetime library to generate current time and then greets accordingly. - + Args: g (str): To decide whether to say hello or good bye """ if g == "start" or g == "s": h = datetime.datetime.now().hour - text = '' + text = "" if h > 12 and h < 17: text = "Hello ! Good Afternoon " elif h < 12 and h > 0: text = "Hello! Good Morning " - elif h >= 17 : + elif h >= 17: text = "Hello! Good Evening " text += " I am Python, How may i help you ?" - speak(text) - + speak(text) + elif g == "quit" or g == "end" or g == "over" or g == "e": - text = 'Thank you!. Good Bye ! ' + text = "Thank you!. Good Bye ! " speak(text) + def hear(): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] Returns: [str]: [Speech of user as a string in English(en - IN)] - """ + """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ - r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily - r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. - r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy + r.pause_threshold = ( + 1 # a pause of more than 1 second will stop the microphone temporarily + ) + r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. + r.dynamic_energy_threshold = ( + True # pyhton now can dynamically change the threshold energy + ) with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") - #time.sleep(0.5) + # time.sleep(0.5) - speech = r.record(source, duration = 9) # option - #speech = r.listen(source) + speech = r.record(source, duration=9) # option + # speech = r.listen(source) # convert speech to text try: - #print("Recognizing...") + # print("Recognizing...") recognizing() speech = r.recognize_google(speech) print(speech + "\n") - + except Exception as exception: print(exception) return "None" return speech + def recognizing(): - """Uses the Rich library to print a simulates version of "recognizing" by printing a loading bar. - """ + """Uses the Rich library to print a simulates version of "recognizing" by printing a loading bar.""" with Progress() as pr: - rec = pr.add_task("[red]Recognizing...", total = 100) + rec = pr.add_task("[red]Recognizing...", total=100) while not pr.finished: - pr.update(rec, advance = 1.0) + pr.update(rec, advance=1.0) time.sleep(0.01) -def long_hear(duration_time = 60): + +def long_hear(duration_time=60): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] the difference between the hear() and long_hear() is that - the hear() - records users voice for 9 seconds long_hear() - will record user's voice for the time specified by user. By default, it records for 60 seconds. Returns: [str]: [Speech of user as a string in English(en - IN)] - """ + """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ - r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily - r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. - r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy + r.pause_threshold = ( + 1 # a pause of more than 1 second will stop the microphone temporarily + ) + r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. + r.dynamic_energy_threshold = ( + True # pyhton now can dynamically change the threshold energy + ) with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") - #time.sleep(0.5) + # time.sleep(0.5) - speech = r.record(source, duration = duration_time) # option - #speech = r.listen(source) + speech = r.record(source, duration=duration_time) # option + # speech = r.listen(source) # convert speech to text try: - print(Fore.RED +"Recognizing...") - #recognizing() + print(Fore.RED + "Recognizing...") + # recognizing() speech = r.recognize_google(speech) - #print(speech + "\n") - + # print(speech + "\n") + except Exception as exception: - print(exception) + print(exception) return "None" return speech -def short_hear(duration_time = 5): + +def short_hear(duration_time=5): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] the difference between the hear() and long_hear() is that - the hear() - records users voice for 9 seconds long_hear - will record user's voice for the time specified by user. By default, it records for 60 seconds. Returns: [str]: [Speech of user as a string in English(en - IN)] - """ + """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ - r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily - r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. - r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy + r.pause_threshold = ( + 1 # a pause of more than 1 second will stop the microphone temporarily + ) + r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. + r.dynamic_energy_threshold = ( + True # pyhton now can dynamically change the threshold energy + ) with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") - #time.sleep(0.5) + # time.sleep(0.5) - speech = r.record(source, duration = duration_time) # option - #speech = r.listen(source) + speech = r.record(source, duration=duration_time) # option + # speech = r.listen(source) # convert speech to text try: - print(Fore.RED +"Recognizing...") - #recognizing() + print(Fore.RED + "Recognizing...") + # recognizing() speech = r.recognize_google(speech) - #print(speech + "\n") - + # print(speech + "\n") + except Exception as exception: - print(exception) + print(exception) return "None" return speech - -if __name__ == '__main__': +if __name__ == "__main__": # print("Enter your name") # name = hear() # speak("Hello " + name) # greet("s") # greet("e") pass - #hear() - #recognizing() - + # hear() + # recognizing() diff --git a/VoiceAssistant/Project_Basic_struct/speechtotext.py b/VoiceAssistant/Project_Basic_struct/speechtotext.py index 1b1974c8b79..e73a55eaf32 100644 --- a/VoiceAssistant/Project_Basic_struct/speechtotext.py +++ b/VoiceAssistant/Project_Basic_struct/speechtotext.py @@ -1,6 +1,9 @@ import speech_recognition as sr + # initialize the recognizer r = sr.Recognizer() + + def stt(): with sr.Microphone() as source: # read the audio data from the default microphone @@ -8,4 +11,4 @@ def stt(): print("Recognizing...") # convert speech to text text = r.recognize_google(audio_data) - print(text) \ No newline at end of file + print(text) diff --git a/VoiceAssistant/Project_Basic_struct/textRead.py b/VoiceAssistant/Project_Basic_struct/textRead.py index 030c78501f0..27bafbfdb9c 100644 --- a/VoiceAssistant/Project_Basic_struct/textRead.py +++ b/VoiceAssistant/Project_Basic_struct/textRead.py @@ -1,169 +1,213 @@ -from speakListen import hear -from speakListen import speak +import time + import docx import fitz -import time -from rich.console import Console # pip3 install Rich -from rich.table import Table from colorama import Fore +from rich.console import Console # pip3 install Rich +from rich.table import Table +from speakListen import hear, speak + def ms_word(): - """[Print and speak out a ms_word docx file as specified in the path] - """ + """[Print and speak out a ms_word docx file as specified in the path]""" # TODO : Take location input from the user try: speak("Enter the document's location - ") location = input("Enter the document's location - ") - - file_loc = doubleslash(location) - + + file_loc = doubleslash(location) + doc = docx.Document(file_loc) fullText = [] for para in doc.paragraphs: fullText.append(para.text) - #print(fullText) - doc_file = '\n'.join(fullText) + # print(fullText) + doc_file = "\n".join(fullText) print(doc_file) speak(doc_file) except Exception as exp: - #print(exp) + # print(exp) print(f"ERROR - {exp}") - print(Fore.YELLOW + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it.") + print( + Fore.YELLOW + + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it." + ) return "None" + def pdf_read(): - """[Print and speak out the pdf on specified path] - """ + """[Print and speak out the pdf on specified path]""" try: speak("Enter the document's location - ") location = input("Enter the document's location - ") - - path = doubleslash(location) + + path = doubleslash(location) pdf = fitz.open(path) - details = pdf.metadata # Stores the meta-data which generally includes Author name and Title of book/document. - total_pages = pdf.pageCount # Stores the total number of pages + details = ( + pdf.metadata + ) # Stores the meta-data which generally includes Author name and Title of book/document. + total_pages = pdf.pageCount # Stores the total number of pages except Exception as exp: print(f"ERROR - {exp}") - print(Fore.YELLOW + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it.") + print( + Fore.YELLOW + + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it." + ) return "None" - try : - """ 1. Author - 2. Creator - 3. Producer - 4. Title """ - - author = details["author"] - #print("Author : ",author) - + try: + """1. Author + 2. Creator + 3. Producer + 4. Title""" + + author = details["author"] + # print("Author : ",author) + title = details["title"] - #print("Title : ",title) - - #print(details) - #print("Total Pages : ",total_pages) + # print("Title : ",title) + + # print(details) + # print("Total Pages : ",total_pages) book_details(author, title, total_pages) speak(f" Title {title}") speak(f" Author {author}") speak(f" Total Pages {total_pages}") - + # TODO : Deal with the Index toc = pdf.get_toc() - print("Say 1 or \"ONLY PRINT INDEX\" - if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'") - speak("Say 1 or only print index if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'") + print( + "Say 1 or \"ONLY PRINT INDEX\" - if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'" + ) + speak( + "Say 1 or only print index if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'" + ) q = hear().lower() - if "only print" in q or "1" in q or "one" in q or "vone" in q or 'only' in q or "index only" in q or 'only' in q or "print only" in q: + if ( + "only print" in q + or "1" in q + or "one" in q + or "vone" in q + or "only" in q + or "index only" in q + or "only" in q + or "print only" in q + ): print_index(toc) time.sleep(15) - elif "speak" in q or "2" in q or 'two' in q: + elif "speak" in q or "2" in q or "two" in q: print_n_speak_index(toc) time.sleep(10) elif q == "None": print("I could'nt understand what you just said!") speak("I could'nt understand what you just said!") time.sleep(4) - else: + else: time.sleep(4) pass - """Allow the user to do the following 1. Read/speak a page 2. Read/speak a range of pages 3. Lesson 4. Read/speak a whole book - """ - - #time.sleep(5) - - print("____________________________________________________________________________________________________________") - print("1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book") - speak("1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book") + """ + + # time.sleep(5) + + print( + "____________________________________________________________________________________________________________" + ) + print( + "1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book" + ) + speak( + "1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book" + ) q = hear().lower() - if "single" in q or "one" in q or "vone" in q or "one page" in q or "vone page" in q or "1 page" in q: + if ( + "single" in q + or "one" in q + or "vone" in q + or "one page" in q + or "vone page" in q + or "1 page" in q + ): try: pgno = int(input("Page Number - ")) page = pdf.load_page(pgno - 1) - text = page.get_text('text') + text = page.get_text("text") print("\n\n") - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) except Exception: - print("Sorry, I could recognize what you entered. Please re-enter the Page Number.") - speak("Sorry, I could recognize what you entered. Please re-enter the Page Number.") + print( + "Sorry, I could recognize what you entered. Please re-enter the Page Number." + ) + speak( + "Sorry, I could recognize what you entered. Please re-enter the Page Number." + ) pgno = input("Page no. - ") page = pdf.load_page(pgno - 1) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) - - elif 'range' in q or "multiple" in q: + elif "range" in q or "multiple" in q: try: start_pg_no = int(input("Starting Page Number - ")) end_pg_no = int(input("End Page Number - ")) for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) except Exception: - print("Sorry, I could recognize what you entered. Please re-enter the Page Number.") - speak("Sorry, I could recognize what you entered. Please re-enter the Page Number.") + print( + "Sorry, I could recognize what you entered. Please re-enter the Page Number." + ) + speak( + "Sorry, I could recognize what you entered. Please re-enter the Page Number." + ) start_pg_no = int(input("Starting Page Number - ")) end_pg_no = int(input("End Page Number - ")) for i in range(start_pg_no - 1, end_pg_no - 1): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) - elif 'lesson' in q: + elif "lesson" in q: try: key = input("Lesson name - ") start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages) if start_pg_no != None and end_pg_no != None: - start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages)) - + start_pg_no, end_pg_no = map( + int, search_in_toc(toc, key, total_pages) + ) + for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) - else: + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) + else: print("Try Again.") speak("Try Again.") speak("Lesson name") key = input("Lesson name - ") - start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages)) + start_pg_no, end_pg_no = map( + int, search_in_toc(toc, key, total_pages) + ) if start_pg_no != None and end_pg_no != None: for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) - + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) + except Exception: print("Try Again! Lesson could not be found.") speak("Try Again.Lesson could not be found") @@ -171,23 +215,25 @@ def pdf_read(): key = input("Lesson name - ") start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages) if start_pg_no != None and end_pg_no != None: - start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages)) - + start_pg_no, end_pg_no = map( + int, search_in_toc(toc, key, total_pages) + ) + for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) - else: + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) + else: print("Sorry, I cannot find the perticular lesson.") speak("Sorry, I cannot find the perticular lesson.") - elif "whole" in q or 'complete' in q: + elif "whole" in q or "complete" in q: for i in range(total_pages): page = pdf.load_page(i) - text = page.get_text('text') - print(text.replace('\t',' ')) - speak(text.replace('\t',' ')) + text = page.get_text("text") + print(text.replace("\t", " ")) + speak(text.replace("\t", " ")) elif q == "None": print("I could'nt understand what you just said!") @@ -195,13 +241,14 @@ def pdf_read(): else: print("You didn't say a valid command!") time.sleep(5) - except Exception as e: + except Exception as e: print(e) pass pdf.close() + def doubleslash(text): - """Replaces / with // + """Replaces / with // Args: text (str): location @@ -209,7 +256,8 @@ def doubleslash(text): Returns: str: formatted location """ - return text.replace('\\' , '\\\\') + return text.replace("\\", "\\\\") + def print_index(toc): """Prints out the index in proper format with title name and page number @@ -218,14 +266,15 @@ def print_index(toc): toc (nested list): toc[1] - Topic name toc[2] - Page number """ - dash = "-"*(100 - 7) - space = " "*47 + dash = "-" * (100 - 7) + space = " " * 47 print(f"{space}INDEX") print(f"\n\nName : {dash} PageNo.\n\n\n") for topic in toc: - eq_dash = "-"*(100 - len(topic[1])) + eq_dash = "-" * (100 - len(topic[1])) print(f"{topic[1]} {eq_dash} {topic[2]}") - + + def print_n_speak_index(toc): """Along with printing, it speaks out the index too. @@ -233,15 +282,16 @@ def print_n_speak_index(toc): toc (nested list): toc[1] - Topic name toc[2] - Page number """ - dash = "-"*(100 - 7) - space = " "*47 + dash = "-" * (100 - 7) + space = " " * 47 print(f"{space}INDEX") print(f"\n\nName : {dash} PageNo.\n\n\n\n") for topic in toc: - eq_dash = "-"*(100 - len(topic[1])) + eq_dash = "-" * (100 - len(topic[1])) print(f"{topic[1]} {eq_dash} {topic[2]}") speak(f"{topic[1]} {topic[2]}") + def search_in_toc(toc, key, totalpg): """Searches a particular lesson name provided as a parameter in toc and returns its starting and ending page numbers. @@ -268,9 +318,10 @@ def search_in_toc(toc, key, totalpg): if topic[1] == key: return (topic[2], totalpg) elif topic[1].lower() == key: - + return (topic[2], totalpg) - return None,None + return None, None + def book_details(author, title, total_pages): """Creates a table of book details like author name, title, and total pages. @@ -280,7 +331,7 @@ def book_details(author, title, total_pages): title (str): title of the book total_pages (int): total pages in the book """ - table = Table(title="\nBook Details :- ", show_lines = True) + table = Table(title="\nBook Details :- ", show_lines=True) table.add_column("Sr. No.", style="magenta", no_wrap=True) table.add_column("Property", style="cyan") @@ -292,7 +343,8 @@ def book_details(author, title, total_pages): console = Console() console.print(table) - -#ms_word() -#pdf_read() -#book_details("abc", "abcde", 12) + + +# ms_word() +# pdf_read() +# book_details("abc", "abcde", 12) diff --git a/VoiceAssistant/Project_Basic_struct/websiteWork.py b/VoiceAssistant/Project_Basic_struct/websiteWork.py index c20a2792791..5e609fd8c78 100644 --- a/VoiceAssistant/Project_Basic_struct/websiteWork.py +++ b/VoiceAssistant/Project_Basic_struct/websiteWork.py @@ -1,37 +1,35 @@ -from speakListen import greet, hear -from speakListen import speak - +from speakListen import greet, hear, speak """ 1. speakListen.speak(text) 2. speakListen.greet() 3. speakListen.hear() """ -import wikipedia import webbrowser +import wikipedia + def google_search(): - """[Goes to google and searches the website asked by the user] - """ + """[Goes to google and searches the website asked by the user]""" google_search_link = "https://www.google.co.in/search?q=" google_search = "What do you want me to search on Google? " print(google_search) speak(google_search) - + query = hear() if query != "None": - webbrowser.open(google_search_link+query) + webbrowser.open(google_search_link + query) elif query == "None": print("I could'nt understand what you just said!") speak("I could'nt understand what you just said!") + def wiki_search(): - """[Speak out the summary in wikipedia and going to the website according to user's choice.] - """ + """[Speak out the summary in wikipedia and going to the website according to user's choice.]""" wiki_search = "What do you want me to search on Wikipedia? Please tell me the exact sentence or word to Search." wiki_search_link = "https://en.wikipedia.org/wiki/" - + print(wiki_search) speak(wiki_search) @@ -39,7 +37,7 @@ def wiki_search(): try: if query != "None": - results = wikipedia.summary(query, sentences = 2) + results = wikipedia.summary(query, sentences=2) print(results) speak(results) @@ -47,7 +45,16 @@ def wiki_search(): speak("Do you want me to open the Wikipedia page?") q = hear().lower() - if "yes" in q or "okay" in q or "ok" in q or "opun" in q or "opan" in q or "vopen" in q or "es" in q or "s" in q: + if ( + "yes" in q + or "okay" in q + or "ok" in q + or "opun" in q + or "opan" in q + or "vopen" in q + or "es" in q + or "s" in q + ): print(wiki_search_link + query) webbrowser.open(wiki_search_link + query) @@ -58,5 +65,6 @@ def wiki_search(): except Exception as e: print("Couldn't find") -#wiki_search() -#google_search() + +# wiki_search() +# google_search() diff --git a/VoiceAssistant/README.md b/VoiceAssistant/README.md index 7e7fb7b5d22..67dd175c7fd 100644 --- a/VoiceAssistant/README.md +++ b/VoiceAssistant/README.md @@ -14,8 +14,8 @@ This is Voice Assistant coded using Python which can do the following: - 4. Read a MS Word(docx) document. 5. Convert speech to text. 6. Read a book(PDF). - - + + ## Author @@ -51,24 +51,24 @@ In-case, if you don't find _1_VoiceAssistant in Voice Assistant folder, just ins ## Description of Commands 1. text to speech - User needs to type the text and then it will be spoken by the VoiceAssistant. -2. Search on Google - Voice Assistant will ask you "What do you want me to search on Google". - - >Voice Assistant then starts recording your voice and will record anything that is spoken henceforth. +2. Search on Google - Voice Assistant will ask you "What do you want me to search on Google". + + >Voice Assistant then starts recording your voice and will record anything that is spoken henceforth. >Then it will open the search results in default browser. -3. Search on Wikipedia - Voice Assistant will ask you "What do you want me to search on Wikipwedia? please say the exactsentence or word to search.". - - >Voice Assistant then starts recording your voice and will record anything that is spoken henceforth. +3. Search on Wikipedia - Voice Assistant will ask you "What do you want me to search on Wikipwedia? please say the exactsentence or word to search.". + + >Voice Assistant then starts recording your voice and will record anything that is spoken henceforth. >Then it will speak out and print the summary of the search results. >It then asks, whether the respective search result should be opened in the default browser. - + 4. Read MS word document - Asks user to enter the location of file to be read and reads it. - + NOTE :- 1. A file location without an extension(i.e. '.docx') will give an error. 2. A file inside a third party folder(Ex OneDrive) can't be accessed and will give an error. 5. Convert speech to text - Prints out the speech spoken by user. - + By default, it record the voice for 60 seconds but it can be changed. 6. Read a book - Asks user to enter the location of file to be read and reads it. diff --git a/VoiceRepeater/__main__.py b/VoiceRepeater/__main__.py index dc3e20a9739..b7d2db7e731 100644 --- a/VoiceRepeater/__main__.py +++ b/VoiceRepeater/__main__.py @@ -1,9 +1,9 @@ +import os +import shutil import time -import speech_recognition as sr -import os import playsound -import shutil +import speech_recognition as sr shutil.rmtree("spoken") os.mkdir("spoken") diff --git a/Weather Scrapper/weather.py b/Weather Scrapper/weather.py index 3980d958bd6..26a5007c5fd 100644 --- a/Weather Scrapper/weather.py +++ b/Weather Scrapper/weather.py @@ -1,32 +1,32 @@ -#TODO - refactor & clean code +# TODO - refactor & clean code import csv import time -from datetime import datetime -from datetime import date +from datetime import date, datetime + from selenium import webdriver -from selenium.webdriver.support.ui import WebDriverWait -from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains -from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.support.ui import WebDriverWait -#TODO - Add input checking +# TODO - Add input checking city = input("City >") state = input("State >") -url = 'https://www.wunderground.com' +url = "https://www.wunderground.com" -#Supresses warnings and specifies the webdriver to run w/o a GUI +# Supresses warnings and specifies the webdriver to run w/o a GUI options = Options() options.headless = True -options.add_argument('log-level=3') +options.add_argument("log-level=3") driver = webdriver.Chrome(options=options) driver.get(url) -#----------------------------------------------------- +# ----------------------------------------------------- # Connected successfully to the site -#Passes the city and state input to the weather sites search box +# Passes the city and state input to the weather sites search box searchBox = driver.find_element(By.XPATH, '//*[@id="wuSearch"]') location = city + " " + state @@ -34,27 +34,40 @@ action = ActionChains(driver) searchBox.send_keys(location) element = WebDriverWait(driver, 10).until( - EC.presence_of_element_located((By.XPATH, '//*[@id="wuForm"]/search-autocomplete/ul/li[2]/a/span[1]')) + EC.presence_of_element_located( + (By.XPATH, '//*[@id="wuForm"]/search-autocomplete/ul/li[2]/a/span[1]') + ), ) searchBox.send_keys(Keys.RETURN) -#----------------------------------------------------- -#Gather weather data -#City - Time - Date - Temperature - Precipitation - Sky - Wind +# ----------------------------------------------------- +# Gather weather data +# City - Time - Date - Temperature - Precipitation - Sky - Wind -#waits till the page loads to begin gathering data +# waits till the page loads to begin gathering data precipitationElem = WebDriverWait(driver, 10).until( - EC.presence_of_element_located((By.XPATH, '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[1]')) + EC.presence_of_element_located( + ( + By.XPATH, + '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[1]', + ) + ), +) +precipitationElem = driver.find_element( + By.XPATH, + '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[1]', ) -precipitationElem = driver.find_element(By.XPATH, '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[1]') precip = "Precipitation:" + precipitationElem.text.split()[0] -windAndSkyElem = driver.find_element(By.XPATH, '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[2]') +windAndSkyElem = driver.find_element( + By.XPATH, + '//*[@id="inner-content"]/div[3]/div[1]/div/div[3]/div/lib-city-today-forecast/div/div[1]/div/div/div/a[2]', +) description = windAndSkyElem.text.split(". ") sky = description[0] temp = description[1] wind = description[2] -#Format the date and time +# Format the date and time time = datetime.now().strftime("%H:%M") today = date.today() date = today.strftime("%b-%d-%Y") diff --git a/WeatherGUI.py b/WeatherGUI.py index 19b42994b84..d0a632a8bc8 100644 --- a/WeatherGUI.py +++ b/WeatherGUI.py @@ -1,4 +1,5 @@ import tkinter as tk + import requests from bs4 import BeautifulSoup @@ -55,7 +56,10 @@ def getWeather(): weatherPrediction.grid(row=2, column=1, sticky="W", padx=40) tk.Label(root, text="Air Quality", font=("Calibri bold", 20), bg="white").grid( - row=1, column=2, sticky="W", padx=20 + row=1, + column=2, + sticky="W", + padx=20, ) airqualitylabel = tk.Label(root, font=("Caliber bold", 20), bg="white") airqualitylabel.grid(row=2, column=2, sticky="W") diff --git a/Web Socket.py b/Web Socket.py index efb44bbbc21..b499bd0e90d 100644 --- a/Web Socket.py +++ b/Web Socket.py @@ -1,13 +1,14 @@ # Program to print a data & it's Metadata of online uploaded file using "socket". import socket -skt_c=socket.socket(socket.AF_INET,socket.SOCK_STREAM) -skt_c.connect(('data.pr4e.org',80)) -link='GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode() + +skt_c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +skt_c.connect(("data.pr4e.org", 80)) +link = b"GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n" skt_c.send(link) while True: - data=skt_c.recv(512) - if len(data)<1: - break - print(data.decode()) + data = skt_c.recv(512) + if len(data) < 1: + break + print(data.decode()) skt_c.close() diff --git a/Web_Scraper.py b/Web_Scraper.py index 46692794431..b33d3533690 100644 --- a/Web_Scraper.py +++ b/Web_Scraper.py @@ -4,11 +4,12 @@ Requirements: selenium, BeautifulSoup """ +import time + import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys -import time # url of the page we want to scrape url = "https://www.naukri.com/top-jobs-by-designations# desigtop600" diff --git a/Webbrowser/tk-browser.py b/Webbrowser/tk-browser.py index cbbfd01bb3e..059466d3690 100644 --- a/Webbrowser/tk-browser.py +++ b/Webbrowser/tk-browser.py @@ -3,26 +3,29 @@ # Written by Sina Meysami # -from tkinter import * # pip install tk-tools -import tkinterweb # pip install tkinterweb import sys +from tkinter import * # pip install tk-tools + +import tkinterweb # pip install tkinterweb + class Browser(Tk): def __init__(self): - super(Browser,self).__init__() + super().__init__() self.title("Tk Browser") try: browser = tkinterweb.HtmlFrame(self) browser.load_website("https://google.com") - browser.pack(fill="both",expand=True) + browser.pack(fill="both", expand=True) except Exception: sys.exit() - - + + def main(): browser = Browser() browser.mainloop() - + + if __name__ == "__main__": # Webbrowser v1.0 main() diff --git a/Wikipdedia/flask_rendering.py b/Wikipdedia/flask_rendering.py index 05c6d7494bf..984f87c140b 100644 --- a/Wikipdedia/flask_rendering.py +++ b/Wikipdedia/flask_rendering.py @@ -1,13 +1,13 @@ -from flask import Flask, render_template, request import practice_beautifulsoap as data +from flask import Flask, render_template, request -app = Flask(__name__, template_folder='template') +app = Flask(__name__, template_folder="template") -@app.route('/', methods=["GET", "POST"]) +@app.route("/", methods=["GET", "POST"]) def index(): languages = data.lang() - return render_template('index.html', languages=languages) + return render_template("index.html", languages=languages) @app.route("/display", methods=["POST"]) @@ -19,8 +19,13 @@ def output(): soup_data = data.data(entered_topic, selected_language) soup_image = data.get_image_urls(entered_topic) - return render_template('output.html', heading=entered_topic.upper(), data=soup_data, - url=soup_image, language=selected_language) + return render_template( + "output.html", + heading=entered_topic.upper(), + data=soup_data, + url=soup_image, + language=selected_language, + ) if __name__ == "__main__": diff --git a/Wikipdedia/main.py b/Wikipdedia/main.py index 5596b44786f..c937c7cff1b 100644 --- a/Wikipdedia/main.py +++ b/Wikipdedia/main.py @@ -6,11 +6,11 @@ def print_hi(name): # Use a breakpoint in the code line below to debug your script. - print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. + print(f"Hi, {name}") # Press Ctrl+F8 to toggle the breakpoint. # Press the green button in the gutter to run the script. -if __name__ == '__main__': - print_hi('PyCharm') +if __name__ == "__main__": + print_hi("PyCharm") # See PyCharm help at https://www.jetbrains.com/help/pycharm/ diff --git a/Wikipdedia/practice_beautifulsoap.py b/Wikipdedia/practice_beautifulsoap.py index 00beb87fc44..4472fb4c9ae 100644 --- a/Wikipdedia/practice_beautifulsoap.py +++ b/Wikipdedia/practice_beautifulsoap.py @@ -1,5 +1,5 @@ -from bs4 import BeautifulSoup import requests +from bs4 import BeautifulSoup language_symbols = {} @@ -8,11 +8,11 @@ def lang(): try: response = requests.get("https://www.wikipedia.org/") response.raise_for_status() - soup = BeautifulSoup(response.content, 'html.parser') + soup = BeautifulSoup(response.content, "html.parser") - for option in soup.find_all('option'): + for option in soup.find_all("option"): language = option.text - symbol = option['lang'] + symbol = option["lang"] language_symbols[language] = symbol return list(language_symbols.keys()) @@ -29,17 +29,19 @@ def data(selected_topic, selected_language): url = f"https://{symbol}.wikipedia.org/wiki/{selected_topic}" data_response = requests.get(url) data_response.raise_for_status() - data_soup = BeautifulSoup(data_response.content, 'html.parser') + data_soup = BeautifulSoup(data_response.content, "html.parser") - main_content = data_soup.find('div', {'id': 'mw-content-text'}) + main_content = data_soup.find("div", {"id": "mw-content-text"}) filtered_content = "" if main_content: for element in main_content.descendants: - if element.name in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']: - filtered_content += "\n" + element.get_text(strip=True).upper() + "\n" + if element.name in ["h1", "h2", "h3", "h4", "h5", "h6"]: + filtered_content += ( + "\n" + element.get_text(strip=True).upper() + "\n" + ) - elif element.name == 'p': + elif element.name == "p": filtered_content += element.get_text(strip=True) + "\n" return filtered_content @@ -54,11 +56,11 @@ def get_image_urls(query): search_url = f"https://www.google.com/search?q={query}&tbm=isch" image_response = requests.get(search_url) image_response.raise_for_status() - image_soup = BeautifulSoup(image_response.content, 'html.parser') + image_soup = BeautifulSoup(image_response.content, "html.parser") image_urls = [] - for img in image_soup.find_all('img'): - image_url = img.get('src') + for img in image_soup.find_all("img"): + image_url = img.get("src") if image_url and image_url.startswith("http"): image_urls.append(image_url) diff --git a/Wikipdedia/static/js/output.js b/Wikipdedia/static/js/output.js index 5c360de488e..5b4841969f4 100644 --- a/Wikipdedia/static/js/output.js +++ b/Wikipdedia/static/js/output.js @@ -6,4 +6,3 @@ function validateForm() { return false; } } - diff --git a/WikipediaModule.py b/WikipediaModule.py index dec5e2a5c0b..32ddad3a447 100644 --- a/WikipediaModule.py +++ b/WikipediaModule.py @@ -3,11 +3,12 @@ @author: Albert """ -from __future__ import print_function -import wikipedia as wk + from bs4 import BeautifulSoup +import wikipedia as wk + def wiki(): """ diff --git a/Windows_Wallpaper_Script/ReadMe.md b/Windows_Wallpaper_Script/ReadMe.md index 96e0558fbc5..cd6d1f61d1b 100644 --- a/Windows_Wallpaper_Script/ReadMe.md +++ b/Windows_Wallpaper_Script/ReadMe.md @@ -3,7 +3,7 @@ Ever seen those amazing windows wallpapers on your windows lock screen? This Pyt The wallpapers keep changing with time when connected to the internet so you can run the script after you notice new wallpapers on your lockscreen in order to obtain them. ***Optional:*** You can also use the windows task scheduler and schedule -the script to run in a set time interval and also set the desktop wallpaper folder as default wallpaper folder. For more Info on task scheduling in Windows 10, +the script to run in a set time interval and also set the desktop wallpaper folder as default wallpaper folder. For more Info on task scheduling in Windows 10, Look Here: [Task Scheduling in windows](https://www.digitalcitizen.life/how-create-task-basic-task-wizard) # Requirements diff --git a/Windows_Wallpaper_Script/wallpaper_extract.py b/Windows_Wallpaper_Script/wallpaper_extract.py index 541462bdff4..bf832f5968c 100644 --- a/Windows_Wallpaper_Script/wallpaper_extract.py +++ b/Windows_Wallpaper_Script/wallpaper_extract.py @@ -74,7 +74,7 @@ def extract_wall(): if ext == ".jpg": try: im = Image.open(w.file_urls["wall_dst"] + filename) - except IOError: + except OSError: print("This isn't a picture.", filename) if list(im.size)[0] != 1920 and list(im.size)[0] != 1080: im.close() diff --git a/Wordle/wordle.py b/Wordle/wordle.py index ffed27a1838..365698c5fbf 100644 --- a/Wordle/wordle.py +++ b/Wordle/wordle.py @@ -26,9 +26,11 @@ import random # Load 5 letter word dictionary -with open("5 letter word dictionary.txt", 'r') as dictionary: +with open("5 letter word dictionary.txt") as dictionary: # Read content of dictionary - dictionary = dictionary.read().split('\n') # This returns a list of all the words in the dictionary + dictionary = dictionary.read().split( + "\n" + ) # This returns a list of all the words in the dictionary # Choose a random word from the dictionary word = random.choice(dictionary) @@ -95,7 +97,6 @@ letter += 1 continue - answer_given = False do_not_add = False # Check if letter is in word @@ -105,7 +106,10 @@ if user_inp[letter] == i: return_answer += "G" else: - if not user_inp[word.index(user_inp[letter])] == word[word.index(user_inp[letter])]: + if ( + not user_inp[word.index(user_inp[letter])] + == word[word.index(user_inp[letter])] + ): return_answer += "Y" else: answer_given = False @@ -117,7 +121,7 @@ # Append checked letter to the list letters_checked if not do_not_add: - letters_checked.append(user_inp[letter]) + letters_checked.append(user_inp[letter]) letter += 1 diff --git a/XORcipher/README.md b/XORcipher/README.md index 8b86506c7d2..0ad4a4df339 100644 --- a/XORcipher/README.md +++ b/XORcipher/README.md @@ -11,4 +11,4 @@ files. You will find detailed docstrings in each method. * encrypt_string : str * decrypt_string : str * encrypt_file : boolean -* decrypt_file : boolean \ No newline at end of file +* decrypt_file : boolean diff --git a/XORcipher/XOR_cipher.py b/XORcipher/XOR_cipher.py index 4d6bdb2190a..7afb21f4bef 100644 --- a/XORcipher/XOR_cipher.py +++ b/XORcipher/XOR_cipher.py @@ -18,7 +18,7 @@ """ -class XORCipher(object): +class XORCipher: def __init__(self, key=0): """ simple constructor that receives a key or uses @@ -141,7 +141,7 @@ def encrypt_file(self, file, key=0): assert isinstance(file, str) and isinstance(key, int) try: - with open(file, "r") as fin: + with open(file) as fin: with open("encrypt.out", "w+") as fout: # actual encrypt-process for line in fin: @@ -165,7 +165,7 @@ def decrypt_file(self, file, key): assert isinstance(file, str) and isinstance(key, int) try: - with open(file, "r") as fin: + with open(file) as fin: with open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: diff --git a/Youtube Downloader With GUI/main.py b/Youtube Downloader With GUI/main.py index 21d5c534ad5..b8b7b28aae9 100644 --- a/Youtube Downloader With GUI/main.py +++ b/Youtube Downloader With GUI/main.py @@ -1,17 +1,20 @@ # libraraies -from pytube import * import os +from threading import * from tkinter import * from tkinter.filedialog import * from tkinter.messagebox import * -from threading import * + +from pytube import * file_size = 0 q = input("") if q == "shutdown": os.system("shutdown -s") + + # function progress to keep check of progress of function. def progress(stream=None, chunk=None, remaining=None): file_downloaded = file_size - remaining @@ -47,7 +50,7 @@ def startDownload(): + "length: " + str(round(ob.length / 60, 1)) + " mins\n\n" - "Views: " + str(round(ob.views / 1000000, 2)) + "M" + "Views: " + str(round(ob.views / 1000000, 2)) + "M", ) desc.pack(side=TOP, pady=10) strm.download(path_save, strm.title) diff --git a/advanced_calculator.py b/advanced_calculator.py index 82ff80d8970..02522d2384e 100644 --- a/advanced_calculator.py +++ b/advanced_calculator.py @@ -10,17 +10,18 @@ # How can I market gtts? Like showing used google's api? This is how can I market it? # Project description? What will be the project description? +from io import BytesIO from numbers import Number +from pprint import pprint from sys import exit + +import art import colorama as color +import date import inquirer from gtts import gTTS -from pygame import mixer, time -from io import BytesIO -from pprint import pprint -import art -import date +from pygame import mixer, time # Find the best of best extensions for the auto generation of the documentation parts. # For your favourite languages like JavaScript, Python ,etc,... diff --git a/agecalculator.py b/agecalculator.py index 094aa88ca46..3b4ca5958e6 100644 --- a/agecalculator.py +++ b/agecalculator.py @@ -1,55 +1,55 @@ -from _datetime import datetime import tkinter as tk from tkinter import ttk + from _datetime import * +from _datetime import datetime win = tk.Tk() -win.title('Age Calculate') -win.geometry('310x400') -# win.iconbitmap('pic.png') this is use extention ico then show pic +win.title("Age Calculate") +win.geometry("310x400") +# win.iconbitmap('pic.png') this is use extention ico then show pic ############################################ Frame ############################################ pic = tk.PhotoImage(file=r"E:\Python Practice\Age_calculate\pic.png") -win.tk.call('wm','iconphoto',win._w,pic) +win.tk.call("wm", "iconphoto", win._w, pic) -canvas=tk.Canvas(win,width=310,height=190) +canvas = tk.Canvas(win, width=310, height=190) canvas.grid() image = tk.PhotoImage(file=r"E:\Python Practice\Age_calculate\pic.png") -canvas.create_image(0,0,anchor='nw',image=image) +canvas.create_image(0, 0, anchor="nw", image=image) frame = ttk.Frame(win) -frame.place(x=40,y=220) - +frame.place(x=40, y=220) ############################################ Label on Frame ############################################ -name = ttk.Label(frame,text = 'Name : ',font = ('',12,'bold')) -name.grid(row=0,column=0,sticky = tk.W) +name = ttk.Label(frame, text="Name : ", font=("", 12, "bold")) +name.grid(row=0, column=0, sticky=tk.W) -year = ttk.Label(frame,text = 'Year : ',font = ('',12,'bold')) -year.grid(row=1,column=0,sticky = tk.W) +year = ttk.Label(frame, text="Year : ", font=("", 12, "bold")) +year.grid(row=1, column=0, sticky=tk.W) -month = ttk.Label(frame,text = 'Month : ',font = ('',12,'bold')) -month.grid(row=2,column=0,sticky = tk.W) +month = ttk.Label(frame, text="Month : ", font=("", 12, "bold")) +month.grid(row=2, column=0, sticky=tk.W) -date = ttk.Label(frame,text = 'Date : ',font = ('',12,'bold')) -date.grid(row=3,column=0,sticky = tk.W) +date = ttk.Label(frame, text="Date : ", font=("", 12, "bold")) +date.grid(row=3, column=0, sticky=tk.W) ############################################ Entry Box ############################################ -name_entry = ttk.Entry(frame,width=25) -name_entry.grid(row=0,column=1) +name_entry = ttk.Entry(frame, width=25) +name_entry.grid(row=0, column=1) name_entry.focus() -year_entry = ttk.Entry(frame,width=25) -year_entry.grid(row=1,column=1,pady=5) +year_entry = ttk.Entry(frame, width=25) +year_entry.grid(row=1, column=1, pady=5) -month_entry = ttk.Entry(frame,width=25) -month_entry.grid(row=2,column=1) +month_entry = ttk.Entry(frame, width=25) +month_entry.grid(row=2, column=1) -date_entry = ttk.Entry(frame,width=25) -date_entry.grid(row=3,column=1,pady=5) +date_entry = ttk.Entry(frame, width=25) +date_entry.grid(row=3, column=1, pady=5) def age_cal(): @@ -57,13 +57,12 @@ def age_cal(): year_entry.get() month_entry.get() date_entry.get() - cal = datetime.today()-(int(year_entry)) + cal = datetime.today() - (int(year_entry)) print(cal) -btn = ttk.Button(frame,text='Age calculate',command=age_cal) -btn.grid(row=4,column=1) - +btn = ttk.Button(frame, text="Age calculate", command=age_cal) +btn.grid(row=4, column=1) win.mainloop() diff --git a/alexa_news_headlines.py b/alexa_news_headlines.py index 7cb84b9fe09..a2aa79ef4bf 100644 --- a/alexa_news_headlines.py +++ b/alexa_news_headlines.py @@ -41,7 +41,7 @@ def start_skill(): @ask.intent("YesIntent") def share_headlines(): headlines = get_headlines() - headline_msg = "The current world news headlines are {}".format(headlines) + headline_msg = f"The current world news headlines are {headlines}" return statement(headline_msg) diff --git a/armstrongnumber.py b/armstrongnumber.py index 2e714fa9db4..f4def08d440 100644 --- a/armstrongnumber.py +++ b/armstrongnumber.py @@ -10,7 +10,7 @@ temp = num while temp > 0: digit = temp % 10 - sum += digit ** 3 + sum += digit**3 temp //= 10 # display the result diff --git a/async_downloader/async_downloader.py b/async_downloader/async_downloader.py index 4f715048905..4d283cb4069 100644 --- a/async_downloader/async_downloader.py +++ b/async_downloader/async_downloader.py @@ -24,7 +24,7 @@ def download(ways): event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete( - async_downloader(ways, event_loop, success_files, failure_files) + async_downloader(ways, event_loop, success_files, failure_files), ) finally: event_loop.close() @@ -73,16 +73,20 @@ async def download_file_by_url(url, session=None): if response.status == 404: print( "\t{} from {} : Failed : {}".format( - file_name, url, "404 - Not found" - ) + file_name, + url, + "404 - Not found", + ), ) return fail, url if not response.status == 200: print( "\t{} from {} : Failed : HTTP response {}".format( - file_name, url, response.status - ) + file_name, + url, + response.status, + ), ) return fail, url @@ -97,12 +101,14 @@ async def download_file_by_url(url, session=None): except aiohttp.client_exceptions.ClientConnectionError: print( "\t{} from {}: Failed : {}".format( - file_name, url, "Client connection error" - ) + file_name, + url, + "Client connection error", + ), ) else: - print("\t{} from {} : Success".format(file_name, url)) + print(f"\t{file_name} from {url} : Success") fail = False return fail, url diff --git a/automail.py b/automail.py index 84b67424408..2b765ef7ee9 100644 --- a/automail.py +++ b/automail.py @@ -1,25 +1,30 @@ -#find documentation for ezgmail module at https://pypi.org/project/EZGmail/ -#simple simon says module that interacts with google API to read the subject line of an email and respond to "Simon says:" -#DO NOT FORGET TO ADD CREDENTIALS.JSON AND TOKEN.JSON TO .GITIGNORE!!! +# find documentation for ezgmail module at https://pypi.org/project/EZGmail/ +# simple simon says module that interacts with google API to read the subject line of an email and respond to "Simon says:" +# DO NOT FORGET TO ADD CREDENTIALS.JSON AND TOKEN.JSON TO .GITIGNORE!!! -import ezgmail, re, time +import re +import time + +import ezgmail check = True while check: recThreads = ezgmail.recent() - findEmail = re.compile(r'<(.*)@(.*)>') + findEmail = re.compile(r"<(.*)@(.*)>") i = 0 for msg in recThreads: - subEval = recThreads[i].messages[0].subject.split(' ') + subEval = recThreads[i].messages[0].subject.split(" ") sender = recThreads[i].messages[0].sender - if subEval[0] == 'Simon' and subEval[1] == 'says:': - subEval.remove('Simon') - subEval.remove('says:') - replyAddress = findEmail.search(sender).group(0).replace('<','').replace('>','') - replyContent = 'I am now doing ' + ' '.join(subEval) + if subEval[0] == "Simon" and subEval[1] == "says:": + subEval.remove("Simon") + subEval.remove("says:") + replyAddress = ( + findEmail.search(sender).group(0).replace("<", "").replace(">", "") + ) + replyContent = "I am now doing " + " ".join(subEval) ezgmail.send(replyAddress, replyContent, replyContent) ezgmail._trash(recThreads[i]) - if subEval[0] == 'ENDTASK': #remote kill command + if subEval[0] == "ENDTASK": # remote kill command check = False i += 1 - time.sleep(60) #change check frquency; default every minute \ No newline at end of file + time.sleep(60) # change check frquency; default every minute diff --git a/backup_automater_services.py b/backup_automater_services.py index 21ec7aa0b62..6f8b60d2e94 100644 --- a/backup_automater_services.py +++ b/backup_automater_services.py @@ -18,21 +18,23 @@ ) # Format it so we can use the format to create the directory confdir = os.getenv( - "my_config" + "my_config", ) # Set the variable by getting the value from the OS setting dropbox = os.getenv( - "dropbox" + "dropbox", ) # Set the variable by getting the value from the OS setting conffile = "services.conf" # Set the variable as the name of the configuration file conffilename = os.path.join( - confdir, conffile + confdir, + conffile, ) # Set the variable by combining the path and the file name sourcedir = os.path.expanduser( - "~/Library/Services/" + "~/Library/Services/", ) # Source directory of where the scripts are located # Combine several settings to create destdir = os.path.join( - dropbox, "My_backups" + "/" + "Automater_services" + todaystr + "/" + dropbox, + "My_backups" + "/" + "Automater_services" + todaystr + "/", ) # the destination backup directory @@ -40,9 +42,11 @@ fname = file_name.strip() # Strip out the blank lines from the configuration file if fname: # For the lines that are not blank sourcefile = os.path.join( - sourcedir, fname + sourcedir, + fname, ) # Get the name of the source files to backup destfile = os.path.join( - destdir, fname + destdir, + fname, ) # Get the name of the destination file names shutil.copytree(sourcefile, destfile) # Copy the directories diff --git a/bank_managment_system/backend.py b/bank_managment_system/backend.py index e54027cf0a6..c0c56616c39 100644 --- a/bank_managment_system/backend.py +++ b/bank_managment_system/backend.py @@ -10,10 +10,10 @@ def connect_database(): cur = conn.cursor() cur.execute( - "create table if not exists bank (acc_no int, name text, age int, address text, balance int, account_type text, mobile_number int)" + "create table if not exists bank (acc_no int, name text, age int, address text, balance int, account_type text, mobile_number int)", ) cur.execute( - "create table if not exists staff (name text, pass text,salary int, position text)" + "create table if not exists staff (name text, pass text,salary int, position text)", ) cur.execute("create table if not exists admin (name text, pass text)") cur.execute("insert into admin values('arpit','123')") @@ -139,14 +139,14 @@ def check_balance(acc_no): # update_name_in_bank_table def update_name_in_bank_table(new_name, acc_no): print(new_name) - conn.execute("update bank set name='{}' where acc_no={}".format(new_name, acc_no)) + conn.execute(f"update bank set name='{new_name}' where acc_no={acc_no}") conn.commit() # update_age_in_bank_table def update_age_in_bank_table(new_name, acc_no): print(new_name) - conn.execute("update bank set age={} where acc_no={}".format(new_name, acc_no)) + conn.execute(f"update bank set age={new_name} where acc_no={acc_no}") conn.commit() @@ -154,7 +154,7 @@ def update_age_in_bank_table(new_name, acc_no): def update_address_in_bank_table(new_name, acc_no): print(new_name) conn.execute( - "update bank set address='{}' where acc_no={}".format(new_name, acc_no) + f"update bank set address='{new_name}' where acc_no={acc_no}", ) conn.commit() @@ -204,20 +204,20 @@ def show_employees_for_update(): # update employee name from data base def update_employee_name(new_name, old_name): print(new_name, old_name) - cur.execute("update staff set name='{}' where name='{}'".format(new_name, old_name)) + cur.execute(f"update staff set name='{new_name}' where name='{old_name}'") conn.commit() def update_employee_password(new_pass, old_name): print(new_pass, old_name) - cur.execute("update staff set pass='{}' where name='{}'".format(new_pass, old_name)) + cur.execute(f"update staff set pass='{new_pass}' where name='{old_name}'") conn.commit() def update_employee_salary(new_salary, old_name): print(new_salary, old_name) cur.execute( - "update staff set salary={} where name='{}'".format(new_salary, old_name) + f"update staff set salary={new_salary} where name='{old_name}'", ) conn.commit() @@ -225,7 +225,7 @@ def update_employee_salary(new_salary, old_name): def update_employee_position(new_pos, old_name): print(new_pos, old_name) cur.execute( - "update staff set position='{}' where name='{}'".format(new_pos, old_name) + f"update staff set position='{new_pos}' where name='{old_name}'", ) conn.commit() diff --git a/bank_managment_system/frontend.py b/bank_managment_system/frontend.py index c885c2b37c3..9128d4e084c 100644 --- a/bank_managment_system/frontend.py +++ b/bank_managment_system/frontend.py @@ -36,11 +36,17 @@ def delete_create(): ): acc_no = backend.create_customer( - name, age, address, balance, acc_type, mobile_number + name, + age, + address, + balance, + acc_type, + mobile_number, ) label = Label( - create_employee_frame, text="Your account number is {}".format(acc_no) + create_employee_frame, + text=f"Your account number is {acc_no}", ) label.grid(row=14) @@ -91,7 +97,9 @@ def delete_create(): entry10 = Entry(create_employee_frame) entry10.grid(row=12, pady=4) button = Button( - create_employee_frame, text="Submit", command=create_customer_in_database + create_employee_frame, + text="Submit", + command=create_customer_in_database, ) button.grid(row=13, pady=4) @@ -137,27 +145,37 @@ def back_page2(): show_frame.grid(padx=400, pady=200) label = Label( - show_frame, text="Account_number:\t{}".format(details[0]), font="bold" + show_frame, + text=f"Account_number:\t{details[0]}", + font="bold", ) label.grid(row=0, pady=6) - label = Label(show_frame, text="Name:\t{}".format(details[1]), font="bold") + label = Label(show_frame, text=f"Name:\t{details[1]}", font="bold") label.grid(row=1, pady=6) - label = Label(show_frame, text="Age:\t{}".format(details[2]), font="bold") + label = Label(show_frame, text=f"Age:\t{details[2]}", font="bold") label.grid(row=2, pady=6) label = Label( - show_frame, text="Address:\t{}".format(details[3]), font="bold" + show_frame, + text=f"Address:\t{details[3]}", + font="bold", ) label.grid(row=3, pady=6) label = Label( - show_frame, text="Balance:\t{}".format(details[4]), font="bold" + show_frame, + text=f"Balance:\t{details[4]}", + font="bold", ) label.grid(row=4, pady=6) label = Label( - show_frame, text="Account_type:\t{}".format(details[5]), font="bold" + show_frame, + text=f"Account_type:\t{details[5]}", + font="bold", ) label.grid(row=5, pady=6) label = Label( - show_frame, text="Mobile Number:\t{}".format(details[6]), font="bold" + show_frame, + text=f"Mobile Number:\t{details[6]}", + font="bold", ) label.grid(row=6, pady=6) button = Button( @@ -221,12 +239,14 @@ def update_money(): detail = backend.get_detail(acc_no) label = Label( - add_frame, text="Account holder name: {}".format(detail[0][0]) + add_frame, + text=f"Account holder name: {detail[0][0]}", ) label.grid(row=0, pady=3) label = Label( - add_frame, text="Current amount: {}".format(detail[0][1]) + add_frame, + text=f"Current amount: {detail[0][1]}", ) label.grid(row=1, pady=3) @@ -312,12 +332,14 @@ def deduct_money(): detail = backend.get_detail(acc_no) label = Label( - add_frame, text="Account holder name: {}".format(detail[0][0]) + add_frame, + text=f"Account holder name: {detail[0][0]}", ) label.grid(row=0, pady=3) label = Label( - add_frame, text="Current amount: {}".format(detail[0][1]) + add_frame, + text=f"Current amount: {detail[0][1]}", ) label.grid(row=1, pady=3) @@ -395,7 +417,9 @@ def delete_check_frame(): check_frame.grid(padx=500, pady=300) label = Label( - check_frame, text="Balance Is:{}".format(balance), font="bold" + check_frame, + text=f"Balance Is:{balance}", + font="bold", ) label.grid(row=0, pady=4) @@ -474,7 +498,9 @@ def update_name_in_database(): entry_name.grid(row=1, column=2, padx=2) global submit_button submit_button = Button( - update_customer_frame, text="Update", command=update_name_in_database + update_customer_frame, + text="Update", + command=update_name_in_database, ) submit_button.grid(row=1, column=3) @@ -504,7 +530,9 @@ def update_age_in_database(): entry_name.grid(row=2, column=2, padx=2) global submit_button submit_button = Button( - update_customer_frame, text="Update", command=update_age_in_database + update_customer_frame, + text="Update", + command=update_age_in_database, ) submit_button.grid(row=2, column=3) @@ -534,7 +562,9 @@ def update_address_in_database(): entry_name.grid(row=3, column=2, padx=2) global submit_button submit_button = Button( - update_customer_frame, text="Update", command=update_address_in_database + update_customer_frame, + text="Update", + command=update_address_in_database, ) submit_button.grid(row=3, column=3) @@ -553,17 +583,23 @@ def update_address_in_database(): label.grid(row=0) name_button = Button( - update_customer_frame, text="Name", command=update_name + update_customer_frame, + text="Name", + command=update_name, ) name_button.grid(row=1, column=0, pady=6) age_button = Button( - update_customer_frame, text="Age", command=update_age + update_customer_frame, + text="Age", + command=update_age, ) age_button.grid(row=2, column=0, pady=6) address_button = Button( - update_customer_frame, text="Address", command=update_address + update_customer_frame, + text="Address", + command=update_address, ) address_button.grid(row=3, column=0, pady=6) @@ -602,7 +638,10 @@ def update_address_in_database(): entry_acc.grid(pady=4) button = Button( - search_frame, text="update", command=show_all_updateble_content, bg="red" + search_frame, + text="update", + command=show_all_updateble_content, + bg="red", ) button.grid() @@ -620,20 +659,30 @@ def clear_list_frame(): list_frame = Frame(tk) list_frame.grid(padx=50, pady=50) label = Label( - list_frame, text="Acc_no\t\t\tName\t\t\tAge\t\t\tAddress\t\t\tbalance" + list_frame, + text="Acc_no\t\t\tName\t\t\tAge\t\t\tAddress\t\t\tbalance", ) label.grid(pady=6) for i in details: label = Label( list_frame, text="{}\t\t\t{}\t\t\t{}\t\t\t{}\t\t\t{}".format( - i[0], i[1], i[2], i[3], i[4] + i[0], + i[1], + i[2], + i[3], + i[4], ), ) label.grid(pady=4) button = Button( - list_frame, text="Back", width=20, height=2, bg="red", command=clear_list_frame + list_frame, + text="Back", + width=20, + height=2, + bg="red", + command=clear_list_frame, ) button.grid() mainloop() @@ -716,13 +765,21 @@ def back_to_main_from_page2(): button1 = Button(frame1, text="Create Account", command=create, width=20, height=2) button1.grid(row=0, pady=6) button2 = Button( - frame1, text="Show Details", command=search_acc, width=20, height=2 + frame1, + text="Show Details", + command=search_acc, + width=20, + height=2, ) button2.grid(row=1, pady=6) button3 = Button(frame1, text="Add balance", command=add, width=20, height=2) button3.grid(row=2, pady=6) button4 = Button( - frame1, text="Withdraw money", command=withdraw, width=20, height=2 + frame1, + text="Withdraw money", + command=withdraw, + width=20, + height=2, ) button4.grid(row=3, pady=6) button5 = Button(frame1, text="Check balance", command=check, width=20, height=2) @@ -730,14 +787,22 @@ def back_to_main_from_page2(): button6 = Button(frame1, text="Update Account", command=update, width=20, height=2) button6.grid(row=5, pady=6) button7 = Button( - frame1, text="List of all members", command=allmembers, width=20, height=2 + frame1, + text="List of all members", + command=allmembers, + width=20, + height=2, ) button7.grid(row=6, pady=6) button8 = Button(frame1, text="Delete Account", command=delete, width=20, height=2) button8.grid(row=7, pady=6) button9 = Button( - frame1, text="Exit", command=back_to_main_from_page2, width=20, height=2 + frame1, + text="Exit", + command=back_to_main_from_page2, + width=20, + height=2, ) button9.grid(row=8, pady=6) @@ -846,7 +911,9 @@ def database_calling(): entry19.grid(row=1, column=1, padx=4) global update_button update_button = Button( - update_frame, text="Update", command=database_calling + update_frame, + text="Update", + command=database_calling, ) update_button.grid(row=1, column=2, padx=4) @@ -868,7 +935,9 @@ def database_calling(): entry19.grid(row=2, column=1, padx=4) global update_button update_button = Button( - update_frame, text="Update", command=database_calling + update_frame, + text="Update", + command=database_calling, ) update_button.grid(row=2, column=2, padx=4) @@ -892,7 +961,9 @@ def database_calling(): entry19.grid(row=3, column=1, padx=4) global update_button update_button = Button( - update_frame, text="Update", command=database_calling + update_frame, + text="Update", + command=database_calling, ) update_button.grid(row=3, column=2, padx=4) @@ -915,7 +986,9 @@ def database_calling(): entry19.grid(row=4, column=1, padx=4) global update_button update_button = Button( - update_frame, text="Update", command=database_calling + update_frame, + text="Update", + command=database_calling, ) update_button.grid(row=4, column=2, padx=4) @@ -924,7 +997,9 @@ def database_calling(): update_frame.grid(padx=400, pady=250) label = Label( - update_frame, text="press what do you want to update", font="bold" + update_frame, + text="press what do you want to update", + font="bold", ) label.grid(pady=6) @@ -1039,7 +1114,7 @@ def back_to_main_page1(): for i in details: label = Label( show_employee_frame, - text="{}\t\t\t{}\t\t\t{}\t\t\t{}".format(i[0], i[1], i[2], i[3]), + text=f"{i[0]}\t\t\t{i[1]}\t\t\t{i[2]}\t\t\t{i[3]}", ) label.grid(pady=4) @@ -1073,7 +1148,7 @@ def back_to_main_page1_from_total_money(): label = Label(all_money, text="Total Amount of money") label.grid(row=0, pady=6) - label = Label(all_money, text="{}".format(all)) + label = Label(all_money, text=f"{all}") label.grid(row=1) button = Button( @@ -1167,12 +1242,20 @@ def back_to_main2(): button13.grid(row=2, pady=6) button11 = Button( - page1_frame, text="Total Money", command=Total_money, width=20, height=2 + page1_frame, + text="Total Money", + command=Total_money, + width=20, + height=2, ) button11.grid(row=3, pady=6) button12 = Button( - page1_frame, text="Back", command=back_to_main, width=20, height=2 + page1_frame, + text="Back", + command=back_to_main, + width=20, + height=2, ) button12.grid(row=4, pady=6) diff --git a/batch_file_rename.py b/batch_file_rename.py index b3a4d75e6d5..fa396c117bd 100644 --- a/batch_file_rename.py +++ b/batch_file_rename.py @@ -38,7 +38,7 @@ def batch_rename(work_dir, old_ext, new_ext): def get_parser(): parser = argparse.ArgumentParser( - description="change extension of files in a working directory" + description="change extension of files in a working directory", ) parser.add_argument( "work_dir", @@ -48,10 +48,18 @@ def get_parser(): help="the directory where to change extension", ) parser.add_argument( - "old_ext", metavar="OLD_EXT", type=str, nargs=1, help="old extension" + "old_ext", + metavar="OLD_EXT", + type=str, + nargs=1, + help="old extension", ) parser.add_argument( - "new_ext", metavar="NEW_EXT", type=str, nargs=1, help="new extension" + "new_ext", + metavar="NEW_EXT", + type=str, + nargs=1, + help="new extension", ) return parser diff --git a/binary search.py b/binary search.py index cfad85df817..2cf464c8f20 100644 --- a/binary search.py +++ b/binary search.py @@ -1,23 +1,25 @@ -def binarySearchAppr (arr, start, end, x): -# check condition - if end >= start: - mid = start + (end- start)//2 - # If element is present at the middle - if arr[mid] == x: - return mid - # If element is smaller than mid - elif arr[mid] > x: - return binarySearchAppr(arr, start, mid-1, x) - # Else the element greator than mid - else: - return binarySearchAppr(arr, mid+1, end, x) - else: - # Element is not found in the array - return -1 -arr = sorted(['t','u','t','o','r','i','a','l']) -x ='r' -result = binarySearchAppr(arr, 0, len(arr)-1, x) +def binarySearchAppr(arr, start, end, x): + # check condition + if end >= start: + mid = start + (end - start) // 2 + # If element is present at the middle + if arr[mid] == x: + return mid + # If element is smaller than mid + elif arr[mid] > x: + return binarySearchAppr(arr, start, mid - 1, x) + # Else the element greator than mid + else: + return binarySearchAppr(arr, mid + 1, end, x) + else: + # Element is not found in the array + return -1 + + +arr = sorted(["t", "u", "t", "o", "r", "i", "a", "l"]) +x = "r" +result = binarySearchAppr(arr, 0, len(arr) - 1, x) if result != -1: - print ("Element is present at index "+str(result)) + print("Element is present at index " + str(result)) else: - print ("Element is not present in array") + print("Element is not present in array") diff --git a/binarySTree isTrue_YashV1729.Java b/binarySTree isTrue_YashV1729.Java index e758ab13e34..0faf301e216 100644 --- a/binarySTree isTrue_YashV1729.Java +++ b/binarySTree isTrue_YashV1729.Java @@ -1,67 +1,67 @@ -//Java implementation to check if given Binary tree -//is a BST or not +//Java implementation to check if given Binary tree +//is a BST or not -/* Class containing left and right child of current +/* Class containing left and right child of current node and key value*/ -class Node -{ - int data; - Node left, right; +class Node +{ + int data; + Node left, right; - public Node(int item) - { - data = item; - left = right = null; - } -} + public Node(int item) + { + data = item; + left = right = null; + } +} -public class BinaryTree -{ - //Root of the Binary Tree - Node root; +public class BinaryTree +{ + //Root of the Binary Tree + Node root; - /* can give min and max value according to your code or + /* can give min and max value according to your code or can write a function to find min and max value of tree. */ - /* returns true if given search tree is binary + /* returns true if given search tree is binary search tree (efficient version) */ - boolean isBST() { - return isBSTUtil(root, Integer.MIN_VALUE, - Integer.MAX_VALUE); - } + boolean isBST() { + return isBSTUtil(root, Integer.MIN_VALUE, + Integer.MAX_VALUE); + } - /* Returns true if the given tree is a BST and its + /* Returns true if the given tree is a BST and its values are >= min and <= max. */ - boolean isBSTUtil(Node node, int min, int max) - { + boolean isBSTUtil(Node node, int min, int max) + { /* an empty tree is BST */ - if (node == null) - return true; + if (node == null) + return true; /* false if this node violates the min/max constraints */ - if (node.data < min || node.data > max) - return false; + if (node.data < min || node.data > max) + return false; - /* otherwise check the subtrees recursively + /* otherwise check the subtrees recursively tightening the min/max constraints */ - // Allow only distinct values - return (isBSTUtil(node.left, min, node.data-1) && - isBSTUtil(node.right, node.data+1, max)); - } + // Allow only distinct values + return (isBSTUtil(node.left, min, node.data-1) && + isBSTUtil(node.right, node.data+1, max)); + } /* Driver program to test above functions */ - public static void main(String args[]) - { - BinaryTree tree = new BinaryTree(); - tree.root = new Node(4); - tree.root.left = new Node(2); - tree.root.right = new Node(5); - tree.root.left.left = new Node(1); - tree.root.left.right = new Node(3); + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(4); + tree.root.left = new Node(2); + tree.root.right = new Node(5); + tree.root.left.left = new Node(1); + tree.root.left.right = new Node(3); - if (tree.isBST()) - System.out.println("IS BST"); + if (tree.isBST()) + System.out.println("IS BST"); else - System.out.println("Not a BST"); - } -} + System.out.println("Not a BST"); + } +} diff --git a/binary_search_trees/delete_a_node_in_bst.py b/binary_search_trees/delete_a_node_in_bst.py index bfb6a0708ac..c600a9f9fd4 100644 --- a/binary_search_trees/delete_a_node_in_bst.py +++ b/binary_search_trees/delete_a_node_in_bst.py @@ -1,35 +1,36 @@ from inorder_successor import inorder_successor + + # The above line imports the inorder_successor function from the inorder_successor.py file -def delete_node(root,val): - """ This function deletes a node with value val from the BST""" - - # search in the left subtree - if root.data < val: - root.right = delete_node(root.right,val) - - # search in the right subtree - elif root.data>val: - root.left=delete_node(root.left,val) - - # node to be deleted is found - else: - # case 1: no child leaf node - if root.left is None and root.right is None: - return None - - # case 2: one child - if root.left is None: - return root.right - - # case 2: one child - elif root.right is None: - return root.left - - # case 3: two children - - # find the inorder successor - IS=inorder_successor(root.right) - root.data=IS.data - root.right=delete_node(root.right,IS.data) - return root - \ No newline at end of file +def delete_node(root, val): + """This function deletes a node with value val from the BST""" + + # search in the left subtree + if root.data < val: + root.right = delete_node(root.right, val) + + # search in the right subtree + elif root.data > val: + root.left = delete_node(root.left, val) + + # node to be deleted is found + else: + # case 1: no child leaf node + if root.left is None and root.right is None: + return None + + # case 2: one child + if root.left is None: + return root.right + + # case 2: one child + elif root.right is None: + return root.left + + # case 3: two children + + # find the inorder successor + IS = inorder_successor(root.right) + root.data = IS.data + root.right = delete_node(root.right, IS.data) + return root diff --git a/binary_search_trees/inorder_successor.py b/binary_search_trees/inorder_successor.py index b9b15666eea..36b26a51119 100644 --- a/binary_search_trees/inorder_successor.py +++ b/binary_search_trees/inorder_successor.py @@ -1,10 +1,10 @@ def inorder_successor(root): - # This function returns the inorder successor of a node in a BST - - # The inorder successor of a node is the node with the smallest value greater than the value of the node - current=root - - # The inorder successor is the leftmost node in the right subtree - while current.left is not None: - current=current.left - return current \ No newline at end of file + # This function returns the inorder successor of a node in a BST + + # The inorder successor of a node is the node with the smallest value greater than the value of the node + current = root + + # The inorder successor is the leftmost node in the right subtree + while current.left is not None: + current = current.left + return current diff --git a/binary_search_trees/inorder_traversal.py b/binary_search_trees/inorder_traversal.py index 3bb4c4101ed..1a98ebcf903 100644 --- a/binary_search_trees/inorder_traversal.py +++ b/binary_search_trees/inorder_traversal.py @@ -1,15 +1,15 @@ def inorder(root): - """ This function performs an inorder traversal of a BST""" - + """This function performs an inorder traversal of a BST""" + # The inorder traversal of a BST is the nodes in increasing order if root is None: return - + # Traverse the left subtree inorder(root.left) - + # Print the root node print(root.data) - + # Traverse the right subtree - inorder(root.right) \ No newline at end of file + inorder(root.right) diff --git a/binary_search_trees/insert_in_bst.py b/binary_search_trees/insert_in_bst.py index dd726d06596..9264cf61723 100644 --- a/binary_search_trees/insert_in_bst.py +++ b/binary_search_trees/insert_in_bst.py @@ -1,17 +1,18 @@ from tree_node import Node -def insert(root,val): - - """ This function inserts a node with value val into the BST""" - + + +def insert(root, val): + """This function inserts a node with value val into the BST""" + # If the tree is empty, create a new node if root is None: return Node(val) - + # If the value to be inserted is less than the root value, insert in the left subtree if val < root.data: - root.left = insert(root.left,val) - + root.left = insert(root.left, val) + # If the value to be inserted is greater than the root value, insert in the right subtree else: - root.right = insert(root.right,val) - return root \ No newline at end of file + root.right = insert(root.right, val) + return root diff --git a/binary_search_trees/main.py b/binary_search_trees/main.py index 96ebb6ae8eb..7eda0b1c9b0 100644 --- a/binary_search_trees/main.py +++ b/binary_search_trees/main.py @@ -1,16 +1,16 @@ -from tree_node import Node -from insert_in_bst import insert from delete_a_node_in_bst import delete_node -from search_in_bst import search from inorder_successor import inorder_successor +from insert_in_bst import insert from mirror_a_bst import create_mirror_bst from print_in_range import print_in_range from root_to_leaf_paths import print_root_to_leaf_paths +from search_in_bst import search +from tree_node import Node from validate_bst import is_valid_bst def main(): - + # Create a BST root = None root = insert(root, 50) @@ -20,54 +20,51 @@ def main(): root = insert(root, 70) root = insert(root, 60) root = insert(root, 80) - + # Print the inorder traversal of the BST print("Inorder traversal of the original BST:") print_in_range(root, 10, 90) - + # Print the root to leaf paths print("Root to leaf paths:") print_root_to_leaf_paths(root, []) - + # Check if the tree is a BST - print("Is the tree a BST:", is_valid_bst(root,None,None)) - - + print("Is the tree a BST:", is_valid_bst(root, None, None)) + # Delete nodes from the BST print("Deleting 20 from the BST:") root = delete_node(root, 20) - + # Print the inorder traversal of the BST print("Inorder traversal of the BST after deleting 20:") print_in_range(root, 10, 90) - + # Check if the tree is a BST - print("Is the tree a BST:", is_valid_bst(root,None,None)) - - + print("Is the tree a BST:", is_valid_bst(root, None, None)) + # Delete nodes from the BST print("Deleting 30 from the BST:") root = delete_node(root, 30) - + # Print the inorder traversal of the BST after deleting 30 print("Inorder traversal of the BST after deleting 30:") print_in_range(root, 10, 90) - + # Check if the tree is a BST - print("Is the tree a BST:", is_valid_bst(root,None,None)) - + print("Is the tree a BST:", is_valid_bst(root, None, None)) + # Delete nodes from the BST print("Deleting 50 from the BST:") root = delete_node(root, 50) - + # Print the inorder traversal of the BST after deleting 50 print("Inorder traversal of the BST after deleting 50:") print_in_range(root, 10, 90) - + # Check if the tree is a BST - print("Is the tree a BST:", is_valid_bst(root,None,None)) - - + print("Is the tree a BST:", is_valid_bst(root, None, None)) + print("Searching for 70 in the BST:", search(root, 70)) print("Searching for 100 in the BST:", search(root, 100)) print("Inorder traversal of the BST:") @@ -77,9 +74,6 @@ def main(): print("Inorder traversal of the mirror BST:") print_in_range(mirror_root, 10, 90) + if __name__ == "__main__": main() - - - - diff --git a/binary_search_trees/mirror_a_bst.py b/binary_search_trees/mirror_a_bst.py index 73f080f85c2..284809217d5 100644 --- a/binary_search_trees/mirror_a_bst.py +++ b/binary_search_trees/mirror_a_bst.py @@ -1,16 +1,18 @@ from tree_node import Node + + def create_mirror_bst(root): - """ Function to create a mirror of a binary search tree""" - + """Function to create a mirror of a binary search tree""" + # If the tree is empty, return None if root is None: return None - + # Create a new node with the root value - + # Recursively create the mirror of the left and right subtrees left_mirror = create_mirror_bst(root.left) right_mirror = create_mirror_bst(root.right) root.left = right_mirror root.right = left_mirror - return root \ No newline at end of file + return root diff --git a/binary_search_trees/print_in_range.py b/binary_search_trees/print_in_range.py index fecca23ba24..5df1d8aefa2 100644 --- a/binary_search_trees/print_in_range.py +++ b/binary_search_trees/print_in_range.py @@ -1,21 +1,20 @@ -def print_in_range(root,k1,k2): - - """ This function prints the nodes in a BST that are in the range k1 to k2 inclusive""" - - # If the tree is empty, return - if root is None: - return - - # If the root value is in the range, print the root value - if root.data >= k1 and root.data <= k2: - print_in_range(root.left,k1,k2) - print(root.data) - print_in_range(root.right,k1,k2) - - # If the root value is less than k1, the nodes in the range will be in the right subtree - elif root.data < k1: - print_in_range(root.left,k1,k2) - - # If the root value is greater than k2, the nodes in the range will be in the left subtree - else: - print_in_range(root.right,k1,k2) \ No newline at end of file +def print_in_range(root, k1, k2): + """This function prints the nodes in a BST that are in the range k1 to k2 inclusive""" + + # If the tree is empty, return + if root is None: + return + + # If the root value is in the range, print the root value + if root.data >= k1 and root.data <= k2: + print_in_range(root.left, k1, k2) + print(root.data) + print_in_range(root.right, k1, k2) + + # If the root value is less than k1, the nodes in the range will be in the right subtree + elif root.data < k1: + print_in_range(root.left, k1, k2) + + # If the root value is greater than k2, the nodes in the range will be in the left subtree + else: + print_in_range(root.right, k1, k2) diff --git a/binary_search_trees/root_to_leaf_paths.py b/binary_search_trees/root_to_leaf_paths.py index 22867a713ec..5638d1afb97 100644 --- a/binary_search_trees/root_to_leaf_paths.py +++ b/binary_search_trees/root_to_leaf_paths.py @@ -1,17 +1,17 @@ def print_root_to_leaf_paths(root, path): - """ This function prints all the root to leaf paths in a BST""" - + """This function prints all the root to leaf paths in a BST""" + # If the tree is empty, return if root is None: return - + # Add the root value to the path path.append(root.data) if root.left is None and root.right is None: print(path) - + # Recursively print the root to leaf paths in the left and right subtrees else: print_root_to_leaf_paths(root.left, path) print_root_to_leaf_paths(root.right, path) - path.pop() \ No newline at end of file + path.pop() diff --git a/binary_search_trees/search_in_bst.py b/binary_search_trees/search_in_bst.py index 4a95780e43a..08a3449eb2c 100644 --- a/binary_search_trees/search_in_bst.py +++ b/binary_search_trees/search_in_bst.py @@ -1,15 +1,15 @@ def search(root, val): - """ This function searches for a node with value val in the BST and returns True if found, False otherwise""" - + """This function searches for a node with value val in the BST and returns True if found, False otherwise""" + # If the tree is empty, return False if root == None: return False - + # If the root value is equal to the value to be searched, return True if root.data == val: return True - + # If the value to be searched is less than the root value, search in the left subtree if root.data > val: return search(root.left, val) - return search(root.right, val) \ No newline at end of file + return search(root.right, val) diff --git a/binary_search_trees/tree_node.py b/binary_search_trees/tree_node.py index 1d35656da08..1f03b8595ba 100644 --- a/binary_search_trees/tree_node.py +++ b/binary_search_trees/tree_node.py @@ -1,6 +1,6 @@ - # Node class for binary tree + class Node: def __init__(self, data): self.data = data diff --git a/binary_search_trees/validate_bst.py b/binary_search_trees/validate_bst.py index 3569c833005..cbb1a32dd9f 100644 --- a/binary_search_trees/validate_bst.py +++ b/binary_search_trees/validate_bst.py @@ -1,17 +1,17 @@ -def is_valid_bst(root,min,max): - """ Function to check if a binary tree is a binary search tree""" - +def is_valid_bst(root, min, max): + """Function to check if a binary tree is a binary search tree""" + # If the tree is empty, return True if root is None: return True - + # If the root value is less than the minimum value or greater than the maximum value, return False if min is not None and root.data <= min.data: return False - + # If the root value is greater than the maximum value or less than the minimum value, return False elif max is not None and root.data >= max.data: return False - + # Recursively check if the left and right subtrees are BSTs - return is_valid_bst(root.left,min,root) and is_valid_bst(root.right,root,max) \ No newline at end of file + return is_valid_bst(root.left, min, root) and is_valid_bst(root.right, root, max) diff --git a/binod.py b/binod.py index 2bee72de9d6..c4ede90d579 100644 --- a/binod.py +++ b/binod.py @@ -7,11 +7,11 @@ # def checkBinod(file): # ======= +import os # def checkBinod(file): #this function will check there is any 'Binod' text in file or not # with open(file, "r") as f: #we are opening file in read mode and using 'with' so need to take care of close() # ======= import time -import os # Importing our Bindoer print("To Kaise Hai Ap Log!") @@ -21,7 +21,7 @@ def checkBinod(file): # Trying to find Binod In File Insted Of Manohar Ka Kotha # master - with open(file, "r") as f: + with open(file) as f: # master fileContent = f.read() if "binod" in fileContent.lower(): diff --git a/birthdays.py b/birthdays.py index 19ad2b001a2..a85610e6ded 100644 --- a/birthdays.py +++ b/birthdays.py @@ -1,15 +1,15 @@ -birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} +birthdays = {"Alice": "Apr 1", "Bob": "Dec 12", "Carol": "Mar 4"} while True: - - print('Enter a name: (blank to quit)') - name = input() - if name == '': - break - if name in birthdays: - print(birthdays[name] + ' is the birthday of ' + name) - else: - print('I do not have birthday information for ' + name) - print('What is their birthday?') - bday = input() - birthdays[name] = bday - print('Birthday database updated.') + + print("Enter a name: (blank to quit)") + name = input() + if name == "": + break + if name in birthdays: + print(birthdays[name] + " is the birthday of " + name) + else: + print("I do not have birthday information for " + name) + print("What is their birthday?") + bday = input() + birthdays[name] = bday + print("Birthday database updated.") diff --git a/blackJackGUI.py b/blackJackGUI.py index a67e6e06717..a2b0a8e4c4c 100644 --- a/blackJackGUI.py +++ b/blackJackGUI.py @@ -1,11 +1,11 @@ -from __future__ import print_function import random + import simplegui CARD_SIZE = (72, 96) CARD_CENTER = (36, 48) card_images = simplegui.load_image( - "http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png" + "http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png", ) in_play = False diff --git a/blackjack.py b/blackjack.py index 1cdac41bc43..9968d1b49d8 100644 --- a/blackjack.py +++ b/blackjack.py @@ -7,13 +7,13 @@ random.shuffle(deck) print( - " ********************************************************** " + " ********************************************************** ", ) print( - " Welcome to the game Casino - BLACK JACK ! " + " Welcome to the game Casino - BLACK JACK ! ", ) print( - " ********************************************************** " + " ********************************************************** ", ) d_cards = [] # Initialising dealer's cards @@ -39,7 +39,7 @@ if sum(d_cards) > 21: print( - "Dealer is BUSTED !\n ************** You are the Winner !!******************\n" + "Dealer is BUSTED !\n ************** You are the Winner !!******************\n", ) exit() @@ -100,7 +100,7 @@ def dealer_choice(): print("*************You are BUSTED !*************\n Dealer Wins !!") if sum(p_cards) == 21: print( - "*******************You are the Winner !!*****************************" + "*******************You are the Winner !!*****************************", ) else: diff --git a/bodymass.py b/bodymass.py index be37d0db0ef..bfc2c01e1ee 100644 --- a/bodymass.py +++ b/bodymass.py @@ -1,19 +1,19 @@ -kilo = float (input("kilonuzu giriniz(örnek: 84.9): ")) -boy = float (input("Boyunuzu m cinsinden giriniz: ")) +kilo = float(input("kilonuzu giriniz(örnek: 84.9): ")) +boy = float(input("Boyunuzu m cinsinden giriniz: ")) -vki = (kilo / (boy**2)) +vki = kilo / (boy**2) if vki < 18.5: print(f"vucut kitle indeksiniz: {vki} zayıfsınız.") elif vki < 25: - print (f"vucut kitle indeksiniz: {vki} normalsiniz.") + print(f"vucut kitle indeksiniz: {vki} normalsiniz.") elif vki < 30: - print (f"vucut kitle indeksiniz: {vki} fazla kilolusunuz.") + print(f"vucut kitle indeksiniz: {vki} fazla kilolusunuz.") elif vki < 35: - print (f"vucut kitle indeksiniz: {vki} 1. derece obezsiniz") + print(f"vucut kitle indeksiniz: {vki} 1. derece obezsiniz") elif vki < 40: - print (f"vucut kitle indeksiniz: {vki} 2.derece obezsiniz.") -elif vki >40: - print (f"vucut kitle indeksiniz: {vki} 3.derece obezsiniz.") + print(f"vucut kitle indeksiniz: {vki} 2.derece obezsiniz.") +elif vki > 40: + print(f"vucut kitle indeksiniz: {vki} 3.derece obezsiniz.") else: print("Yanlış değer girdiniz.") diff --git a/bookstore_manangement_system.py b/bookstore_manangement_system.py index 7ae31cb195b..25d954a1726 100644 --- a/bookstore_manangement_system.py +++ b/bookstore_manangement_system.py @@ -1,10 +1,12 @@ import os - import mysql.connector as mys mycon = mys.connect( - host="localhost", user="root", passwd="Yksrocks", database="book_store_management" + host="localhost", + user="root", + passwd="Yksrocks", + database="book_store_management", ) @@ -216,7 +218,7 @@ def CNB2(): separator() print( - " Password Is Greater than 20 Characters Enter Again" + " Password Is Greater than 20 Characters Enter Again", ) separator() @@ -379,7 +381,7 @@ def CNB2(): separator() rep = input( - "Do You Want To Restart ?? yes / no -- " + "Do You Want To Restart ?? yes / no -- ", ).lower() if rep == "yes": @@ -429,7 +431,7 @@ def CNB2(): separator() choice44 = input( - "DO YOU WANT TO BUY BOOK ? Y/N -- " + "DO YOU WANT TO BUY BOOK ? Y/N -- ", ) separator() @@ -464,7 +466,7 @@ def CNB2(): if y[6] <= 8: print( - "WARNING!!!!!!!!!!!!!!!!!!!!!!!" + "WARNING!!!!!!!!!!!!!!!!!!!!!!!", ) print( "NO. OF THIS BOOK IS LOW", @@ -480,7 +482,7 @@ def CNB2(): separator() rep = input( - "Do You Want To Restart ?? yes / no -- " + "Do You Want To Restart ?? yes / no -- ", ).lower() if rep == "yes": @@ -504,7 +506,7 @@ def CNB2(): elif choice44 == "n" or choice44 == "N": print( - "SORRY FOR INCONVENIENCE WE WILL TRY TO FULLFILL YOUR REQUIREMENT AS SOON AS POSSIBLE" + "SORRY FOR INCONVENIENCE WE WILL TRY TO FULLFILL YOUR REQUIREMENT AS SOON AS POSSIBLE", ) end_separator() @@ -512,7 +514,7 @@ def CNB2(): separator() rep = input( - "Do You Want To Restart ?? yes / no -- " + "Do You Want To Restart ?? yes / no -- ", ).lower() if rep == "yes": @@ -534,7 +536,7 @@ def CNB2(): elif y[6] == 0: print( - "SORRY NO BOOK LEFT WE WILL TRY TO FULLFILL YOUR REQUIREMENT AS SOON AS POSSIBLE" + "SORRY NO BOOK LEFT WE WILL TRY TO FULLFILL YOUR REQUIREMENT AS SOON AS POSSIBLE", ) end_separator() @@ -542,7 +544,7 @@ def CNB2(): separator() rep = input( - "Do You Want To Restart ?? yes / no -- " + "Do You Want To Restart ?? yes / no -- ", ).lower() if rep == "yes": @@ -589,7 +591,7 @@ def CNB2(): separator() rep = input( - "Do You Want To Restart ?? yes / no -- " + "Do You Want To Restart ?? yes / no -- ", ).lower() if rep == "yes": diff --git a/brickout-game/README.md b/brickout-game/README.md index ee998318816..6dfb6a159ca 100644 --- a/brickout-game/README.md +++ b/brickout-game/README.md @@ -1,13 +1,12 @@ # Brickout-Game in pygame -This is a simple brickout-game. It's includes ball, paddle, brick wall +This is a simple brickout-game. It's includes ball, paddle, brick wall and additional collision detection between these objects. Furthermore, logic for winning and losing and -scoring. The game is written in **Python 2**. +scoring. The game is written in **Python 2**. You start the game with ```python game.py``` -The game runs with 60 frames per second. +The game runs with 60 frames per second. I used a code sample for the basic structure of pygame from this site [http://programarcadegames.com/](http://programarcadegames.com/) The site contains a comprehensive introduction in Python and Pygame. In addition many many examples. - diff --git a/brickout-game/brickout-game.py b/brickout-game/brickout-game.py index c212be6a634..d88af2b0fc1 100644 --- a/brickout-game/brickout-game.py +++ b/brickout-game/brickout-game.py @@ -1,11 +1,11 @@ """ Pygame base template for opening a window - + Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ - + Explanation video: http://youtu.be/vRB_983kUMc ------------------------------------------------- @@ -33,12 +33,12 @@ screen = pygame.display.set_mode(size) """ - This is a simple Ball class for respresenting a ball - in the game. + This is a simple Ball class for respresenting a ball + in the game. """ -class Ball(object): +class Ball: def __init__(self, screen, radius, x, y): self.__screen = screen self._radius = radius @@ -107,7 +107,7 @@ def update(self, paddle, brickwall): """ -class Paddle(object): +class Paddle: def __init__(self, screen, width, height, x, y): self.__screen = screen self._width = width @@ -123,7 +123,10 @@ def draw(self): draws the paddle onto screen. """ pygame.draw.rect( - screen, (0, 0, 0), (self._xLoc, self._yLoc, self._width, self._height), 0 + screen, + (0, 0, 0), + (self._xLoc, self._yLoc, self._width, self._height), + 0, ) def update(self): @@ -212,7 +215,7 @@ def collide(self, ball): """ - This is a simple class for representing a + This is a simple class for representing a brick wall. """ diff --git a/calc_area.py b/calc_area.py index 7f35917c746..b1825f550ef 100644 --- a/calc_area.py +++ b/calc_area.py @@ -6,12 +6,12 @@ def main(): shape = int( input( - "Enter 1 for square, 2 for rectangle, 3 for circle, 4 for triangle, 5 for cylinder, 6 for cone, or 7 for sphere: " - ) + "Enter 1 for square, 2 for rectangle, 3 for circle, 4 for triangle, 5 for cylinder, 6 for cone, or 7 for sphere: ", + ), ) if shape == 1: side = float(input("Enter length of side: ")) - print("Area of square = " + str(side ** 2)) + print("Area of square = " + str(side**2)) elif shape == 2: l = float(input("Enter length: ")) b = float(input("Enter breadth: ")) diff --git a/calculator-gui.py b/calculator-gui.py index e0a0ea5a28d..9342d94404f 100755 --- a/calculator-gui.py +++ b/calculator-gui.py @@ -1,7 +1,6 @@ # ==================== Libraries ==================== import tkinter as tk -from tkinter import ttk -from tkinter import messagebox +from tkinter import messagebox, ttk # =================================================== # ==================== Classes ====================== @@ -128,7 +127,8 @@ def press_plus(self): self.value1 = self.out_var.get() if self.value1 == "": messagebox.showwarning( - "Operator Before Number", "Please Enter Number Before Operator" + "Operator Before Number", + "Please Enter Number Before Operator", ) else: self.out_var.set("") @@ -138,7 +138,8 @@ def press_min(self): self.value1 = self.out_var.get() if self.value1 == "": messagebox.showwarning( - "Operator Before Number", "Please Enter Number Before Operator" + "Operator Before Number", + "Please Enter Number Before Operator", ) else: self.out_var.set("") @@ -148,7 +149,8 @@ def press_mul(self): self.value1 = self.out_var.get() if self.value1 == "": messagebox.showwarning( - "Operator Before Number", "Please Enter Number Before Operator" + "Operator Before Number", + "Please Enter Number Before Operator", ) else: self.out_var.set("") @@ -158,7 +160,8 @@ def press_div(self): self.value1 = self.out_var.get() if self.value1 == "": messagebox.showwarning( - "Operator Before Number", "Please Enter Number Before Operator" + "Operator Before Number", + "Please Enter Number Before Operator", ) else: self.out_var.set("") @@ -170,7 +173,8 @@ def press_equal(self): self.value2 = self.out_var.get() if self.value2 == "": messagebox.showerror( - "Second Number", "Please Enter Second Number To Perform Calculation" + "Second Number", + "Please Enter Second Number To Perform Calculation", ) else: @@ -198,7 +202,8 @@ def press_equal(self): except ValueError: messagebox.showinfo( - "Restart", "Please Close And Restart Application...Sorry" + "Restart", + "Please Close And Restart Application...Sorry", ) def cal_buttons(self): diff --git a/calculator.py b/calculator.py index b0ef5dca8dd..cae13e9c008 100644 --- a/calculator.py +++ b/calculator.py @@ -2,7 +2,7 @@ Written by : Shreyas Daniel - github.com/shreydan Description : Uses Pythons eval() function as a way to implement calculator. - + Functions available are: -------------------------------------------- + : addition @@ -11,7 +11,7 @@ / : division % : percentage e : 2.718281... - pi : 3.141592... + pi : 3.141592... sine : sin(rad) cosine : cos(rad) exponent: x^y @@ -25,9 +25,10 @@ import sys +from fileinfo import raw_input + ## Imported math library to run sin(), cos(), tan() and other such functions in the calculator -from fileinfo import raw_input def calc(term): @@ -111,7 +112,7 @@ def main(): print( "\nScientific Calculator\n\nFor Example: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2)" - + "- 12mod3\n\nEnter quit to exit" + + "- 12mod3\n\nEnter quit to exit", ) if sys.version_info.major >= 3: diff --git a/cartesian_product.py b/cartesian_product.py index 7ed49aae295..dd1926b6e80 100644 --- a/cartesian_product.py +++ b/cartesian_product.py @@ -9,11 +9,11 @@ def cartesian_product(list1, list2): """Cartesian Product of Two Lists.""" for _i in list1: for _j in list2: - print((_i, _j), end=' ') + print((_i, _j), end=" ") # Main -if __name__ == '__main__': +if __name__ == "__main__": list1 = input().split() list2 = input().split() @@ -22,4 +22,3 @@ def cartesian_product(list1, list2): list2 = [int(i) for i in list2] cartesian_product(list1, list2) - diff --git a/changemac.py b/changemac.py index b5e86ceae09..f92cd25680c 100644 --- a/changemac.py +++ b/changemac.py @@ -44,7 +44,7 @@ def retrandmac(mac): print( "Your Current mac address = " + crrntmac - + "\nEnter Option to change Your MAC:\n1. Enter MAC address manually \n2. Automatic Random MAC address" + + "\nEnter Option to change Your MAC:\n1. Enter MAC address manually \n2. Automatic Random MAC address", ) opt = int(input()) diff --git a/chaos.py b/chaos.py index 520f3d44512..103c513cab3 100644 --- a/chaos.py +++ b/chaos.py @@ -6,7 +6,7 @@ def main(): while True: try: - x = float((input("Enter a number between 0 and 1: "))) + x = float(input("Enter a number between 0 and 1: ")) if 0 < x and x < 1: break else: diff --git a/check if a number positive , negative or zero b/check if a number positive , negative or zero index c47cda8ae78..7cbe03ce09c 100644 --- a/check if a number positive , negative or zero +++ b/check if a number positive , negative or zero @@ -13,4 +13,3 @@ if num >= 0: print("Positive number") else: print("Negative number") - diff --git a/check whether the string is Symmetrical or Palindrome.py b/check whether the string is Symmetrical or Palindrome.py index d29772e721a..3747bdc2c47 100644 --- a/check whether the string is Symmetrical or Palindrome.py +++ b/check whether the string is Symmetrical or Palindrome.py @@ -1,53 +1,55 @@ -def palindrome(a): - - mid = (len(a)-1)//2 +def palindrome(a): + + mid = (len(a) - 1) // 2 start = 0 - last = len(a)-1 + last = len(a) - 1 flag = 0 - - while(start= 2: file_names = sys.argv[1:] filteredfilenames_1 = list( - file_names + file_names, ) # To counter changing in the same list which you are iterating filteredfilenames_2 = list(file_names) # Iterate for each filename passed in command line argument @@ -44,7 +42,7 @@ def main(): if not os.path.isfile(filename): # Check the File exists print("[-] " + filename + " does not exist.") filteredfilenames_2.remove( - filename + filename, ) # remove non existing files from fileNames list continue diff --git a/check_for_sqlite_files.py b/check_for_sqlite_files.py index 556d348f8af..181d83a3084 100644 --- a/check_for_sqlite_files.py +++ b/check_for_sqlite_files.py @@ -8,13 +8,12 @@ # Description : Scans directories to check if there are any sqlite files in there -from __future__ import print_function import os def isSQLite3(filename): - from os.path import isfile, getsize + from os.path import getsize, isfile if not isfile(filename): return False @@ -37,11 +36,13 @@ def isSQLite3(filename): if isSQLite3(files): print(files) print( - "[+] '%s' **** is a SQLITE database file **** " % os.path.join(r, files) + "[+] '%s' **** is a SQLITE database file **** " + % os.path.join(r, files), ) log.write("[+] '%s' **** is a SQLITE database file **** " % files + "\n") else: log.write( - "[-] '%s' is NOT a sqlite database file" % os.path.join(r, files) + "\n" + "[-] '%s' is NOT a sqlite database file" % os.path.join(r, files) + + "\n", ) log.write("[-] '%s' is NOT a sqlite database file" % files + "\n") diff --git a/chicks_n_rabs.py b/chicks_n_rabs.py index fa82f161d1c..c0114a08060 100644 --- a/chicks_n_rabs.py +++ b/chicks_n_rabs.py @@ -2,7 +2,7 @@ Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Module to solve a classic ancient Chinese puzzle: -We count 35 heads and 94 legs among the chickens and rabbits in a farm. +We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? """ diff --git a/classicIndianCardMatch.py b/classicIndianCardMatch.py index 6c859fb8f4d..8a604f15334 100644 --- a/classicIndianCardMatch.py +++ b/classicIndianCardMatch.py @@ -76,7 +76,7 @@ def __str__(self): player1 = combinedDeck[0:52] player2 = combinedDeck[52:] print( - "Deck has been split into two and Human get a half and computer gets the other...\n" + "Deck has been split into two and Human get a half and computer gets the other...\n", ) # Begin play: @@ -97,20 +97,20 @@ def __str__(self): for card in range(len(player1)): input("Enter any key to place a card!!!\n") currentPlayer1Card = player1[card].rank - print("Your current card's rank: {}".format(currentPlayer1Card)) + print(f"Your current card's rank: {currentPlayer1Card}") centerPile.append(player1[card]) player1.pop(card) switchPlayer = False if currentPlayer2Card == currentPlayer1Card: player1 = player1 + centerPile print( - "The human got a match and takes all the cards from center pile.." + "The human got a match and takes all the cards from center pile..", ) break while switchPlayer == False: for card in range(len(player2)): currentPlayer2Card = player2[card].rank - print("Computer's current card's rank: {}".format(currentPlayer2Card)) + print(f"Computer's current card's rank: {currentPlayer2Card}") centerPile.append(player2[card]) player2.pop(card) switchPlayer = True @@ -121,4 +121,4 @@ def __str__(self): print("GAME OVER!!!\n") -print("Human has {} cards and computer has {}..".format(len(player1), len(player2))) +print(f"Human has {len(player1)} cards and computer has {len(player2)}..") diff --git a/cli_master/cli_master.py b/cli_master/cli_master.py index f57a3b192bb..67d44711c69 100644 --- a/cli_master/cli_master.py +++ b/cli_master/cli_master.py @@ -2,8 +2,6 @@ import sys from pprint import pprint -import sys - sys.path.append(os.path.realpath(".")) import inquirer # noqa diff --git a/cli_master/validation_page.py b/cli_master/validation_page.py index 8852781d4b7..a9f1c2bcffc 100644 --- a/cli_master/validation_page.py +++ b/cli_master/validation_page.py @@ -1,10 +1,12 @@ import re + def phone_validation(phone_number): # Match a typical US phone number format (xxx) xxx-xxxx - pattern = re.compile(r'^\(\d{3}\) \d{3}-\d{4}$') + pattern = re.compile(r"^\(\d{3}\) \d{3}-\d{4}$") return bool(pattern.match(phone_number)) + # Example usage: phone_number_input = input("Enter phone number: ") if phone_validation(phone_number_input): @@ -12,11 +14,13 @@ def phone_validation(phone_number): else: print("Invalid phone number.") + def email_validation(email): # Basic email format validation - pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$') + pattern = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$") return bool(pattern.match(email)) + # Example usage: email_input = input("Enter email address: ") if email_validation(email_input): @@ -29,6 +33,7 @@ def password_validation(password): # Password must be at least 8 characters long and contain at least one digit return len(password) >= 8 and any(char.isdigit() for char in password) + # Example usage: password_input = input("Enter password: ") if password_validation(password_input): @@ -39,7 +44,8 @@ def password_validation(password): def username_validation(username): # Allow only alphanumeric characters and underscores - return bool(re.match('^[a-zA-Z0-9_]+$', username)) + return bool(re.match("^[a-zA-Z0-9_]+$", username)) + # Example usage: username_input = input("Enter username: ") @@ -51,7 +57,8 @@ def username_validation(username): def country_validation(country): # Example: Allow only alphabetical characters and spaces - return bool(re.match('^[a-zA-Z ]+$', country)) + return bool(re.match("^[a-zA-Z ]+$", country)) + # Example usage: country_input = input("Enter country name: ") @@ -59,4 +66,3 @@ def country_validation(country): print("Country name is valid.") else: print("Invalid country name.") - diff --git a/cloning_a_list.py b/cloning_a_list.py index ceaebef16e7..ad638191e08 100644 --- a/cloning_a_list.py +++ b/cloning_a_list.py @@ -1,17 +1,18 @@ -# Python program to copy or clone a list -# Using the Slice Operator -def Cloning(li1): +# Python program to copy or clone a list +# Using the Slice Operator +def Cloning(li1): return li1[:] - -# Driver Code + + +# Driver Code li1 = [ - 4, - 8, - 2, - 10, - 15, - 18 -] -li2 = Cloning(li1) -print("Original List:", li1) -print("After Cloning:", li2) + 4, + 8, + 2, + 10, + 15, + 18, +] +li2 = Cloning(li1) +print("Original List:", li1) +print("After Cloning:", li2) diff --git a/colorma_as_color.py b/colorma_as_color.py index 9bf2338ebbb..c67cb73654e 100644 --- a/colorma_as_color.py +++ b/colorma_as_color.py @@ -1,7 +1,5 @@ import colorama as color - - -from colorama import Fore, Back, Style +from colorama import Back, Fore, Style print(Fore.RED + "some red text") print(Back.GREEN + "and with a green background") @@ -19,4 +17,4 @@ print("back to normal now") -# …or, Colorama can be used in conjunction with existing ANSI libraries such as the venerable Termcolor the fabulous Blessings, or the incredible _Rich. \ No newline at end of file +# …or, Colorama can be used in conjunction with existing ANSI libraries such as the venerable Termcolor the fabulous Blessings, or the incredible _Rich. diff --git a/colour spiral.py b/colour spiral.py index 86385ada09d..83c2785828a 100644 --- a/colour spiral.py +++ b/colour spiral.py @@ -1,52 +1,52 @@ # import turtle import turtle - + # defining colors -colors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange'] - +colors = ["red", "yellow", "green", "purple", "blue", "orange"] + # setup turtle pen -t= turtle.Pen() - +t = turtle.Pen() + # changes the speed of the turtle t.speed(10) - + # changes the background color turtle.bgcolor("black") - + # make spiral_web for x in range(200): - t.pencolor(colors[x%6]) # setting color + t.pencolor(colors[x % 6]) # setting color - t.width(x/100 + 1) # setting width + t.width(x / 100 + 1) # setting width - t.forward(x) # moving forward + t.forward(x) # moving forward + + t.left(59) # moving left - t.left(59) # moving left - turtle.done() t.speed(10) - -turtle.bgcolor("black") # changes the background color - + +turtle.bgcolor("black") # changes the background color + # make spiral_web for x in range(200): - t.pencolor(colors[x%6]) # setting color + t.pencolor(colors[x % 6]) # setting color - t.width(x/100 + 1) # setting width + t.width(x / 100 + 1) # setting width - t.forward(x) # moving forward + t.forward(x) # moving forward - t.left(59) # moving left - -turtle.done() \ No newline at end of file + t.left(59) # moving left + +turtle.done() diff --git a/communication/file.py b/communication/file.py index 4198d95ec0e..c3a82d1c6d3 100755 --- a/communication/file.py +++ b/communication/file.py @@ -1,5 +1,4 @@ #!/usr/bin/python -# coding: utf-8 import math import os @@ -30,7 +29,7 @@ def pi(n): sums = [] for pid in pids: os.waitpid(pid, 0) # 等待子进程结束 - with open("%d" % pid, "r") as f: + with open("%d" % pid) as f: sums.append(float(f.read())) os.remove("%d" % pid) # 删除通信的文件 return math.sqrt(sum(sums) * 8) diff --git a/communication/pipe.py b/communication/pipe.py index 4138c519570..7f70a695ec5 100644 --- a/communication/pipe.py +++ b/communication/pipe.py @@ -1,7 +1,3 @@ -# coding: utf-8 - -from __future__ import print_function - import math import os import sys diff --git a/communication/socket_conn.py b/communication/socket_conn.py index ffe1ed437fa..24b5ebc5576 100644 --- a/communication/socket_conn.py +++ b/communication/socket_conn.py @@ -1,7 +1,3 @@ -# coding: utf-8 - -from __future__ import print_function - import math import os import socket diff --git a/convert celsius into fahrenheit.py b/convert celsius into fahrenheit.py index df58fcda9de..0f3bf8e9838 100644 --- a/convert celsius into fahrenheit.py +++ b/convert celsius into fahrenheit.py @@ -1,4 +1,4 @@ -cels= float(input("enter temp in celsius")) -print("temprature in celsius is :",cels) -fahr = cels*9/5+32 -print("temprature in fahrenhite is :",fahr) +cels = float(input("enter temp in celsius")) +print("temprature in celsius is :", cels) +fahr = cels * 9 / 5 + 32 +print("temprature in fahrenhite is :", fahr) diff --git a/convert_time.py b/convert_time.py index d7ff1c9f697..8d7c19eb421 100644 --- a/convert_time.py +++ b/convert_time.py @@ -1,5 +1,3 @@ -from __future__ import print_function - # Created by sarathkaul on 12/11/19 diff --git a/count the numbers of two vovels.py b/count the numbers of two vovels.py index 297e2488590..eb66d0967d6 100644 --- a/count the numbers of two vovels.py +++ b/count the numbers of two vovels.py @@ -1,19 +1,19 @@ # Program to count the number of each vowels # string of vowels -vowels = 'aeiou' +vowels = "aeiou" -ip_str = 'Hello, have you tried our tutorial section yet?' +ip_str = "Hello, have you tried our tutorial section yet?" # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 -count = {}.fromkeys(vowels,0) +count = {}.fromkeys(vowels, 0) # count the vowels for char in ip_str: - if char in count: - count[char] += 1 + if char in count: + count[char] += 1 print(count) diff --git a/create password validity in python.py b/create password validity in python.py index 46793e91061..c69a826e89e 100644 --- a/create password validity in python.py +++ b/create password validity in python.py @@ -1,24 +1,27 @@ import time -pwd=input("Enter your password: ") #any password u want to set + +pwd = input("Enter your password: ") # any password u want to set + def IInd_func(): - count1=0 - for j in range(5): - a=0 - count=0 - user_pwd = input("Enter remember password: ") #password you remember - for i in range(len(pwd)): - if user_pwd[i] == pwd[a]: #comparing remembered pwd with fixed pwd - a +=1 - count+=1 - if count==len(pwd): - print("correct pwd") - break - else: - count1 += 1 - print("not correct") - if count1==5: - time.sleep(30) - IInd_func() + count1 = 0 + for j in range(5): + a = 0 + count = 0 + user_pwd = input("Enter remember password: ") # password you remember + for i in range(len(pwd)): + if user_pwd[i] == pwd[a]: # comparing remembered pwd with fixed pwd + a += 1 + count += 1 + if count == len(pwd): + print("correct pwd") + break + else: + count1 += 1 + print("not correct") + if count1 == 5: + time.sleep(30) + IInd_func() + -IInd_func() \ No newline at end of file +IInd_func() diff --git a/create_dir_if_not_there.py b/create_dir_if_not_there.py index a50db085346..b31b90713c8 100644 --- a/create_dir_if_not_there.py +++ b/create_dir_if_not_there.py @@ -14,15 +14,15 @@ TESTDIR = "testdir" try: home = os.path.expanduser( - "~" + "~", ) # Set the variable home by expanding the user's set home directory print(home) # Print the location if not os.path.exists( - os.path.join(home, TESTDIR) + os.path.join(home, TESTDIR), ): # os.path.join() for making a full path safely os.makedirs( - os.path.join(home, TESTDIR) + os.path.join(home, TESTDIR), ) # If not create the directory, inside their home directory else: print(MESSAGE) diff --git a/cricket_news.py b/cricket_news.py index 8c78c1820e6..b5c6405a28f 100644 --- a/cricket_news.py +++ b/cricket_news.py @@ -1,6 +1,6 @@ -from bs4 import BeautifulSoup -import requests import pyttsx3 +import requests +from bs4 import BeautifulSoup engine = pyttsx3.init() voices = engine.getProperty("voices") diff --git a/currency converter/country.txt b/currency converter/country.txt index 0398e381859..c063709a938 100644 --- a/currency converter/country.txt +++ b/currency converter/country.txt @@ -174,4 +174,4 @@ Venezuela Bolivar-VEB Vietnam Dong-VND Yemen Rial-YER Zambia Kwacha-ZMK -Zimbabwe Dollar-ZWD \ No newline at end of file +Zimbabwe Dollar-ZWD diff --git a/currency converter/main.py b/currency converter/main.py index a75a047c724..181973cb6ea 100644 --- a/currency converter/main.py +++ b/currency converter/main.py @@ -1,11 +1,10 @@ # cc program -from PyQt5.QtGui import * -from PyQt5.QtCore import * -from PyQt5.QtWidgets import * -from PyQt5 import QtWidgets, uic -from PyQt5.QtCore import * import requests from bs4 import BeautifulSoup +from PyQt5 import QtWidgets, uic +from PyQt5.QtCore import * +from PyQt5.QtGui import * +from PyQt5.QtWidgets import * from requests.models import ContentDecodingError @@ -27,10 +26,10 @@ def getVal(cont1, cont2): app = QtWidgets.QApplication([]) window = uic.loadUi("gui.ui") -f = open("country.txt", "r") +f = open("country.txt") window = uic.loadUi("C:/Users/prath/Desktop/Currency-Calculator-Dynamic/gui.ui") -f = open("C:/Users/prath/Desktop/Currency-Calculator-Dynamic/country.txt", "r") +f = open("C:/Users/prath/Desktop/Currency-Calculator-Dynamic/country.txt") window.dropDown1.addItem("Select") window.dropDown2.addItem("Select") diff --git a/daily_checks.py b/daily_checks.py index 337f8d5aebe..8198e72fcf0 100644 --- a/daily_checks.py +++ b/daily_checks.py @@ -31,11 +31,11 @@ def print_docs(): # Function to print the daily checks automatically # The command below passes the command line string to open word, open the document, print it then close word down subprocess.Popen( [ - "C:\\Program Files (x86)\Microsoft Office\Office14\winword.exe", + "C:\\Program Files (x86)\\Microsoft Office\\Office14\\winword.exe", "P:\\\\Documentation\\Daily Docs\\Back office Daily Checks.doc", "/mFilePrintDefault", "/mFileExit", - ] + ], ).communicate() @@ -43,13 +43,13 @@ def putty_sessions(conffilename): # Function to load the putty sessions I need # Open the file server_list.txt, loop through reading each line # 1.1 -Changed - 1.3 Changed name to use variable conffilename for server in open(conffilename): - subprocess.Popen(("putty -load " + server)) # Open the PuTTY sessions - 1.1 + subprocess.Popen("putty -load " + server) # Open the PuTTY sessions - 1.1 def rdp_sessions(): print("Loading RDP Sessions:") subprocess.Popen( - "mstsc eclr.rdp" + "mstsc eclr.rdp", ) # Open up a terminal session connection and load the euroclear session @@ -57,7 +57,7 @@ def euroclear_docs(): # The command below opens IE and loads the Euroclear password document subprocess.Popen( '"C:\\Program Files\\Internet Explorer\\iexplore.exe"' - '"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"' + r'"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"', ) @@ -68,7 +68,7 @@ def euroclear_docs(): def main(): filename = sys.argv[0] # Create the variable filename confdir = os.getenv( - "my_config" + "my_config", ) # Set the variable confdir from the OS environment variable - 1.3 conffile = "daily_checks_servers.conf" # Set the variable conffile - 1.3 # Set the variable conffilename by joining confdir and conffile together - 1.3 diff --git a/daily_horoscope.py b/daily_horoscope.py index 04669971819..556be32753c 100644 --- a/daily_horoscope.py +++ b/daily_horoscope.py @@ -1,5 +1,5 @@ -from bs4 import BeautifulSoup import requests +from bs4 import BeautifulSoup """ this check_sign function checks and returns the zodiac sign diff --git a/days_from_date.py b/days_from_date.py index 3a166679607..c9d101ed612 100644 --- a/days_from_date.py +++ b/days_from_date.py @@ -1,6 +1,6 @@ -import re # regular expressions import calendar # module of python to provide useful fucntions related to calendar import datetime # module of python to get the date and time +import re # regular expressions import tkinter as tk root = tk.Tk() @@ -16,7 +16,8 @@ def process_date(user_input): def find_day(date): born = datetime.datetime.strptime( - date, "%d %m %Y" + date, + "%d %m %Y", ).weekday() # this statement returns an integer corresponding to the day of the week return calendar.day_name[ born @@ -31,15 +32,22 @@ def printt(): date = process_date(user_input) c = "Day on " + user_input + " is " + find_day(date) label2 = tk.Label(root, text=c, font=("Times new roman", 20), fg="black").place( - x=20, y=200 + x=20, + y=200, ) lbl = tk.Label(root, text="Date --", font=("Ubuntu", 20), fg="black").place( - x=0, y=0.1, height=60, width=150 + x=0, + y=0.1, + height=60, + width=150, ) lbl1 = tk.Label(root, text="(DD/MM/YYYY)", font=("Ubuntu", 15), fg="Gray").place( - x=120, y=0.1, height=60, width=150 + x=120, + y=0.1, + height=60, + width=150, ) but = tk.Button( root, @@ -51,7 +59,11 @@ def printt(): bg="black", ).place(x=50, y=130, height=50, width=300) Date = tk.Entry( - root, font=("Times new roman", 20), textvariable=user_input1, bg="white", fg="black" + root, + font=("Times new roman", 20), + textvariable=user_input1, + bg="white", + fg="black", ).place(x=30, y=50, height=40, width=340) root.mainloop() diff --git a/decimal to binary.py b/decimal to binary.py index 566f83be43c..03619b074c2 100644 --- a/decimal to binary.py +++ b/decimal to binary.py @@ -3,7 +3,7 @@ def decimalToBinary(num): to binary and prints it""" if num > 1: decimalToBinary(num // 2) - print(num % 2, end='') + print(num % 2, end="") # decimal number diff --git a/depreciated_programs/corona_cases.py b/depreciated_programs/corona_cases.py index e93e7cd99f9..e8448b46558 100644 --- a/depreciated_programs/corona_cases.py +++ b/depreciated_programs/corona_cases.py @@ -30,8 +30,8 @@ def world(): world = f""" -▀▀█▀▀ █▀▀█ ▀▀█▀▀ █▀▀█ █░░   ▒█▀▀█ █▀▀█ █▀▀ █▀▀ █▀▀   ▀█▀ █▀▀▄   ▒█░░▒█ █▀▀█ █▀▀█ █░░ █▀▀▄ -░▒█░░ █░░█ ░░█░░ █▄▄█ █░░   ▒█░░░ █▄▄█ ▀▀█ █▀▀ ▀▀█   ▒█░ █░░█   ▒█▒█▒█ █░░█ █▄▄▀ █░░ █░░█ +▀▀█▀▀ █▀▀█ ▀▀█▀▀ █▀▀█ █░░   ▒█▀▀█ █▀▀█ █▀▀ █▀▀ █▀▀   ▀█▀ █▀▀▄   ▒█░░▒█ █▀▀█ █▀▀█ █░░ █▀▀▄ +░▒█░░ █░░█ ░░█░░ █▄▄█ █░░   ▒█░░░ █▄▄█ ▀▀█ █▀▀ ▀▀█   ▒█░ █░░█   ▒█▒█▒█ █░░█ █▄▄▀ █░░ █░░█ ░▒█░░ ▀▀▀▀ ░░▀░░ ▀░░▀ ▀▀▀   ▒█▄▄█ ▀░░▀ ▀▀▀ ▀▀▀ ▀▀▀   ▄█▄ ▀░░▀   ▒█▄▀▄█ ▀▀▀▀ ▀░▀▀ ▀▀▀ ▀▀▀░\n New Confirmed Cases :- {NewConfirmed} Total Confirmed Cases :- {TotalConfirmed} @@ -71,7 +71,7 @@ def india(): ██║░░╚═╝██║░░██║██████╔╝██║░░██║██╔██╗██║███████║  ╚██╗░██╔╝██║██████╔╝██║░░░██║╚█████╗░ ██║░░██╗██║░░██║██╔══██╗██║░░██║██║╚████║██╔══██║  ░╚████╔╝░██║██╔══██╗██║░░░██║░╚═══██╗ ╚█████╔╝╚█████╔╝██║░░██║╚█████╔╝██║░╚███║██║░░██║  ░░╚██╔╝░░██║██║░░██║╚██████╔╝██████╔╝ -░╚════╝░░╚════╝░╚═╝░░╚═╝░╚════╝░╚═╝░░╚══╝╚═╝░░╚═╝  ░░░╚═╝░░░╚═╝╚═╝░░╚═╝░╚═════╝░╚═════╝░""" +░╚════╝░░╚════╝░╚═╝░░╚═╝░╚════╝░╚═╝░░╚══╝╚═╝░░╚═╝  ░░░╚═╝░░░╚═╝╚═╝░░╚═╝░╚═════╝░╚═════╝░""", ) print("\nDeveloped By @TheDarkW3b") diff --git a/dialogs/messagebox.py b/dialogs/messagebox.py index 14a88dc185d..46410ac4db4 100644 --- a/dialogs/messagebox.py +++ b/dialogs/messagebox.py @@ -3,5 +3,6 @@ from quo.dialog import MessageBox MessageBox( - title='Example dialog window', - text='Do you want to continue?') + title="Example dialog window", + text="Do you want to continue?", +) diff --git a/dice.py b/dice.py index a2e5c12f99b..90ea7414753 100644 --- a/dice.py +++ b/dice.py @@ -12,7 +12,7 @@ import random -class Die(object): +class Die: # A dice has a feature of number about how many sides it has when it's # established,like 6. def __init__(self): diff --git a/diceV2_dynamic.py b/diceV2_dynamic.py index a0dcbcfbc61..4c4d450ba30 100644 --- a/diceV2_dynamic.py +++ b/diceV2_dynamic.py @@ -12,7 +12,7 @@ def setSides(self, sides): else: print( "This absolutely shouldn't ever happen. The programmer sucks or someone " - "has tweaked with code they weren't supposed to touch!" + "has tweaked with code they weren't supposed to touch!", ) def roll(self): @@ -63,7 +63,9 @@ def getDices(): sides = pickNumber(sides, "How many sides will the dices have?: ", sideLowerLimit) diceAmount = pickNumber( - diceAmount, "How many dices will do you want?: ", diceLowerLimit + diceAmount, + "How many dices will do you want?: ", + diceLowerLimit, ) for i in range(0, diceAmount): diff --git a/dice_rolling_simulator.py b/dice_rolling_simulator.py index fd7b5701e92..d0d21973622 100644 --- a/dice_rolling_simulator.py +++ b/dice_rolling_simulator.py @@ -83,7 +83,7 @@ def dice12(): def user_exit_checker(): # Checking if the user would like to roll another die, or to exit the program user_exit_checker_raw = input( - "\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>" + "\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>", ) user_exit_checker = user_exit_checker_raw.lower() if user_exit_checker == "roll": diff --git a/diction.py b/diction.py index 8fc071cb6b8..68a352e1158 100644 --- a/diction.py +++ b/diction.py @@ -1,6 +1,7 @@ +import json from difflib import get_close_matches + import pyttsx3 -import json import speech_recognition as sr data = json.load(open("data.json")) diff --git a/different model output b/different model output index c45cf1dff2e..48da7588d79 100644 --- a/different model output +++ b/different model output @@ -10,4 +10,4 @@ linear Regression : Random forest regressor: Mean: 3.3009631251857217 - Standard deviation: 0.7076841067486248 \ No newline at end of file + Standard deviation: 0.7076841067486248 diff --git a/digital_clock.py b/digital_clock.py index f461878917b..bf08d16a46d 100644 --- a/digital_clock.py +++ b/digital_clock.py @@ -4,22 +4,21 @@ # using python code base import time - +# importing strftime function to +# retrieve system's time +from time import strftime # because we need digital clock , so we are importing the time library. # master from tkinter import * from tkinter.ttk import * -# importing strftime function to -# retrieve system's time -from time import strftime - # creating tkinter window root = Tk() root.title("Clock") # master + # This function is used to # display time on the label def def_time(): diff --git a/dir_test.py b/dir_test.py index 992d5924a88..f9faa65e5d9 100644 --- a/dir_test.py +++ b/dir_test.py @@ -6,7 +6,6 @@ # Modifications : # Description : Tests to see if the directory testdir exists, if not it will create the directory for you if you want it created. -from __future__ import print_function import os diff --git a/divisors_of_a_number.py b/divisors_of_a_number.py index 326378b177f..55ffd18a753 100644 --- a/divisors_of_a_number.py +++ b/divisors_of_a_number.py @@ -1,20 +1,20 @@ a = 0 -while a<= 0 : +while a <= 0: number_to_divide = input("choose the number to divide -->") - try : + try: a = int(number_to_divide) - except ValueError : + except ValueError: a = 0 - if a <= 0 : - print('choose a number grether than 0') + if a <= 0: + print("choose a number grether than 0") list_number_divided = [] -for number in range(1,a + 1) : +for number in range(1, a + 1): b = a % number - if b == 0 : + if b == 0: list_number_divided.append(number) -print('\nthe number ' + number_to_divide + ' can be divided by:') -for item in list_number_divided : - print(f'{item}') -if len(list_number_divided) <= 2 : - print(number_to_divide + ' is a prime number') \ No newline at end of file +print("\nthe number " + number_to_divide + " can be divided by:") +for item in list_number_divided: + print(f"{item}") +if len(list_number_divided) <= 2: + print(number_to_divide + " is a prime number") diff --git a/email id dictionary/README.md b/email id dictionary/README.md index 0ea1bc885e6..d147ddc2dd6 100644 --- a/email id dictionary/README.md +++ b/email id dictionary/README.md @@ -1 +1 @@ -Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer. \ No newline at end of file +Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer. diff --git a/email id dictionary/mbox-short.txt b/email id dictionary/mbox-short.txt index dc1138cf49f..1cefaa67667 100644 --- a/email id dictionary/mbox-short.txt +++ b/email id dictionary/mbox-short.txt @@ -11,7 +11,7 @@ Received: from holes.mr.itd.umich.edu (holes.mr.itd.umich.edu [141.211.14.79]) by flawless.mail.umich.edu () with ESMTP id m05EEFR1013674; Sat, 5 Jan 2008 09:14:15 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY holes.mr.itd.umich.edu ID 477F90B0.2DB2F.12494 ; + BY holes.mr.itd.umich.edu ID 477F90B0.2DB2F.12494 ; 5 Jan 2008 09:14:10 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 5F919BC2F2; @@ -76,7 +76,7 @@ Received: from icestorm.mr.itd.umich.edu (icestorm.mr.itd.umich.edu [141.211.93. by sleepers.mail.umich.edu () with ESMTP id m04NAbGa029441; Fri, 4 Jan 2008 18:10:37 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY icestorm.mr.itd.umich.edu ID 477EBCE3.161BB.4320 ; + BY icestorm.mr.itd.umich.edu ID 477EBCE3.161BB.4320 ; 4 Jan 2008 18:10:31 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 07969BB706; @@ -141,7 +141,7 @@ Received: from ghostbusters.mr.itd.umich.edu (ghostbusters.mr.itd.umich.edu [141 by panther.mail.umich.edu () with ESMTP id m04LAcZw014275; Fri, 4 Jan 2008 16:10:38 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY ghostbusters.mr.itd.umich.edu ID 477EA0C6.A0214.25480 ; + BY ghostbusters.mr.itd.umich.edu ID 477EA0C6.A0214.25480 ; 4 Jan 2008 16:10:33 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id C48CDBB490; @@ -205,7 +205,7 @@ Received: from dreamcatcher.mr.itd.umich.edu (dreamcatcher.mr.itd.umich.edu [141 by panther.mail.umich.edu () with ESMTP id m04KkNbx032077; Fri, 4 Jan 2008 15:46:23 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY dreamcatcher.mr.itd.umich.edu ID 477E9B13.2F3BC.22965 ; + BY dreamcatcher.mr.itd.umich.edu ID 477E9B13.2F3BC.22965 ; 4 Jan 2008 15:46:13 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 4AE03BB552; @@ -273,7 +273,7 @@ Received: from firestarter.mr.itd.umich.edu (firestarter.mr.itd.umich.edu [141.2 by fan.mail.umich.edu () with ESMTP id m04K3HGF006563; Fri, 4 Jan 2008 15:03:17 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY firestarter.mr.itd.umich.edu ID 477E9100.8F7F4.1590 ; + BY firestarter.mr.itd.umich.edu ID 477E9100.8F7F4.1590 ; 4 Jan 2008 15:03:15 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 57770BB477; @@ -322,7 +322,7 @@ Sakai Source Repository #38024 Wed Nov 07 14:54:46 MST 2007 zqian@umich.ed Watch for enrollments object being null and concatenate provider ids when there are more than one. Files Changed -MODIFY /site-manage/trunk/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java +MODIFY /site-manage/trunk/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java @@ -346,7 +346,7 @@ Received: from eyewitness.mr.itd.umich.edu (eyewitness.mr.itd.umich.edu [141.211 by mission.mail.umich.edu () with ESMTP id m04JoHJi019755; Fri, 4 Jan 2008 14:50:17 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY eyewitness.mr.itd.umich.edu ID 477E8DF2.67B91.5278 ; + BY eyewitness.mr.itd.umich.edu ID 477E8DF2.67B91.5278 ; 4 Jan 2008 14:50:13 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 2D1B9BB492; @@ -425,7 +425,7 @@ Received: from tadpole.mr.itd.umich.edu (tadpole.mr.itd.umich.edu [141.211.14.72 by fan.mail.umich.edu () with ESMTP id m04GbT9x022078; Fri, 4 Jan 2008 11:37:29 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY tadpole.mr.itd.umich.edu ID 477E60B2.82756.9904 ; + BY tadpole.mr.itd.umich.edu ID 477E60B2.82756.9904 ; 4 Jan 2008 11:37:09 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 8D13DBB001; @@ -504,7 +504,7 @@ Received: from it.mr.itd.umich.edu (it.mr.itd.umich.edu [141.211.93.151]) by fan.mail.umich.edu () with ESMTP id m04GZ6lt020480; Fri, 4 Jan 2008 11:35:06 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY it.mr.itd.umich.edu ID 477E6033.6469D.21870 ; + BY it.mr.itd.umich.edu ID 477E6033.6469D.21870 ; 4 Jan 2008 11:35:02 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id E40FABAE5B; @@ -583,7 +583,7 @@ Received: from holes.mr.itd.umich.edu (holes.mr.itd.umich.edu [141.211.14.79]) by panther.mail.umich.edu () with ESMTP id m04GCaHB030887; Fri, 4 Jan 2008 11:12:36 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY holes.mr.itd.umich.edu ID 477E5AEB.E670B.28397 ; + BY holes.mr.itd.umich.edu ID 477E5AEB.E670B.28397 ; 4 Jan 2008 11:12:30 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 99715BAE7D; @@ -649,7 +649,7 @@ Received: from creepshow.mr.itd.umich.edu (creepshow.mr.itd.umich.edu [141.211.1 by godsend.mail.umich.edu () with ESMTP id m04GBqqv025330; Fri, 4 Jan 2008 11:11:52 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY creepshow.mr.itd.umich.edu ID 477E5AB3.5CC32.30840 ; + BY creepshow.mr.itd.umich.edu ID 477E5AB3.5CC32.30840 ; 4 Jan 2008 11:11:34 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 62AA4BAE46; @@ -715,7 +715,7 @@ Received: from carrie.mr.itd.umich.edu (carrie.mr.itd.umich.edu [141.211.93.152] by sleepers.mail.umich.edu () with ESMTP id m04GB3Vg011502; Fri, 4 Jan 2008 11:11:03 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY carrie.mr.itd.umich.edu ID 477E5A8D.B378F.24200 ; + BY carrie.mr.itd.umich.edu ID 477E5A8D.B378F.24200 ; 4 Jan 2008 11:10:56 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id C7251BAD44; @@ -780,7 +780,7 @@ Received: from holes.mr.itd.umich.edu (holes.mr.itd.umich.edu [141.211.14.79]) by faithful.mail.umich.edu () with ESMTP id m04GAL9k010604; Fri, 4 Jan 2008 11:10:21 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY holes.mr.itd.umich.edu ID 477E5A67.34350.23015 ; + BY holes.mr.itd.umich.edu ID 477E5A67.34350.23015 ; 4 Jan 2008 11:10:18 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 98D04BAD43; @@ -846,7 +846,7 @@ Received: from shining.mr.itd.umich.edu (shining.mr.itd.umich.edu [141.211.93.15 by flawless.mail.umich.edu () with ESMTP id m04Fcfjm012313; Fri, 4 Jan 2008 10:38:41 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY shining.mr.itd.umich.edu ID 477E52FA.E6C6E.24093 ; + BY shining.mr.itd.umich.edu ID 477E52FA.E6C6E.24093 ; 4 Jan 2008 10:38:37 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 6A39594CD2; @@ -915,7 +915,7 @@ Received: from creepshow.mr.itd.umich.edu (creepshow.mr.itd.umich.edu [141.211.1 by sleepers.mail.umich.edu () with ESMTP id m04FHgfs011536; Fri, 4 Jan 2008 10:17:42 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY creepshow.mr.itd.umich.edu ID 477E4E0F.CCA4B.926 ; + BY creepshow.mr.itd.umich.edu ID 477E4E0F.CCA4B.926 ; 4 Jan 2008 10:17:38 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id BD02DBAC64; @@ -980,7 +980,7 @@ Received: from holes.mr.itd.umich.edu (holes.mr.itd.umich.edu [141.211.14.79]) by panther.mail.umich.edu () with ESMTP id m04F4Dci015108; Fri, 4 Jan 2008 10:04:13 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY holes.mr.itd.umich.edu ID 477E4AE3.D7AF.31669 ; + BY holes.mr.itd.umich.edu ID 477E4AE3.D7AF.31669 ; 4 Jan 2008 10:04:05 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 933E3BAC17; @@ -1057,7 +1057,7 @@ Received: from guys.mr.itd.umich.edu (guys.mr.itd.umich.edu [141.211.14.76]) by flawless.mail.umich.edu () with ESMTP id m04E5U3C029277; Fri, 4 Jan 2008 09:05:30 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY guys.mr.itd.umich.edu ID 477E3D23.EE2E7.5237 ; + BY guys.mr.itd.umich.edu ID 477E3D23.EE2E7.5237 ; 4 Jan 2008 09:05:26 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 33C7856DC0; @@ -1131,7 +1131,7 @@ Received: from guys.mr.itd.umich.edu (guys.mr.itd.umich.edu [141.211.14.76]) by faithful.mail.umich.edu () with ESMTP id m04C2VN7026678; Fri, 4 Jan 2008 07:02:31 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY guys.mr.itd.umich.edu ID 477E2050.C2599.3263 ; + BY guys.mr.itd.umich.edu ID 477E2050.C2599.3263 ; 4 Jan 2008 07:02:27 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 6497FBA906; @@ -1217,7 +1217,7 @@ Received: from firestarter.mr.itd.umich.edu (firestarter.mr.itd.umich.edu [141.2 by casino.mail.umich.edu () with ESMTP id m04B8Qw9001368; Fri, 4 Jan 2008 06:08:26 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY firestarter.mr.itd.umich.edu ID 477E13A5.30FC0.24054 ; + BY firestarter.mr.itd.umich.edu ID 477E13A5.30FC0.24054 ; 4 Jan 2008 06:08:23 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 784A476D7B; @@ -1286,7 +1286,7 @@ Received: from galaxyquest.mr.itd.umich.edu (galaxyquest.mr.itd.umich.edu [141.2 by score.mail.umich.edu () with ESMTP id m049n60G017588; Fri, 4 Jan 2008 04:49:06 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY galaxyquest.mr.itd.umich.edu ID 477E010C.48C2.10259 ; + BY galaxyquest.mr.itd.umich.edu ID 477E010C.48C2.10259 ; 4 Jan 2008 04:49:03 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 254CC8CDEE; @@ -1364,7 +1364,7 @@ Received: from workinggirl.mr.itd.umich.edu (workinggirl.mr.itd.umich.edu [141.2 by fan.mail.umich.edu () with ESMTP id m049Xge3031803; Fri, 4 Jan 2008 04:33:42 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY workinggirl.mr.itd.umich.edu ID 477DFD6C.75DBE.26054 ; + BY workinggirl.mr.itd.umich.edu ID 477DFD6C.75DBE.26054 ; 4 Jan 2008 04:33:35 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 6C929BA656; @@ -1450,7 +1450,7 @@ Received: from salemslot.mr.itd.umich.edu (salemslot.mr.itd.umich.edu [141.211.1 by panther.mail.umich.edu () with ESMTP id m0497WAN027902; Fri, 4 Jan 2008 04:07:32 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY salemslot.mr.itd.umich.edu ID 477DF74E.49493.30415 ; + BY salemslot.mr.itd.umich.edu ID 477DF74E.49493.30415 ; 4 Jan 2008 04:07:29 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 88598BA5B6; @@ -1514,7 +1514,7 @@ Received: from eyewitness.mr.itd.umich.edu (eyewitness.mr.itd.umich.edu [141.211 by jacknife.mail.umich.edu () with ESMTP id m040pJHB027171; Thu, 3 Jan 2008 19:51:19 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY eyewitness.mr.itd.umich.edu ID 477D8300.AC098.32562 ; + BY eyewitness.mr.itd.umich.edu ID 477D8300.AC098.32562 ; 3 Jan 2008 19:51:15 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id E6CC4B9F8A; @@ -1579,7 +1579,7 @@ Received: from salemslot.mr.itd.umich.edu (salemslot.mr.itd.umich.edu [141.211.1 by jacknife.mail.umich.edu () with ESMTP id m03MIMXY027729; Thu, 3 Jan 2008 17:18:22 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY salemslot.mr.itd.umich.edu ID 477D5F23.797F6.16348 ; + BY salemslot.mr.itd.umich.edu ID 477D5F23.797F6.16348 ; 3 Jan 2008 17:18:14 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id EF439B98CE; @@ -1644,7 +1644,7 @@ Received: from anniehall.mr.itd.umich.edu (anniehall.mr.itd.umich.edu [141.211.9 by faithful.mail.umich.edu () with ESMTP id m03M6xaq014868; Thu, 3 Jan 2008 17:06:59 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY anniehall.mr.itd.umich.edu ID 477D5C7A.4FE1F.22211 ; + BY anniehall.mr.itd.umich.edu ID 477D5C7A.4FE1F.22211 ; 3 Jan 2008 17:06:53 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 0BC8D7225E; @@ -1708,7 +1708,7 @@ Received: from icestorm.mr.itd.umich.edu (icestorm.mr.itd.umich.edu [141.211.93. by chaos.mail.umich.edu () with ESMTP id m03LYdY1029538; Thu, 3 Jan 2008 16:34:39 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY icestorm.mr.itd.umich.edu ID 477D54EA.13F34.26602 ; + BY icestorm.mr.itd.umich.edu ID 477D54EA.13F34.26602 ; 3 Jan 2008 16:34:36 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id CC710ADC79; @@ -1773,7 +1773,7 @@ Received: from galaxyquest.mr.itd.umich.edu (galaxyquest.mr.itd.umich.edu [141.2 by fan.mail.umich.edu () with ESMTP id m03LT6uw027749; Thu, 3 Jan 2008 16:29:06 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY galaxyquest.mr.itd.umich.edu ID 477D5397.E161D.20326 ; + BY galaxyquest.mr.itd.umich.edu ID 477D5397.E161D.20326 ; 3 Jan 2008 16:28:58 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id DEC65ADC79; @@ -1848,7 +1848,7 @@ Received: from salemslot.mr.itd.umich.edu (salemslot.mr.itd.umich.edu [141.211.1 by jacknife.mail.umich.edu () with ESMTP id m03LNlf0002115; Thu, 3 Jan 2008 16:23:47 -0500 Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184]) - BY salemslot.mr.itd.umich.edu ID 477D525E.1448.30389 ; + BY salemslot.mr.itd.umich.edu ID 477D525E.1448.30389 ; 3 Jan 2008 16:23:44 -0500 Received: from paploo.uhi.ac.uk (localhost [127.0.0.1]) by paploo.uhi.ac.uk (Postfix) with ESMTP id 9D005B9D06; diff --git a/encrypter-decrypter-gui.py b/encrypter-decrypter-gui.py index 75d10d37839..115565c03e6 100644 --- a/encrypter-decrypter-gui.py +++ b/encrypter-decrypter-gui.py @@ -110,26 +110,34 @@ def __init__(self, parent): self.nb.pack(expand=True, fill="both") # ----- LabelFrames ----- self.page1_main_label = ttk.LabelFrame( - self.page1, text="Encrypt Any Text" + self.page1, + text="Encrypt Any Text", ) # <----- Page1 LabelFrame1 self.page1_main_label.grid(row=0, column=0, pady=20, padx=2, ipadx=20) self.page1_output_label = ttk.LabelFrame(self.page1, text="Decrypted Text") self.page1_output_label.grid(row=1, column=0, pady=10, padx=2) self.page2_main_label = ttk.LabelFrame( - self.page2, text="Decrypt Any Text" + self.page2, + text="Decrypt Any Text", ) # <----- Page1 LabelFrame1 self.page2_main_label.grid(row=0, column=0, pady=20, padx=2, ipadx=20) self.page2_output_label = ttk.LabelFrame(self.page2, text="Real Text") self.page2_output_label.grid(row=1, column=0, pady=10, padx=2) # <---Scrolled Text Global self.decrypted_text_box = ScrolledText( - self.page1_output_label, width=30, height=5, state="normal" + self.page1_output_label, + width=30, + height=5, + state="normal", ) self.decrypted_text_box.grid(row=1, column=0, padx=2, pady=10) self.text_box = ScrolledText( - self.page2_output_label, width=30, height=5, state="normal" + self.page2_output_label, + width=30, + height=5, + state="normal", ) self.text_box.grid(row=1, column=0, padx=2, pady=10) # ----- Variables ----- @@ -145,11 +153,15 @@ def __init__(self, parent): def page1_inside(self): style = ttk.Style() user_text_label = ttk.Label( - self.page1_main_label, text="Enter Your Text Here : ", font=("", 14) + self.page1_main_label, + text="Enter Your Text Here : ", + font=("", 14), ) user_text_label.grid(row=0, column=0, pady=10) user_entry_box = ttk.Entry( - self.page1_main_label, width=35, textvariable=self.user_text + self.page1_main_label, + width=35, + textvariable=self.user_text, ) user_entry_box.grid(row=1, column=0) style.configure( @@ -173,7 +185,8 @@ def encrypt_now(self): user_text = self.user_text.get() if user_text == "": showerror( - "Nothing Found", "Please Enter Something In Entry Box To Encrypt...!" + "Nothing Found", + "Please Enter Something In Entry Box To Encrypt...!", ) return else: @@ -185,11 +198,15 @@ def encrypt_now(self): def page2_inside(self): style = ttk.Style() user_text_label = ttk.Label( - self.page2_main_label, text="Enter Decrypted Text Here : ", font=("", 14) + self.page2_main_label, + text="Enter Decrypted Text Here : ", + font=("", 14), ) user_text_label.grid(row=0, column=0, pady=10) user_entry_box = ttk.Entry( - self.page2_main_label, width=35, textvariable=self.user_text2 + self.page2_main_label, + width=35, + textvariable=self.user_text2, ) user_entry_box.grid(row=1, column=0) style.configure( @@ -212,7 +229,8 @@ def decrypt_now(self): user_text = self.user_text2.get() if user_text == "": showerror( - "Nothing Found", "Please Enter Something In Entry Box To Encrypt...!" + "Nothing Found", + "Please Enter Something In Entry Box To Encrypt...!", ) return else: @@ -224,7 +242,7 @@ def backend_work(self, todo, text_coming): if todo == "Encrypt": try: text_coming = str( - text_coming + text_coming, ) # <----- Lowering the letters as dic in lower letter for word in text_coming: for key, value in self.data_dic.items(): diff --git a/encrypter_decrypter_gui.py b/encrypter_decrypter_gui.py index 75d10d37839..115565c03e6 100644 --- a/encrypter_decrypter_gui.py +++ b/encrypter_decrypter_gui.py @@ -110,26 +110,34 @@ def __init__(self, parent): self.nb.pack(expand=True, fill="both") # ----- LabelFrames ----- self.page1_main_label = ttk.LabelFrame( - self.page1, text="Encrypt Any Text" + self.page1, + text="Encrypt Any Text", ) # <----- Page1 LabelFrame1 self.page1_main_label.grid(row=0, column=0, pady=20, padx=2, ipadx=20) self.page1_output_label = ttk.LabelFrame(self.page1, text="Decrypted Text") self.page1_output_label.grid(row=1, column=0, pady=10, padx=2) self.page2_main_label = ttk.LabelFrame( - self.page2, text="Decrypt Any Text" + self.page2, + text="Decrypt Any Text", ) # <----- Page1 LabelFrame1 self.page2_main_label.grid(row=0, column=0, pady=20, padx=2, ipadx=20) self.page2_output_label = ttk.LabelFrame(self.page2, text="Real Text") self.page2_output_label.grid(row=1, column=0, pady=10, padx=2) # <---Scrolled Text Global self.decrypted_text_box = ScrolledText( - self.page1_output_label, width=30, height=5, state="normal" + self.page1_output_label, + width=30, + height=5, + state="normal", ) self.decrypted_text_box.grid(row=1, column=0, padx=2, pady=10) self.text_box = ScrolledText( - self.page2_output_label, width=30, height=5, state="normal" + self.page2_output_label, + width=30, + height=5, + state="normal", ) self.text_box.grid(row=1, column=0, padx=2, pady=10) # ----- Variables ----- @@ -145,11 +153,15 @@ def __init__(self, parent): def page1_inside(self): style = ttk.Style() user_text_label = ttk.Label( - self.page1_main_label, text="Enter Your Text Here : ", font=("", 14) + self.page1_main_label, + text="Enter Your Text Here : ", + font=("", 14), ) user_text_label.grid(row=0, column=0, pady=10) user_entry_box = ttk.Entry( - self.page1_main_label, width=35, textvariable=self.user_text + self.page1_main_label, + width=35, + textvariable=self.user_text, ) user_entry_box.grid(row=1, column=0) style.configure( @@ -173,7 +185,8 @@ def encrypt_now(self): user_text = self.user_text.get() if user_text == "": showerror( - "Nothing Found", "Please Enter Something In Entry Box To Encrypt...!" + "Nothing Found", + "Please Enter Something In Entry Box To Encrypt...!", ) return else: @@ -185,11 +198,15 @@ def encrypt_now(self): def page2_inside(self): style = ttk.Style() user_text_label = ttk.Label( - self.page2_main_label, text="Enter Decrypted Text Here : ", font=("", 14) + self.page2_main_label, + text="Enter Decrypted Text Here : ", + font=("", 14), ) user_text_label.grid(row=0, column=0, pady=10) user_entry_box = ttk.Entry( - self.page2_main_label, width=35, textvariable=self.user_text2 + self.page2_main_label, + width=35, + textvariable=self.user_text2, ) user_entry_box.grid(row=1, column=0) style.configure( @@ -212,7 +229,8 @@ def decrypt_now(self): user_text = self.user_text2.get() if user_text == "": showerror( - "Nothing Found", "Please Enter Something In Entry Box To Encrypt...!" + "Nothing Found", + "Please Enter Something In Entry Box To Encrypt...!", ) return else: @@ -224,7 +242,7 @@ def backend_work(self, todo, text_coming): if todo == "Encrypt": try: text_coming = str( - text_coming + text_coming, ) # <----- Lowering the letters as dic in lower letter for word in text_coming: for key, value in self.data_dic.items(): diff --git a/encryptsys.py b/encryptsys.py index 45daea14fd6..cd5cd4d10a8 100644 --- a/encryptsys.py +++ b/encryptsys.py @@ -71,7 +71,7 @@ def encrypt(): fintext = str(nummoves) + "." + fintext - print("\Encrypted text : " + fintext) + print(r"\Encrypted text : " + fintext) sel = input("What would you want to do?\n\n[1] Encrypt\n[2] Decrypt\n\n> ").lower() diff --git a/env_check.py b/env_check.py index 7e7bc53e8cd..a889bd370ba 100644 --- a/env_check.py +++ b/env_check.py @@ -11,25 +11,26 @@ import os confdir = os.getenv( - "my_config" + "my_config", ) # Set the variable confdir from the OS environment variable conffile = "env_check.conf" # Set the variable conffile conffilename = os.path.join( - confdir, conffile + confdir, + conffile, ) # Set the variable conffilename by joining confdir and conffile together for env_check in open(conffilename): # Open the config file and read all the settings env_check = ( env_check.strip() ) # Set the variable as itself, but strip the extra text out - print("[{}]".format(env_check)) # Format the Output to be in Square Brackets + print(f"[{env_check}]") # Format the Output to be in Square Brackets newenv = os.getenv( - env_check + env_check, ) # Set the variable newenv to get the settings from the OS what is currently set for the settings out the configfile if newenv is None: # If it doesn't exist print(env_check, "is not set") # Print it is not set else: # Else if it does exist print( - "Current Setting for {}={}\n".format(env_check, newenv) + f"Current Setting for {env_check}={newenv}\n", ) # Print out the details diff --git a/environment.yml b/environment.yml index a290a698a558889192c9b96c18037440b2eaf939..a805a42a1e8b694cb8fce2a076ff375fd093ab7f 100644 GIT binary patch delta 11 ScmZ3pfpP5y#tk|Vj9dU6$^-iV delta 9 QcmZ3xfpN_S#tk|V02Sc_@Bjb+ diff --git a/equations.py b/equations.py index 1fc4b9159d7..464f1d58b67 100644 --- a/equations.py +++ b/equations.py @@ -25,7 +25,7 @@ b = int(input("What is value of b?")) c = int(input("What is value of c?")) - D = b ** 2 - 4 * a * c + D = b**2 - 4 * a * c if D < 0: print("No real values of x satisfies your equation.") diff --git a/facebook id hack.py b/facebook id hack.py index a7faa2bb225..da0234d47d2 100644 --- a/facebook id hack.py +++ b/facebook id hack.py @@ -1,12 +1,13 @@ # Author-Kingslayer # Email-kingslayer8509@gmail.com # you need to create a file password.txt which contains all possible passwords -import requests +import os +import sys import threading import urllib.request -import os + +import requests from bs4 import BeautifulSoup -import sys if sys.version_info[0] != 3: print( @@ -14,7 +15,7 @@ REQUIRED PYTHON 3.x use: python3 fb.py -------------------------------------- - """ + """, ) sys.exit() @@ -54,7 +55,7 @@ def function(email, passw, i): print("\n---------- Welcome To Facebook BruteForce ----------\n") -file = open("passwords.txt", "r") +file = open("passwords.txt") email = input("Enter Email/Username : ") diff --git a/facebook-autologin-bot.py b/facebook-autologin-bot.py index 261f02721d5..c619aa0b178 100644 --- a/facebook-autologin-bot.py +++ b/facebook-autologin-bot.py @@ -1,5 +1,6 @@ -import pyttsx3 import time + +import pyttsx3 from selenium import webdriver tts = pyttsx3.init() @@ -34,7 +35,7 @@ def speak(text): speak(text) text = "I can autologin to your social sites like facebook twitter github and instagram" print( - "I can autologin to your social sites like facebook twitter github and instagram" + "I can autologin to your social sites like facebook twitter github and instagram", ) speak(text) continue diff --git a/factorial_perm_comp.py b/factorial_perm_comp.py index f329eac3380..fae25a66a1c 100644 --- a/factorial_perm_comp.py +++ b/factorial_perm_comp.py @@ -39,7 +39,7 @@ def main(): while True: try: n = int(input("\n Enter Value for n ")) - print("Factorial of {} = {}".format(n, factorial(n))) + print(f"Factorial of {n} = {factorial(n)}") break except ValueError: print("Invalid Value") @@ -52,7 +52,7 @@ def main(): try: n = int(input("\n Enter Value for n ")) r = int(input("\n Enter Value for r ")) - print("Permutation of {}P{} = {}".format(n, r, permutation(n, r))) + print(f"Permutation of {n}P{r} = {permutation(n, r)}") break except ValueError: print("Invalid Value") @@ -65,7 +65,7 @@ def main(): n = int(input("\n Enter Value for n ")) r = int(input("\n Enter Value for r ")) - print("Combination of {}C{} = {}".format(n, r, combination(n, r))) + print(f"Combination of {n}C{r} = {combination(n, r)}") break except ValueError: diff --git a/fastapi.py b/fastapi.py index 37aa3aa3ce0..0f5db2e787f 100644 --- a/fastapi.py +++ b/fastapi.py @@ -1,12 +1,15 @@ -from fastapi import FastAPI -from pydantic import BaseModel from typing import Optional +from pydantic import BaseModel + +from fastapi import FastAPI + app = FastAPI() # temp database fakedb = [] + # course model to store courses class Course(BaseModel): id: int diff --git a/fibonici series.py b/fibonici series.py index 17e24228f94..85483ee8ab7 100644 --- a/fibonici series.py +++ b/fibonici series.py @@ -6,16 +6,16 @@ # check if the number of terms is valid if nterms <= 0: - print("Please enter a positive integer") + print("Please enter a positive integer") elif nterms == 1: - print("Fibonacci sequence upto",nterms,":") - print(n1) + print("Fibonacci sequence upto", nterms, ":") + print(n1) else: - print("Fibonacci sequence:") - while count < nterms: - print(n1) - nth = n1 + n2 - # update values - n1 = n2 - n2 = nth - count += 1 + print("Fibonacci sequence:") + while count < nterms: + print(n1) + nth = n1 + n2 + # update values + n1 = n2 + n2 = nth + count += 1 diff --git a/file_ext_changer.py b/file_ext_changer.py index 4d80261b052..1f27659aa7b 100644 --- a/file_ext_changer.py +++ b/file_ext_changer.py @@ -1,14 +1,15 @@ -'''' Multiple extension changer''' +"""' Multiple extension changer""" + +import hashlib +import random as rand import time from pathlib import Path as p -import random as rand -import hashlib def chxten_(files, xten): chfile = [] for file in files: - ch_file = file.split('.') + ch_file = file.split(".") ch_file = ch_file[0] chfile.append(ch_file) if len(xten) == len(chfile): @@ -22,7 +23,7 @@ def chxten_(files, xten): ch_xten = chfile[i] + xten[i] chxten.append(ch_xten) for i in range(1, (len(chfile) + 1) - len(xten)): - ch_xten = chfile[- + i] + xten[-1] + ch_xten = chfile[-+i] + xten[-1] chxten.append(ch_xten) elif len(xten) == 1: chxten = [] @@ -40,61 +41,64 @@ def chxten_(files, xten): ch_xten = chfile[i] + xten[i] chxten.append(ch_xten) else: - return 'an error occured' + return "an error occured" return chxten # End of function definitions # Beggining of execution of code -#password -password = input('Enter password:') +# password +password = input("Enter password:") password = password.encode() password = hashlib.sha512(password).hexdigest() -if password == 'c99d3d8f321ff63c2f4aaec6f96f8df740efa2dc5f98fccdbbb503627fd69a9084073574ee4df2b888f9fe2ed90e29002c318be476bb62dabf8386a607db06c4': +if ( + password + == "c99d3d8f321ff63c2f4aaec6f96f8df740efa2dc5f98fccdbbb503627fd69a9084073574ee4df2b888f9fe2ed90e29002c318be476bb62dabf8386a607db06c4" +): pass else: - print('wrong password!') + print("wrong password!") time.sleep(0.3) exit(404) -files = input('Enter file names and thier extensions (seperated by commas):') -xten = input('Enter Xtensions to change with (seperated by commas):') +files = input("Enter file names and thier extensions (seperated by commas):") +xten = input("Enter Xtensions to change with (seperated by commas):") -if files == '*': +if files == "*": pw = p.cwd() - files = '' + files = "" for i in pw.iterdir(): if not p.is_dir(i): i = str(i) - if not i.endswith('.py'): + if not i.endswith(".py"): # if not i.endswith('exe'): - if not i.endswith('.log'): - files = files + i + ',' -if files == 'r': + if not i.endswith(".log"): + files = files + i + "," +if files == "r": pw = p.cwd() - files = '' + files = "" filer = [] for i in pw.iterdir(): if p.is_file(i): i = str(i) - if not i.endswith('.py'): - if not i.endswith('.exe'): - if not i.endswith('.log'): + if not i.endswith(".py"): + if not i.endswith(".exe"): + if not i.endswith(".log"): filer.append(i) for i in range(5): - pos = rand.randint(0,len(filer)) - files = files + filer[pos] + ',' + pos = rand.randint(0, len(filer)) + files = files + filer[pos] + "," print(files) -files = files.split(',') -xten = xten.split(',') +files = files.split(",") +xten = xten.split(",") # Validation for file in files: check = p(file).exists() if check == False: - print(f'{file} is not found. Paste this file in the directory of {file}') + print(f"{file} is not found. Paste this file in the directory of {file}") files.remove(file) # Ended validation @@ -102,8 +106,8 @@ def chxten_(files, xten): chxten = chxten_(files, xten) # Error Handlings -if chxten == 'an error occured': - print('Check your inputs correctly') +if chxten == "an error occured": + print("Check your inputs correctly") time.sleep(1) exit(404) else: @@ -111,7 +115,7 @@ def chxten_(files, xten): for i in range(len(files)): f = p(files[i]) f.rename(chxten[i]) - print('All files has been changed') + print("All files has been changed") except PermissionError: pass except FileNotFoundError: @@ -119,7 +123,9 @@ def chxten_(files, xten): for file in files: check = p(file).exists() if check == False: - print(f'{file} is not found. Paste this file in the directory of {file}') + print( + f"{file} is not found. Paste this file in the directory of {file}" + ) files.remove(file) # except Exception: # print('An Error Has Occured in exception') diff --git a/fileinfo.py b/fileinfo.py index bc80dc4bc5a..5f091fc53c6 100644 --- a/fileinfo.py +++ b/fileinfo.py @@ -9,15 +9,13 @@ # get file information using os.stat() # tested with Python24 vegsaeat 25sep2006 -from __future__ import print_function import os import stat # index constants for os.stat() import sys import time -if sys.version_info >= (3, 0): - raw_input = input +raw_input = input file_name = raw_input("Enter a file name: ") # pick a file you have count = 0 @@ -33,7 +31,7 @@ print(e) sys.exit(1) # When open item is a directory (python2) -except IOError: +except OSError: pass # When open item is a directory (python3) except IsADirectoryError: @@ -45,13 +43,16 @@ "fname": file_name, "fsize": file_stats[stat.ST_SIZE], "f_lm": time.strftime( - "%d/%m/%Y %I:%M:%S %p", time.localtime(file_stats[stat.ST_MTIME]) + "%d/%m/%Y %I:%M:%S %p", + time.localtime(file_stats[stat.ST_MTIME]), ), "f_la": time.strftime( - "%d/%m/%Y %I:%M:%S %p", time.localtime(file_stats[stat.ST_ATIME]) + "%d/%m/%Y %I:%M:%S %p", + time.localtime(file_stats[stat.ST_ATIME]), ), "f_ct": time.strftime( - "%d/%m/%Y %I:%M:%S %p", time.localtime(file_stats[stat.ST_CTIME]) + "%d/%m/%Y %I:%M:%S %p", + time.localtime(file_stats[stat.ST_CTIME]), ), "no_of_lines": count, "t_char": t_char, diff --git a/find_cube_root.py b/find_cube_root.py index cf315708a25..87e9b4215b7 100644 --- a/find_cube_root.py +++ b/find_cube_root.py @@ -7,9 +7,9 @@ def cubeRoot(): x = int(input("Enter an integer: ")) for ans in range(0, abs(x) + 1): - if ans ** 3 == abs(x): + if ans**3 == abs(x): break - if ans ** 3 != abs(x): + if ans**3 != abs(x): print(x, "is not a perfect cube!") else: if x < 0: diff --git a/find_prime.py b/find_prime.py index d6d5a515bd2..2fd050abeda 100644 --- a/find_prime.py +++ b/find_prime.py @@ -9,21 +9,22 @@ -Sieve of Eratosthenes(source:wikipedia.com) In mathematics, the sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to any given limit. - It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime - number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant - difference between them that is equal to that prime. This is the sieve's key distinction from using trial division to + It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime + number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant + difference between them that is equal to that prime. This is the sieve's key distinction from using trial division to sequentially test each candidate number for divisibility by each prime. To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method: - Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n). - Initially, let p equal 2, the smallest prime number. - - Enumerate the multiples of p by counting to n from 2p in increments of p, and mark them in the list (these will be 2p, + - Enumerate the multiples of p by counting to n from 2p in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ...; the p itself should not be marked). - - Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let + - Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3. - When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n. """ + import sys diff --git a/finding LCM.py b/finding LCM.py index e95feb45b47..573ae0557d9 100644 --- a/finding LCM.py +++ b/finding LCM.py @@ -1,21 +1,22 @@ - # Python Program to find the L.C.M. of two input number + def compute_lcm(x, y): - # choose the greater number - if x > y: - greater = x - else: - greater = y + # choose the greater number + if x > y: + greater = x + else: + greater = y + + while True: + if (greater % x == 0) and (greater % y == 0): + lcm = greater + break + greater += 1 - while(True): - if((greater % x == 0) and (greater % y == 0)): - lcm = greater - break - greater += 1 + return lcm - return lcm num1 = 54 num2 = 24 diff --git a/flappyBird_pygame/flappy_bird.py b/flappyBird_pygame/flappy_bird.py index 34b3206b7e2..3b21bcb9f19 100644 --- a/flappyBird_pygame/flappy_bird.py +++ b/flappyBird_pygame/flappy_bird.py @@ -1,5 +1,4 @@ #! /usr/bin/env python3 -# -*- coding: utf-8 -*- """ Created on Fri Mar 23 14:17:24 2019 @@ -31,7 +30,7 @@ class Bird(pygame.sprite.Sprite): def __init__(self, x, y, ms_to_up, images): - super(Bird, self).__init__() + super().__init__() self.x, self.y = x, y self.ms_to_up = ms_to_up self._img_wingup, self._img_wingdown = images @@ -93,7 +92,7 @@ def __init__(self, pipe_end_img, pipe_body_img): - 3 * Bird.HEIGHT # fill window from top to bottom - 3 * PipePair.PIECE_HEIGHT # make room for bird to fit through ) - / PipePair.PIECE_HEIGHT # 2 end pieces + 1 body piece # to get number of pipe pieces + / PipePair.PIECE_HEIGHT, # 2 end pieces + 1 body piece # to get number of pipe pieces ) self.bottom_pieces = randint(1, total_pipe_body_pieces) self.top_pieces = total_pipe_body_pieces - self.bottom_pieces diff --git a/floodfill/floodfill.py b/floodfill/floodfill.py index b4c39735f23..e80898ec26e 100644 --- a/floodfill/floodfill.py +++ b/floodfill/floodfill.py @@ -26,8 +26,8 @@ def generateClosedPolygons(self): if self.window_height < 128 or self.window_width < 128: return # surface too small + from math import cos, pi, sin from random import randint, uniform - from math import pi, sin, cos for n in range(0, randint(0, 5)): x = randint(50, self.window_width - 50) @@ -40,17 +40,23 @@ def generateClosedPolygons(self): for i in range(0, randint(3, 7)): dist = randint(10, 50) vertices.append( - (int(x + cos(angle) * dist), int(y + sin(angle) * dist)) + (int(x + cos(angle) * dist), int(y + sin(angle) * dist)), ) angle += uniform(0, pi / 2) for i in range(0, len(vertices) - 1): pygame.draw.line( - self.surface, (255, 0, 0), vertices[i], vertices[i + 1] + self.surface, + (255, 0, 0), + vertices[i], + vertices[i + 1], ) pygame.draw.line( - self.surface, (255, 0, 0), vertices[len(vertices) - 1], vertices[0] + self.surface, + (255, 0, 0), + vertices[len(vertices) - 1], + vertices[0], ) def run(self): diff --git a/folder_size.py b/folder_size.py index 7410de8da36..f533b70b3f3 100755 --- a/folder_size.py +++ b/folder_size.py @@ -25,13 +25,13 @@ "Megabytes": float(1) / (1024 * 1024), "Gigabytes": float(1) / (1024 * 1024 * 1024), } -for (path, dirs, files) in os.walk( - directory +for path, dirs, files in os.walk( + directory, ): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir. for file in files: # Get all the files filename = os.path.join(path, file) dir_size += os.path.getsize( - filename + filename, ) # Add the size of each file in the root dir to get the total size. fsizeList = [ diff --git a/framework/quo.md b/framework/quo.md index b2505a7b066..cece6f2ba1f 100644 --- a/framework/quo.md +++ b/framework/quo.md @@ -17,11 +17,11 @@ **Quo** is a toolkit for writing Command-Line Interface(CLI) applications and a TUI (Text User Interface) framework for Python. Quo is making headway towards composing speedy and orderly CLI and TUI applications while forestalling any disappointments brought about by the failure to execute a python application. -Simple to code, easy to learn, and does not come with needless baggage. +Simple to code, easy to learn, and does not come with needless baggage. ## Compatibility Quo works flawlessly with Linux, OSX, and Windows. -Quo requires Python `3.8` or later. +Quo requires Python `3.8` or later. ## Features @@ -67,9 +67,9 @@ Try this: **Example 1** ```python - from quo import echo +from quo import echo - echo("Hello, World!", fg="red", italic=True, bold=True) +echo("Hello, World!", fg="red", italic=True, bold=True) ```

@@ -78,10 +78,9 @@ Try this: **Example 2** ```python - from quo import echo +from quo import echo - echo("Blue on white", fg="blue", bg="white") - +echo("Blue on white", fg="blue", bg="white") ```

@@ -92,18 +91,17 @@ Alternatively, you can import [print](https://quo.readthedocs.io/en/latest/print **Example 1** ```python - from quo import print +from quo import print - print('This is bold') - print('This is italic') +print("This is bold") +print("This is italic") ``` **Example 2** ```python - from quo import print +from quo import print - print('This is underlined') - +print("This is underlined") ```

@@ -111,20 +109,19 @@ Alternatively, you can import [print](https://quo.readthedocs.io/en/latest/print **Example 3** ```python - from quo import print +from quo import print - print("Quo is ") +print("Quo is ") ```

**Example 4** -```python - # Colors from the ANSI palette. - print('This is red') - print('!') +def toolbar(): + return Text('This is a !') - # Returns a callable - session = Prompt(bottom_toolbar=toolbar) - session.prompt('> ') +# Returns a callable +session = Prompt(bottom_toolbar=toolbar) +session.prompt("> ") ``` ![validate](https://raw.githubusercontent.com/scalabli/quo/master/docs/images/bottom-toolbar.png) @@ -199,12 +194,11 @@ A placeholder text that's displayed as long as no input s given. :bulb: This won't be returned as part of the output. ```python +from quo.prompt import Prompt +from quo.text import Text - from quo.prompt import Prompt - from quo.text import Text - - session = Prompt(placeholder=Text('(please type something)')) - session.prompt("What is your name?: ") +session = Prompt(placeholder=Text("(please type something)")) +session.prompt("What is your name?: ") ```

@@ -216,14 +210,12 @@ A placeholder text that's displayed as long as no input s given. ```python +from quo.color import Color +from quo.prompt import Prompt - from quo.color import Color - from quo.prompt import Prompt - - style = Color("fg:red") - session = Prompt(style=style) - session.prompt("Type something: ") - +style = Color("fg:red") +session = Prompt(style=style) +session.prompt("Type something: ") ```

@@ -236,12 +228,12 @@ A placeholder text that's displayed as long as no input s given. Press [Tab] to autocomplete ```python +from quo.prompt import Prompt +from quo.completion import WordCompleter - from quo.prompt import Prompt - from quo.completion import WordCompleter - example = WordCompleter(['USA', 'UK', 'Canada', 'Kenya']) - session = Prompt(completer=example) - session.prompt('Which country are you from?: ') +example = WordCompleter(["USA", "UK", "Canada", "Kenya"]) +session = Prompt(completer=example) +session.prompt("Which country are you from?: ") ``` ![Autocompletion](https://github.com/scalabli/quo/raw/master/docs/images/autocompletion.png) @@ -252,19 +244,18 @@ Press [Tab] to autocomplete Auto suggestion is a way to propose some input completions to the user. Usually, the input is compared to the history and when there is another entry starting with the given text, the completion will be shown as gray text behind the current input. Pressing the right arrow → or ctrl-e will insert this suggestion, alt-f will insert the first word of the suggestion. ```python +from quo.history import MemoryHistory +from quo.prompt import Prompt - from quo.history import MemoryHistory - from quo.prompt import Prompt - - MemoryHistory.append("import os") - MemoryHistory.append('print("hello")') - MemoryHistory.append('print("world")') - MemoryHistory.append("import path") +MemoryHistory.append("import os") +MemoryHistory.append('print("hello")') +MemoryHistory.append('print("world")') +MemoryHistory.append("import path") - session = Prompt(history=MemoryHistory, suggest="history") +session = Prompt(history=MemoryHistory, suggest="history") - while True: - session.prompt('> ') +while True: + session.prompt("> ") ``` @@ -280,12 +271,10 @@ For more control over quo terminal content, import and construct a `Console` obj Draw a horizontal bar with an optional title, which is a good way of dividing your terminal output in to sections. ```python +from quo.console import Console - from quo.console import Console - - console = Console() - console.bar("I am a bar") - +console = Console() +console.bar("I am a bar") ```

@@ -300,23 +289,19 @@ Quo supports launching applications through `Console.launch` **Example 1** ```python +from quo.console import Console - from quo.console import Console - - console = Console() - console.launch("https://quo.rtfd.io/") - +console = Console() +console.launch("https://quo.rtfd.io/") ``` **Example 2** ```python +from quo.console import Console - from quo.console import Console - - console = Console() - console.launch("/home/path/README.md", locate=True) - +console = Console() +console.launch("/home/path/README.md", locate=True) ``` ``Rule`` @@ -326,12 +311,10 @@ Used for drawing a horizontal line. **Example 1** ```python +from quo.console import Console - from quo.console import Console - - console = Console() - console.rule() - +console = Console() +console.rule() ```

@@ -342,12 +325,10 @@ Used for drawing a horizontal line. A multicolored line. ```python +from quo.console import Console - from quo.console import Console - - console = Console() - console.rule(multicolored=True) - +console = Console() +console.rule(multicolored=True) ```

@@ -361,16 +342,14 @@ A multicolored line. Quo can create a context manager that is used to display a spinner on stdout as long as the context has not exited ```python +import time +from quo.console import Console - import time - from quo.console import Console - - console = Console() - - with console.spin(): - time.sleep(3) - print("Hello, World") +console = Console() +with console.spin(): + time.sleep(3) + print("Hello, World") ``` Read more on [Console](https://quo.readthedocs.io/en/latest/console.html) @@ -382,14 +361,11 @@ High level API for displaying dialog boxes to the user for informational purpose Message Box dialog ```python +from quo.dialog import MessageBox - from quo.dialog import MessageBox - - MessageBox( - title="Message pop up window", - text="Do you want to continue?\nPress ENTER to quit." - ) - +MessageBox( + title="Message pop up window", text="Do you want to continue?\nPress ENTER to quit." +) ``` ![Message Box](https://github.com/scalabli/quo/raw/master/docs/images/messagebox.png) @@ -398,14 +374,9 @@ Message Box dialog Input Box dialog ```python +from quo.dialog import InputBox - from quo.dialog import InputBox - - InputBox( - title="InputBox shenanigans", - text="What Country are you from? :" - ) - +InputBox(title="InputBox shenanigans", text="What Country are you from? :") ``` ![Prompt Box](https://github.com/scalabli/quo/raw/master/docs/images/promptbox.png) @@ -417,47 +388,46 @@ Read more on [Dialogs](https://quo.readthedocs.io/en/latest/dialogs.html) A key binding is an association between a physical key on akeyboard and a parameter. ```python +from quo import echo +from quo.keys import bind +from quo.prompt import Prompt - from quo import echo - from quo.keys import bind - from quo.prompt import Prompt +session = Prompt() - session = Prompt() - # Print "Hello world" when ctrl-h is pressed - @bind.add("ctrl-h") - def _(event): - echo("Hello, World!") +# Print "Hello world" when ctrl-h is pressed +@bind.add("ctrl-h") +def _(event): + echo("Hello, World!") - session.prompt("") +session.prompt("") ``` Read more on [Key bindings](https://quo.readthedocs.io/en/latest/kb.html) -## Quo Parser +## Quo Parser You can parse optional and positional arguments with Quo and generate help pages for your command-line tools. ```python - from quo.parse import Parser - - parser = Parser(description= "This script prints hello NAME COUNT times.") +from quo.parse import Parser + +parser = Parser(description="This script prints hello NAME COUNT times.") - parser.argument('--count', default=3, type=int, help='number of greetings') - parser.argument('name', help="The person to greet") - - arg = parser.parse() - - for x in range(arg.count): - print(f"Hello {arg.name}!") +parser.argument("--count", default=3, type=int, help="number of greetings") +parser.argument("name", help="The person to greet") +arg = parser.parse() + +for x in range(arg.count): + print(f"Hello {arg.name}!") ``` ```shell $ python prog.py John --count 4 - + ``` And what it looks like: @@ -482,13 +452,12 @@ Creating a new progress bar can be done by calling the class **ProgressBar** The progress can be displayed for any iterable. This works by wrapping the iterable (like ``range``) with the class **ProgressBar** ```python +import time +from quo.progress import ProgressBar - import time - from quo.progress import ProgressBar - - with ProgressBar() as pb: - for i in pb(range(800)): - time.sleep(.01) +with ProgressBar() as pb: + for i in pb(range(800)): + time.sleep(0.01) ``` ![ProgressBar](https://raw.githubusercontent.com/scalabli/quo/master/docs/images/simple-progress-bar.png) @@ -503,18 +472,16 @@ This offers a number of configuration options to set the look and feel of the ta **Example 1** ```python +from quo.table import Table - from quo.table import Table - - data = [ - ["Name", "Gender", "Age"], - ["Alice", "F", 24], - ["Bob", "M", 19], - ["Dave", "M", 24] - ] - - Table(data) +data = [ + ["Name", "Gender", "Age"], + ["Alice", "F", 24], + ["Bob", "M", 19], + ["Dave", "M", 24], +] +Table(data) ``` ![tabulate](https://raw.githubusercontent.com/scalabli/quo/master/docs/images/tables/table.png) @@ -523,17 +490,15 @@ This offers a number of configuration options to set the look and feel of the ta Right aligned table ```python +from quo.table import Table - from quo.table import Table - - data = [ +data = [ ["Name", "Gender", "Age"], ["Alice", "F", 24], ["Bob", "M", 19], - ["Dave", "M", 24] - ] - Table(data, align="right") - + ["Dave", "M", 24], +] +Table(data, align="right") ``` ![tabulate](https://raw.githubusercontent.com/scalabli/quo/master/docs/images/tables/right-table.png) @@ -543,18 +508,16 @@ Right aligned table Colored table ```python +from quo.table import Table - from quo.table import Table - - data = [ +data = [ ["Name", "Gender", "Age"], ["Alice", "F", 24], ["Bob", "M", 19], - ["Dave", "M", 24] - ] - - Table(data, style="fg:green") + ["Dave", "M", 24], +] +Table(data, style="fg:green") ``` @@ -565,18 +528,16 @@ Colored table Grid table ```python +from quo.table import Table - from quo.table import Table - - data = [ +data = [ ["Name", "Gender", "Age"], ["Alice", "F", 24], ["Bob", "M", 19], - ["Dave", "M", 24] - ] - - Table(data, theme="grid") + ["Dave", "M", 24], +] +Table(data, theme="grid") ``` @@ -595,17 +556,13 @@ A collection of reusable components for building full screen applications. Draw a border around any container, optionally with a title. ```python +from quo import container +from quo.widget import Frame, Label - from quo import container - from quo.widget import Frame, Label - - content = Frame( - Label("Hello, World!"), - title="Quo: python") - - #Press Ctrl-C to exit - container(content, bind=True, full_screen=True) +content = Frame(Label("Hello, World!"), title="Quo: python") +# Press Ctrl-C to exit +container(content, bind=True, full_screen=True) ``` ![Frame](https://raw.githubusercontent.com/scalabli/quo/master/docs/images/widgets/frame.png) @@ -618,49 +575,45 @@ Widget that displays the given text. It is not editable or focusable. This will occupy a minimum space in your terminal ```python +from quo import container +from quo.widget import Label - from quo import container - from quo.widget import Label - - content = Label("Hello, World", style="fg:black bg:red") - - container(content) +content = Label("Hello, World", style="fg:black bg:red") +container(content) ``` **Example 2** This will be a fullscreen application ```python +from quo import container +from quo.widget import Label - from quo import container - from quo.widget import Label - - content = Label("Hello, World", style="fg:black bg:red") - - # Press Ctrl-C to exit - container(content, bind=True, full_screen=True) +content = Label("Hello, World", style="fg:black bg:red") +# Press Ctrl-C to exit +container(content, bind=True, full_screen=True) ``` **Example 3** Full screen application using a custom binding key. ```python +from quo import container +from quo.keys import bind +from quo.widget import Label - from quo import container - from quo.keys import bind - from quo.widget import Label +content = Label("Hello, World", style="fg:black bg:red") - content = Label("Hello, World", style="fg:black bg:red") - #Press Ctrl-Z to exit - @bind.add("ctrl-z") - def _(event): - event.app.exit() +# Press Ctrl-Z to exit +@bind.add("ctrl-z") +def _(event): + event.app.exit() - container(content, bind=True, full_screen=True) +container(content, bind=True, full_screen=True) ``` Read more on [Widgets](https://quo.readthedocs.io/en/latest/widgets.html) @@ -696,7 +649,7 @@ For discussions about the usage, development, and the future of quo, please join ### Bug tracker If you have any suggestions, bug reports, or annoyances please report them -to our issue tracker at +to our issue tracker at [Bug tracker](https://github.com/scalabli/quo/issues/) or send an email to: 📥 scalabli@googlegroups.com | scalabli@proton.me @@ -710,7 +663,7 @@ to our issue tracker at ## License📑 -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) This software is licensed under the `MIT License`. See the [License](https://github.com/scalabli/quo/blob/master/LICENSE) file in the top distribution directory for the full license text. @@ -718,4 +671,3 @@ This software is licensed under the `MIT License`. See the [License](https://git Code of Conduct is adapted from the Contributor Covenant, version 1.2.0 available at [Code of Conduct](http://contributor-covenant.org/version/1/2/0/) - diff --git a/friday.py b/friday.py index 544a1d7516d..4c0b4f3b5af 100644 --- a/friday.py +++ b/friday.py @@ -1,6 +1,7 @@ -import pyttsx3 import os +import pyttsx3 + var = 1 while var > 0: diff --git a/ftp_send_receive.py b/ftp_send_receive.py index 691e0e8e899..d2f1137df66 100644 --- a/ftp_send_receive.py +++ b/ftp_send_receive.py @@ -4,7 +4,7 @@ Note: Do not use root username & password for security reasons Create a seperate user and provide access to a home directory of the user - Use login id and password of the user created + Use login id and password of the user created cwd here stands for current working directory """ diff --git a/game_of_life/05_mixed_sorting.py b/game_of_life/05_mixed_sorting.py index ef0dced3325..86caf1eaaea 100644 --- a/game_of_life/05_mixed_sorting.py +++ b/game_of_life/05_mixed_sorting.py @@ -15,8 +15,8 @@ [4, 13, 11, 8, -5, 90] Explanation -The even numbers are sorted in increasing order, the odd numbers are sorted in -decreasing number, and the relative positions were +The even numbers are sorted in increasing order, the odd numbers are sorted in +decreasing number, and the relative positions were [even, odd, odd, even, odd, even] and remain the same after sorting. """ diff --git a/game_of_life/game_o_life.py b/game_of_life/game_o_life.py index 7d2ee832dcf..50f1322bd5a 100644 --- a/game_of_life/game_o_life.py +++ b/game_of_life/game_o_life.py @@ -1,4 +1,4 @@ -"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) +"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Requirements: - numpy @@ -13,7 +13,7 @@ - $python3 game_o_life Game-Of-Life Rules: - + 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. @@ -27,11 +27,11 @@ Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ + import random import sys import numpy as np - from matplotlib import use as mpluse mpluse("TkAgg") @@ -71,7 +71,8 @@ def run(canvas): for c, pt in enumerate(row): # print(r-1,r+2,c-1,c+2) next_gen_canvas[r][c] = __judge_point( - pt, canvas[r - 1 : r + 2, c - 1 : c + 2] + pt, + canvas[r - 1 : r + 2, c - 1 : c + 2], ) canvas = next_gen_canvas diff --git a/gcd.py b/gcd.py index 0f10da082d7..f51571ba8d0 100644 --- a/gcd.py +++ b/gcd.py @@ -2,6 +2,7 @@ although there is function to find gcd in python but this is the code which takes two inputs and prints gcd of the two. """ + a = int(input("Enter number 1 (a): ")) b = int(input("Enter number 2 (b): ")) @@ -11,4 +12,4 @@ gcd = i i = i + 1 -print("\nGCD of {0} and {1} = {2}".format(a, b, gcd)) +print(f"\nGCD of {a} and {b} = {gcd}") diff --git a/generate_permutations.py b/generate_permutations.py index 4623e08d2c3..26d473d1d32 100644 --- a/generate_permutations.py +++ b/generate_permutations.py @@ -1,16 +1,17 @@ -def generate(A,k): - if k ==1: +def generate(A, k): + if k == 1: print(A) return else: for i in range(k): - generate(A,k-1) - if(i80): + sentence = sentence + line.text + ratio = fuzz.token_set_ratio(sentence, checkString) + if ratio > 80: singleLink.append(k) singleRatio.append(ratio) - if(len(singleLink)>=4): - singleLink=np.array(singleLink) - singleRatio=np.array(singleRatio) - inds=singleRatio.argsort() - sortedLink=singleLink[inds] - sortedFinalList=list(sortedLink[::-1]) - sortedFinalList=sortedFinalList[:4] - FinalResult.append(singleWrite+sortedFinalList) - elif(len(singleLink)<4) and len(singleLink)>0: + if len(singleLink) >= 4: singleLink = np.array(singleLink) singleRatio = np.array(singleRatio) inds = singleRatio.argsort() sortedLink = singleLink[inds] sortedFinalList = list(sortedLink[::-1]) - sortedFinalList=sortedFinalList+(4-len(sortedFinalList))*[[" "]] + sortedFinalList = sortedFinalList[:4] + FinalResult.append(singleWrite + sortedFinalList) + elif (len(singleLink) < 4) and len(singleLink) > 0: + singleLink = np.array(singleLink) + singleRatio = np.array(singleRatio) + inds = singleRatio.argsort() + sortedLink = singleLink[inds] + sortedFinalList = list(sortedLink[::-1]) + sortedFinalList = sortedFinalList + (4 - len(sortedFinalList)) * [[" "]] FinalResult.append(singleWrite + sortedFinalList) else: - sortedFinalList=[[" "]]*4 - FinalResult.append(singleWrite+sortedFinalList) + sortedFinalList = [[" "]] * 4 + FinalResult.append(singleWrite + sortedFinalList) SearchResults() -FinalResult=np.array(FinalResult) -FinalResult=pd.DataFrame(FinalResult) -FinalResult.columns=["Input","Link A","Link B","Link C","Link D"] -FinalResult.replace(" ",np.nan) -FinalResult.to_csv("Susma.csv",index=False) +FinalResult = np.array(FinalResult) +FinalResult = pd.DataFrame(FinalResult) +FinalResult.columns = ["Input", "Link A", "Link B", "Link C", "Link D"] +FinalResult.replace(" ", np.nan) +FinalResult.to_csv("Susma.csv", index=False) print(FinalResult) diff --git a/greaterno.py b/greaterno.py index a4fb15c1231..d636d48e307 100644 --- a/greaterno.py +++ b/greaterno.py @@ -7,15 +7,15 @@ num3 = 12 # uncomment following lines to take three numbers from user -#num1 = float(input("Enter first number: ")) -#num2 = float(input("Enter second number: ")) -#num3 = float(input("Enter third number: ")) +# num1 = float(input("Enter first number: ")) +# num2 = float(input("Enter second number: ")) +# num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): - largest = num1 + largest = num1 elif (num2 >= num1) and (num2 >= num3): - largest = num2 + largest = num2 else: - largest = num3 + largest = num3 print("The largest number is", largest) diff --git a/gstin_scraper.py b/gstin_scraper.py index 4f55ca6de30..e25596308c4 100644 --- a/gstin_scraper.py +++ b/gstin_scraper.py @@ -1,7 +1,8 @@ -from bs4 import BeautifulSoup -import requests import time +import requests +from bs4 import BeautifulSoup + # Script Name : gstin_scraper.py # Author : Purshotam # Created : Sep 6, 2021 7:59 PM @@ -9,36 +10,47 @@ # Version : 1.0 # Modifications : """ Description : -GSTIN, short for Goods and Services Tax Identification Number, -is a unique 15 digit identification number assigned to every taxpayer +GSTIN, short for Goods and Services Tax Identification Number, +is a unique 15 digit identification number assigned to every taxpayer (primarily dealer or supplier or any business entity) registered under the GST regime. This script is able to fetch GSTIN numbers for any company registered in the Mumbai / Banglore region. """ -# Using a demo list in case of testing the script. +# Using a demo list in case of testing the script. # This list will be used in case user skips "company input" dialogue by pressing enter. -demo_companies = ["Bank of Baroda", "Trident Limited", "Reliance Limited", "The Yummy Treat", "Yes Bank", "Mumbai Mineral Trading Corporation"] +demo_companies = [ + "Bank of Baroda", + "Trident Limited", + "Reliance Limited", + "The Yummy Treat", + "Yes Bank", + "Mumbai Mineral Trading Corporation", +] + def get_company_list(): company_list = [] - + while True: company = input("Enter a company name (or press Enter to finish): ") if not company: break company_list.append(company) - + return company_list + def fetch_gstins(company_name, csrf_token): - third_party_gstin_site = "https://www.knowyourgst.com/gst-number-search/by-name-pan/" - payload = {'gstnum': company_name, 'csrfmiddlewaretoken': csrf_token} + third_party_gstin_site = ( + "https://www.knowyourgst.com/gst-number-search/by-name-pan/" + ) + payload = {"gstnum": company_name, "csrfmiddlewaretoken": csrf_token} # Getting the HTML content and extracting the GSTIN content using BeautifulSoup. html_content = requests.post(third_party_gstin_site, data=payload) - soup = BeautifulSoup(html_content.text, 'html.parser') + soup = BeautifulSoup(html_content.text, "html.parser") site_results = soup.find_all(id="searchresult") # Extracting GSTIN specific values from child elements. @@ -46,23 +58,28 @@ def fetch_gstins(company_name, csrf_token): return gstins + def main(): temp = get_company_list() companies = temp if temp else demo_companies all_gstin_data = "" - third_party_gstin_site = "https://www.knowyourgst.com/gst-number-search/by-name-pan/" + third_party_gstin_site = ( + "https://www.knowyourgst.com/gst-number-search/by-name-pan/" + ) # Getting the CSRF value for further RESTful calls. page_with_csrf = requests.get(third_party_gstin_site) - soup = BeautifulSoup(page_with_csrf.text, 'html.parser') - csrf_token = soup.find('input', {"name": "csrfmiddlewaretoken"})['value'] + soup = BeautifulSoup(page_with_csrf.text, "html.parser") + csrf_token = soup.find("input", {"name": "csrfmiddlewaretoken"})["value"] for company in companies: gstins = fetch_gstins(company, csrf_token) # Only include GSTINs for Bengaluru and Mumbai-based companies - comma_separated_gstins = ', '.join([g for g in gstins if g.startswith(('27', '29'))]) + comma_separated_gstins = ", ".join( + [g for g in gstins if g.startswith(("27", "29"))] + ) all_gstin_data += f"{company} = {comma_separated_gstins}\n\n" @@ -72,5 +89,6 @@ def main(): # Printing the data print(all_gstin_data) + if __name__ == "__main__": main() diff --git a/gui_calculator.py b/gui_calculator.py index 435b38972d1..636e96f6a8c 100644 --- a/gui_calculator.py +++ b/gui_calculator.py @@ -6,6 +6,7 @@ w.title("Calculatorax") w.configure(bg="#03befc") + # Functions(Keypad) def calc1(): b = txt1.get() @@ -145,7 +146,11 @@ def divide(): # Labels lbl1 = Label( - w, text="Calculatorax", font=("Times New Roman", 35), fg="#232226", bg="#fc9d03" + w, + text="Calculatorax", + font=("Times New Roman", 35), + fg="#232226", + bg="#fc9d03", ) # Entryboxes @@ -186,10 +191,18 @@ def divide(): bg="#e876e6", ) btn_subtract = Button( - w, text="-", font=("Unispace", 26), command=subtract, bg="#3954ed" + w, + text="-", + font=("Unispace", 26), + command=subtract, + bg="#3954ed", ) btn_multiplication = Button( - w, text="x", font=("Unispace", 26), command=multiply, bg="#3954ed" + w, + text="x", + font=("Unispace", 26), + command=multiply, + bg="#3954ed", ) btn_division = Button(w, text="÷", font=("Unispace", 26), command=divide, bg="#3954ed") diff --git a/happy_num.py b/happy_num.py index a9740d0703b..c337a79e371 100644 --- a/happy_num.py +++ b/happy_num.py @@ -1,45 +1,44 @@ -#Way2 1: - -#isHappyNumber() will determine whether a number is happy or not -def isHappyNumber(num): - rem = sum = 0; - - #Calculates the sum of squares of digits - while(num > 0): - rem = num%10; - sum = sum + (rem*rem); - num = num//10; - return sum; - -num = 82; -result = num; - -while(result != 1 and result != 4): - result = isHappyNumber(result); - -#Happy number always ends with 1 -if(result == 1): - print(str(num) + " is a happy number after apply way 1"); -#Unhappy number ends in a cycle of repeating numbers which contain 4 -elif(result == 4): - print(str(num) + " is not a happy number after apply way 1"); - - - - - -#way 2: - -#Another way to do this and code is also less -n=num -setData=set() #set datastructure for checking a number is repeated or not. +# Way2 1: + + +# isHappyNumber() will determine whether a number is happy or not +def isHappyNumber(num): + rem = sum = 0 + + # Calculates the sum of squares of digits + while num > 0: + rem = num % 10 + sum = sum + (rem * rem) + num = num // 10 + return sum + + +num = 82 +result = num + +while result != 1 and result != 4: + result = isHappyNumber(result) + +# Happy number always ends with 1 +if result == 1: + print(str(num) + " is a happy number after apply way 1") +# Unhappy number ends in a cycle of repeating numbers which contain 4 +elif result == 4: + print(str(num) + " is not a happy number after apply way 1") + + +# way 2: + +# Another way to do this and code is also less +n = num +setData = set() # set datastructure for checking a number is repeated or not. while 1: - if n==1: - print("{} is a happy number after apply way 2".format(num)) - break - if n in setData: - print("{} is Not a happy number after apply way 2".format(num)) - break - else: - setData.add(n) #adding into set if not inside set - n=int(''.join(str(sum([int(i)**2 for i in str(n)])))) #Pythonic way + if n == 1: + print(f"{num} is a happy number after apply way 2") + break + if n in setData: + print(f"{num} is Not a happy number after apply way 2") + break + else: + setData.add(n) # adding into set if not inside set + n = int("".join(str(sum([int(i) ** 2 for i in str(n)])))) # Pythonic way diff --git a/helloworld.py b/helloworld.py index aa58112bf57..e11e39265bf 100644 --- a/helloworld.py +++ b/helloworld.py @@ -18,7 +18,7 @@ print("A Quick Tip!") time.sleep(1) print( - "make sure to use the same type of quotes(quotation marks or apostrophes)at the end that you used at the start" + "make sure to use the same type of quotes(quotation marks or apostrophes)at the end that you used at the start", ) # in c -> printf("Hello World!"); diff --git a/housing.names b/housing.names index 16064561f77..7a9a4625d5c 100644 --- a/housing.names +++ b/housing.names @@ -3,17 +3,17 @@ 2. Sources: (a) Origin: This dataset was taken from the StatLib library which is maintained at Carnegie Mellon University. - (b) Creator: Harrison, D. and Rubinfeld, D.L. 'Hedonic prices and the + (b) Creator: Harrison, D. and Rubinfeld, D.L. 'Hedonic prices and the demand for clean air', J. Environ. Economics & Management, vol.5, 81-102, 1978. (c) Date: July 7, 1993 3. Past Usage: - - Used in Belsley, Kuh & Welsch, 'Regression diagnostics ...', Wiley, + - Used in Belsley, Kuh & Welsch, 'Regression diagnostics ...', Wiley, 1980. N.B. Various transformations are used in the table on pages 244-261. - Quinlan,R. (1993). Combining Instance-Based and Model-Based Learning. - In Proceedings on the Tenth International Conference of Machine + In Proceedings on the Tenth International Conference of Machine Learning, 236-243, University of Massachusetts, Amherst. Morgan Kaufmann. @@ -29,10 +29,10 @@ 7. Attribute Information: 1. CRIM per capita crime rate by town - 2. ZN proportion of residential land zoned for lots over + 2. ZN proportion of residential land zoned for lots over 25,000 sq.ft. 3. INDUS proportion of non-retail business acres per town - 4. CHAS Charles River dummy variable (= 1 if tract bounds + 4. CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) 5. NOX nitric oxides concentration (parts per 10 million) 6. RM average number of rooms per dwelling @@ -41,12 +41,9 @@ 9. RAD index of accessibility to radial highways 10. TAX full-value property-tax rate per $10,000 11. PTRATIO pupil-teacher ratio by town - 12. B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks + 12. B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town 13. LSTAT % lower status of the population 14. MEDV Median value of owner-occupied homes in $1000's 8. Missing Attribute Values: None. - - - diff --git a/how to add three numbers and find type in python.py b/how to add three numbers and find type in python.py index bc8ba8cd6d4..dbe4e228d3e 100644 --- a/how to add three numbers and find type in python.py +++ b/how to add three numbers and find type in python.py @@ -1,8 +1,8 @@ -#python program for adding three no. -x=45 -y=75 -z=25 -t=x+y+z +# python program for adding three no. +x = 45 +y = 75 +z = 25 +t = x + y + z print(t) -#type of output +# type of output print(type(t)) diff --git a/how to display the fibonacci sequence up to n-.py b/how to display the fibonacci sequence up to n-.py index 9f6b1b3d7ce..d6a70a574cd 100644 --- a/how to display the fibonacci sequence up to n-.py +++ b/how to display the fibonacci sequence up to n-.py @@ -8,16 +8,16 @@ # check if the number of terms is valid if nterms <= 0: - print("Please enter a positive integer") + print("Please enter a positive integer") elif nterms == 1: - print("Fibonacci sequence upto",nterms,":") - print(n1) + print("Fibonacci sequence upto", nterms, ":") + print(n1) else: - print("Fibonacci sequence:") - while count < nterms: - print(n1) - nth = n1 + n2 - # update values - n1 = n2 - n2 = nth - count += 1 + print("Fibonacci sequence:") + while count < nterms: + print(n1) + nth = n1 + n2 + # update values + n1 = n2 + n2 = nth + count += 1 diff --git a/image2pdf/image2pdf.py b/image2pdf/image2pdf.py index 2c6d4bda27b..e3d461f346e 100644 --- a/image2pdf/image2pdf.py +++ b/image2pdf/image2pdf.py @@ -1,18 +1,18 @@ -from PIL import Image import os +from PIL import Image + class image2pdf: def __init__(self): self.validFormats = (".jpg", ".jpeg", ".png", ".JPG", ".PNG") self.pictures = [] - - self.directory = "" - self.isMergePDF = True + self.directory = "" + self.isMergePDF = True def getUserDir(self): - """ Allow user to choose image directory """ + """Allow user to choose image directory""" msg = "\n1. Current directory\n2. Custom directory\nEnter a number: " user_option = int(input(msg)) @@ -21,8 +21,10 @@ def getUserDir(self): while user_option <= 0 or user_option >= 3: user_option = int(input(f"\n*Invalid input*\n{msg}")) - self.directory = os.getcwd() if user_option == 1 else input("\nEnter custom directory: ") - + self.directory = ( + os.getcwd() if user_option == 1 else input("\nEnter custom directory: ") + ) + def filter(self, item): return item.endswith(self.validFormats) @@ -35,60 +37,71 @@ def getPictures(self): if not pictures: print(f" [Error] there are no pictures in the directory: {self.directory} ") return False - + print(f"Found picture(s) :") return pictures def selectPictures(self, pictures): - """ Allow user to manually pick each picture or merge all """ + """Allow user to manually pick each picture or merge all""" listedPictures = {} for index, pic in enumerate(pictures): - listedPictures[index+1] = pic + listedPictures[index + 1] = pic print(f"{index+1}: {pic}") - - userInput = input("\n Enter the number(s) - (comma seperated/no spaces) or (A or a) to merge All \nChoice: ").strip().lower() - + + userInput = ( + input( + "\n Enter the number(s) - (comma seperated/no spaces) or (A or a) to merge All \nChoice: " + ) + .strip() + .lower() + ) + if userInput != "a": # Convert user input (number) into corresponding (image title) pictures = ( - listedPictures.get(int(number)) for number in userInput.split(',') + listedPictures.get(int(number)) for number in userInput.split(",") ) self.isMergePDF = False return pictures - def convertPictures(self): """ - Convert pictures according the following: - * If pictures = 0 -> Skip - * If pictures = 1 -> use all - * Else -> allow user to pick pictures + Convert pictures according the following: + * If pictures = 0 -> Skip + * If pictures = 1 -> use all + * Else -> allow user to pick pictures - Then determine to merge all or one pdf + Then determine to merge all or one pdf """ pictures = self.getPictures() totalPictures = len(pictures) if pictures else 0 - + if totalPictures == 0: return - + elif totalPictures >= 2: pictures = self.selectPictures(pictures) - + if self.isMergePDF: - # All pics in one pdf. + # All pics in one pdf. for picture in pictures: - self.pictures.append(Image.open(f"{self.directory}\\{picture}").convert("RGB")) + self.pictures.append( + Image.open(f"{self.directory}\\{picture}").convert("RGB") + ) self.save() else: - # Each pic in seperate pdf. + # Each pic in seperate pdf. for picture in pictures: - self.save(Image.open(f"{self.directory}\\{picture}").convert("RGB"), picture, False) + self.save( + Image.open(f"{self.directory}\\{picture}").convert("RGB"), + picture, + False, + ) # Reset to default value for next run self.isMergePDF = True @@ -102,17 +115,17 @@ def save(self, image=None, title="All-PDFs", isMergeAll=True): if isMergeAll: self.pictures[0].save( - f"{self.directory}\\{title}.pdf", - save_all=True, - append_images=self.pictures[1:] + f"{self.directory}\\{title}.pdf", + save_all=True, + append_images=self.pictures[1:], ) - + else: image.save(f"{self.directory}\\{title}.pdf") if __name__ == "__main__": - + # Get user directory only once process = image2pdf() process.getUserDir() @@ -120,7 +133,9 @@ def save(self, image=None, title="All-PDFs", isMergeAll=True): # Allow user to rerun any process while True: - user = input("Press (R or r) to Run again\nPress (C or c) to change directory\nPress (Any Key) To Exit\nchoice:").lower() + user = input( + "Press (R or r) to Run again\nPress (C or c) to change directory\nPress (Any Key) To Exit\nchoice:" + ).lower() match user: case "r": process.convertPictures() @@ -129,5 +144,3 @@ def save(self, image=None, title="All-PDFs", isMergeAll=True): process.convertPictures() case _: break - - diff --git a/index.html b/index.html index 8b137891791..e69de29bb2d 100644 --- a/index.html +++ b/index.html @@ -1 +0,0 @@ - diff --git a/inheritance_YahV1729.python b/inheritance_YahV1729.python index 3f55dfab1b3..3425d124a3c 100644 --- a/inheritance_YahV1729.python +++ b/inheritance_YahV1729.python @@ -1,35 +1,35 @@ -# A Python program to demonstrate inheritance - -# Base or Super class. Note object in bracket. -# (Generally, object is made ancestor of all classes) -# In Python 3.x "class Person" is -# equivalent to "class Person(object)" -class Person(object): - - # Constructor - def __init__(self, name): - self.name = name - - # To get name - def getName(self): - return self.name - - # To check if this person is employee - def isEmployee(self): +# A Python program to demonstrate inheritance + +# Base or Super class. Note object in bracket. +# (Generally, object is made ancestor of all classes) +# In Python 3.x "class Person" is +# equivalent to "class Person(object)" +class Person(object): + + # Constructor + def __init__(self, name): + self.name = name + + # To get name + def getName(self): + return self.name + + # To check if this person is employee + def isEmployee(self): return False -# Inherited or Sub class (Note Person in bracket) -class Employee(Person): +# Inherited or Sub class (Note Person in bracket) +class Employee(Person): - # Here we return true - def isEmployee(self): + # Here we return true + def isEmployee(self): return True -# Driver code -emp = Person("Geek1") # An Object of Person -print(emp.getName(), emp.isEmployee()) +# Driver code +emp = Person("Geek1") # An Object of Person +print(emp.getName(), emp.isEmployee()) -emp = Employee("Geek2") # An Object of Employee -print(emp.getName(), emp.isEmployee()) +emp = Employee("Geek2") # An Object of Employee +print(emp.getName(), emp.isEmployee()) diff --git a/insta_image_saving/instagram_image_scrapping.ipynb b/insta_image_saving/instagram_image_scrapping.ipynb index fdb8efbf160..4fba30a8954 100644 --- a/insta_image_saving/instagram_image_scrapping.ipynb +++ b/insta_image_saving/instagram_image_scrapping.ipynb @@ -6,16 +6,17 @@ "metadata": {}, "outputs": [], "source": [ + "import os\n", + "from io import BytesIO\n", "from time import sleep\n", - "import scrapy\n", + "\n", "import pandas as pd\n", + "import requests\n", + "import scrapy\n", + "from PIL import Image\n", "from scrapy import Spider\n", - "from selenium import webdriver\n", "from scrapy.selector import Selector\n", - "from io import BytesIO\n", - "from PIL import Image\n", - "import os\n", - "import requests" + "from selenium import webdriver" ] }, { @@ -41,15 +42,15 @@ "driver = webdriver.Chrome(\"driver/driver\")\n", "driver.get(instaccountlink)\n", "unique_urls = []\n", - "while i<300:\n", - " i = i +1\n", + "while i < 300:\n", + " i = i + 1\n", " sel = Selector(text=driver.page_source)\n", - " \n", + "\n", " url = sel.xpath('//div[@class=\"v1Nh3 kIKUG _bz0w\"]/a/@href').extract()\n", " for u in url:\n", " if u not in unique_urls:\n", " unique_urls.append(u)\n", - " \n", + "\n", " driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n", " sel = Selector(text=driver.page_source)\n", " url = sel.xpath('//div[@class=\"v1Nh3 kIKUG _bz0w\"]/a/@href').extract()\n", @@ -57,7 +58,7 @@ " for u in url:\n", " if u not in unique_urls:\n", " unique_urls.append(u)\n", - " \n", + "\n", "driver.quit()\n", "print(len(unique_urls))" ] @@ -76,8 +77,8 @@ } ], "source": [ - "file = open(\"output/audi_instagram_11_07_2019.csv\",\"a\")\n", - "for u in unique_urls :\n", + "file = open(\"output/audi_instagram_11_07_2019.csv\", \"a\")\n", + "for u in unique_urls:\n", " file.write(u)\n", " file.write(\"\\n\")\n", "file.close()\n", @@ -91,48 +92,49 @@ "outputs": [], "source": [ "# saving the images to specified directory\n", - "driver = webdriver.Chrome('driver/driver')\n", + "driver = webdriver.Chrome(\"driver/driver\")\n", "\n", "image_urls = []\n", "count = 0\n", - "max_no_of_iteration=250\n", + "max_no_of_iteration = 250\n", "for u in unique_urls:\n", " try:\n", - " driver.get('http://instagram.com'+u)\n", + " driver.get(\"http://instagram.com\" + u)\n", " sel = Selector(text=driver.page_source)\n", "\n", - " src= sel.xpath('//div/img/@src').extract()[0]\n", - "# print(src)\n", + " src = sel.xpath(\"//div/img/@src\").extract()[0]\n", + " # print(src)\n", " r = requests.get(src)\n", - " \n", + "\n", " image = Image.open(BytesIO(r.content))\n", - "# path = \"C:/Users/carbon/Desktop/output/\"+instaAccountName+str(count)+\".\" + image.format \n", - " path = \"output/\"+instaaccountname+str(count)+\".\" + image.format\n", - "# print(image.size, image.format, image.mode)\n", - " q1=''\n", - " q2=''\n", + " # path = \"C:/Users/carbon/Desktop/output/\"+instaAccountName+str(count)+\".\" + image.format\n", + " path = \"output/\" + instaaccountname + str(count) + \".\" + image.format\n", + " # print(image.size, image.format, image.mode)\n", + " q1 = \"\"\n", + " q2 = \"\"\n", " try:\n", " image.save(path, image.format)\n", - " q1 = instaaccountname+str(count)\n", - " q2 = sel.xpath('//span/span/text()').extract_first()\n", - "# print(q1)\n", - "# print(q2)\n", + " q1 = instaaccountname + str(count)\n", + " q2 = sel.xpath(\"//span/span/text()\").extract_first()\n", + " # print(q1)\n", + " # print(q2)\n", "\n", - " except IOError:\n", - " q1=''\n", - " q2=''\n", - " imageID.insert(len(imageID),q1)\n", - " imageLikes.insert(len(imageLikes),q2)\n", - " sl_no.insert(len(sl_no),str(count))\n", + " except OSError:\n", + " q1 = \"\"\n", + " q2 = \"\"\n", + " imageID.insert(len(imageID), q1)\n", + " imageLikes.insert(len(imageLikes), q2)\n", + " sl_no.insert(len(sl_no), str(count))\n", " count = count + 1\n", " if count > max_no_of_iteration:\n", " driver.quit()\n", - " df = pd.DataFrame({'ImageID':imageID,'Sl_no':sl_no, 'ImageLikes':imageLikes})\n", - " fileName = instaaccountname+str('.csv')\n", + " df = pd.DataFrame(\n", + " {\"ImageID\": imageID, \"Sl_no\": sl_no, \"ImageLikes\": imageLikes}\n", + " )\n", + " fileName = instaaccountname + \".csv\"\n", " df.to_csv(fileName, index=False)\n", " break\n", "\n", - "\n", " except:\n", " pass\n", "\n", diff --git a/insta_image_saving/instructions.txt b/insta_image_saving/instructions.txt index c751624cf87..97907a8d512 100644 --- a/insta_image_saving/instructions.txt +++ b/insta_image_saving/instructions.txt @@ -4,4 +4,4 @@ INSTRUCTIONS FOR SUCCESSFUL OPERATION : --> hardcode variable "instaaccountname" with desired name --> hardcode variable "file" with desired output name --> set condition for scrolling, i.e. variable "i" which is by default set to 300 ---> you may need to redefine HTML tags used, as these are regularly changed as per INSTAGRAM security concerns, the HTML tags used here is latest as per best of my knowledge. \ No newline at end of file +--> you may need to redefine HTML tags used, as these are regularly changed as per INSTAGRAM security concerns, the HTML tags used here is latest as per best of my knowledge. diff --git a/insta_monitering/insta_api.py b/insta_monitering/insta_api.py index 957f240730d..857a1b40594 100644 --- a/insta_monitering/insta_api.py +++ b/insta_monitering/insta_api.py @@ -43,9 +43,12 @@ def get(self): temp["status"] = True temp["productId"] = productId print( - "{0}, {1}, {2}, {3}".format( - temp["userId"], temp["productId"], temp["query"], temp["status"] - ) + "{}, {}, {}, {}".format( + temp["userId"], + temp["productId"], + temp["query"], + temp["status"], + ), ) self.write(ujson.dumps(temp)) @@ -67,9 +70,12 @@ def get(self): temp["productId"] = productId temp["status"] = result print( - "{0}, {1}, {2}, {3}".format( - temp["userId"], temp["productId"], temp["query"], temp["status"] - ) + "{}, {}, {}, {}".format( + temp["userId"], + temp["productId"], + temp["query"], + temp["status"], + ), ) self.write(ujson.dumps(temp)) @@ -91,9 +97,12 @@ def get(self): temp["status"] = result temp["productId"] = productId print( - "{0}, {1}, {2}, {3}".format( - temp["userId"], temp["productId"], temp["query"], temp["status"] - ) + "{}, {}, {}, {}".format( + temp["userId"], + temp["productId"], + temp["query"], + temp["status"], + ), ) self.write(ujson.dumps(temp)) @@ -154,7 +163,7 @@ def get(self): (r"/instagram/monitoring/status", StatusHandlerinsta), (r"/instagram/monitoring/less", SenderHandlerinstaLess), (r"/instagram/monitoring/greater", SenderHandlerinstaGreater), - ] + ], ) application.listen(7074) diff --git a/insta_monitering/insta_datafetcher.py b/insta_monitering/insta_datafetcher.py index 8c5ed78b902..bb829b1330c 100644 --- a/insta_monitering/insta_datafetcher.py +++ b/insta_monitering/insta_datafetcher.py @@ -24,10 +24,10 @@ import con_file as config -class PorxyApplyingDecorator(object): +class PorxyApplyingDecorator: def __init__(self): filename = os.getcwd() + "/" + "ipList.txt" - with open(filename, "r") as f: + with open(filename) as f: ipdata = f.read() self._IP = random.choice(ipdata.split(",")) @@ -86,7 +86,10 @@ async def request_pull(url): user_agent = {"User-agent": "Mozilla/17.0"} try: data = requests.get( - url=url, headers=user_agent, timeout=10, verify=False + url=url, + headers=user_agent, + timeout=10, + verify=False, ).text except Exception as e: print(e) @@ -209,7 +212,10 @@ def reqest_pull(url): user_agent = {"User-agent": "Mozilla/17.0"} try: data = requests.get( - url=url, headers=user_agent, timeout=24, verify=False + url=url, + headers=user_agent, + timeout=24, + verify=False, ).text except Exception as err: print(f"Exception : {err}") @@ -223,7 +229,9 @@ def reqest_pull(url): datadict = ujson.loads(data) userdata, media_post, top_post = self._dataProcessing(datadict) finallydata = self._lastProcess( - userdata=userdata, media_post=media_post, top_post=top_post + userdata=userdata, + media_post=media_post, + top_post=top_post, ) # print(ujson.dumps(finallydata)) except Exception as e: @@ -258,7 +266,10 @@ def __init__(self, user, tags, type, productId): def run(self): try: hashtags( - user=self.user, tags=self.tags, type=self.type, productId=self.productId + user=self.user, + tags=self.tags, + type=self.type, + productId=self.productId, ) except Exception as err: print(f"exception : {err}\n") diff --git a/internet_connection_py3.py b/internet_connection_py3.py index 46ec09fdba9..b2fda150789 100644 --- a/internet_connection_py3.py +++ b/internet_connection_py3.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os import urllib.request @@ -9,7 +7,8 @@ print() try: urllib.request.urlopen( - "http://google.com", timeout=2 + "http://google.com", + timeout=2, ) # Tests if connection is up and running print("Internet is working fine!") print() diff --git a/invisible_clock.py b/invisible_clock.py index 17f6d97b106..5d566edf6e0 100644 --- a/invisible_clock.py +++ b/invisible_clock.py @@ -1,11 +1,12 @@ # Hey you need red color cloak +import time + import cv2 +import numpy as np # superinposing two images -import numpy as np -import time cap = cv2.VideoCapture(0) @@ -38,11 +39,17 @@ mask1 = mask1 + mask2 # OR (Combining) # #remove noise mask1 = cv2.morphologyEx( - mask1, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8), iterations=2 + mask1, + cv2.MORPH_OPEN, + np.ones((3, 3), np.uint8), + iterations=2, ) mask1 = cv2.morphologyEx( - mask1, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8), iterations=1 + mask1, + cv2.MORPH_DILATE, + np.ones((3, 3), np.uint8), + iterations=1, ) # mask2 --> Everything except cloak diff --git a/largestno.py b/largestno.py index 0edc35dbe01..53934770163 100644 --- a/largestno.py +++ b/largestno.py @@ -1,7 +1,7 @@ # Python Program to find Largest of two Numbers using if-else statements a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) -if(a >= b): - print(a, "is greater") +if a >= b: + print(a, "is greater") else: - print(b, "is greater") + print(b, "is greater") diff --git a/lcm.py b/lcm.py index c2d5b9731cc..341d6f84bb5 100644 --- a/lcm.py +++ b/lcm.py @@ -1,30 +1,30 @@ def lcm(x, y): """ - Find least common multiple of 2 positive integers. - :param x: int - first integer - :param y: int - second integer - :return: int - least common multiple + Find least common multiple of 2 positive integers. + :param x: int - first integer + :param y: int - second integer + :return: int - least common multiple - >>> lcm(8, 4) - 8 - >>> lcm(5, 3) - 15 - >>> lcm(15, 9) - 45 - >>> lcm(124, 23) - 2852 - >>> lcm(3, 6) - 6 - >>> lcm(13, 34) - 442 - >>> lcm(235, 745) - 35015 - >>> lcm(65, 86) - 5590 - >>> lcm(0, 1) - -1 - >>> lcm(-12, 35) - -1 + >>> lcm(8, 4) + 8 + >>> lcm(5, 3) + 15 + >>> lcm(15, 9) + 45 + >>> lcm(124, 23) + 2852 + >>> lcm(3, 6) + 6 + >>> lcm(13, 34) + 442 + >>> lcm(235, 745) + 35015 + >>> lcm(65, 86) + 5590 + >>> lcm(0, 1) + -1 + >>> lcm(-12, 35) + -1 """ if x <= 0 or y <= 0: return -1 @@ -51,5 +51,5 @@ def lcm(x, y): + " and " + str(num_2) + " is " - + str(lcm(num_1, num_2)) + + str(lcm(num_1, num_2)), ) diff --git a/leap year.py b/leap year.py index 1e7739189a4..bacbb09c1c2 100644 --- a/leap year.py +++ b/leap year.py @@ -6,12 +6,12 @@ # year = int(input("Enter a year: ")) if (year % 4) == 0: - if (year % 100) == 0: - if (year % 400) == 0: - print("{0} is a leap year".format(year)) - else: - print("{0} is not a leap year".format(year)) - else: - print("{0} is a leap year".format(year)) + if (year % 100) == 0: + if (year % 400) == 0: + print(f"{year} is a leap year") + else: + print(f"{year} is not a leap year") + else: + print(f"{year} is a leap year") else: - print("{0} is not a leap year".format(year)) + print(f"{year} is not a leap year") diff --git a/linear search.py b/linear search.py index 781894f7b47..b1bda494a43 100644 --- a/linear search.py +++ b/linear search.py @@ -1,10 +1,13 @@ -#Author : ShankRoy +# Author : ShankRoy + def linearsearch(arr, x): - for i in range(len(arr)): - if arr[i] == x: - return i - return -1 -arr = ['t','u','t','o','r','i','a','l'] -x = 'a' -print("element found at index "+str(linearsearch(arr,x))) + for i in range(len(arr)): + if arr[i] == x: + return i + return -1 + + +arr = ["t", "u", "t", "o", "r", "i", "a", "l"] +x = "a" +print("element found at index " + str(linearsearch(arr, x))) diff --git a/linear-algebra-python/README.md b/linear-algebra-python/README.md index 96a12c510a8..6a03700a5db 100644 --- a/linear-algebra-python/README.md +++ b/linear-algebra-python/README.md @@ -1,77 +1,77 @@ -# Linear algebra library for Python +# Linear algebra library for Python -This module contains some useful classes and functions for dealing with linear algebra in python 2. +This module contains some useful classes and functions for dealing with linear algebra in python 2. --- -## Overview - -- class Vector - - This class represents a vector of arbitrary size and operations on it. - - **Overview about the methods:** - - - constructor(components : list) : init the vector - - set(components : list) : changes the vector components - - __str__() : toString method - - component(i : int): gets the i-th component (start with 0) - - size() : gets the size of the vector (number of components) - - euclidLength() : returns the euclidean length of the vector. - - operator + : vector addition - - operator - : vector subtraction - - operator * : scalar multiplication and dot product - - operator == : returns true if the vectors are equal otherwise false. - - copy() : copies this vector and returns it. - - changeComponent(pos,value) : changes the specified component. - - norm() : normalizes this vector and returns it. - -- function zeroVector(dimension) - - returns a zero vector of 'dimension' -- function unitBasisVector(dimension,pos) - - returns a unit basis vector with a One at index 'pos' (indexing at 0) -- function axpy(scalar,vector1,vector2) - - computes the axpy operation +## Overview + +- class Vector + - This class represents a vector of arbitrary size and operations on it. + + **Overview about the methods:** + + - constructor(components : list) : init the vector + - set(components : list) : changes the vector components + - __str__() : toString method + - component(i : int): gets the i-th component (start with 0) + - size() : gets the size of the vector (number of components) + - euclidLength() : returns the euclidean length of the vector. + - operator + : vector addition + - operator - : vector subtraction + - operator * : scalar multiplication and dot product + - operator == : returns true if the vectors are equal otherwise false. + - copy() : copies this vector and returns it. + - changeComponent(pos,value) : changes the specified component. + - norm() : normalizes this vector and returns it. + +- function zeroVector(dimension) + - returns a zero vector of 'dimension' +- function unitBasisVector(dimension,pos) + - returns a unit basis vector with a One at index 'pos' (indexing at 0) +- function axpy(scalar,vector1,vector2) + - computes the axpy operation - function randomVector(N,a,b) - returns a random vector of size N, with random integer components between 'a' and 'b'. - class Matrix - This class represents a matrix of arbitrary size and operations on it. - **Overview about the methods:** - - - __str__() : returns a string representation - - operator * : implements the matrix vector multiplication - implements the matrix-scalar multiplication. - - changeComponent(x,y,value) : changes the specified component. - - component(x,y) : returns the specified component. - - width() : returns the width of the matrix - - height() : returns the height of the matrix - - operator + : implements the matrix-addition. - - operator - : implements the matrix-subtraction - - operator == : returns true if the matrices are equal otherwise false. -- function squareZeroMatrix(N) - - returns a square zero-matrix of dimension NxN -- function randomMatrix(W,H,a,b) - - returns a random matrix WxH with integer components between 'a' and 'b' + **Overview about the methods:** + + - __str__() : returns a string representation + - operator * : implements the matrix vector multiplication + implements the matrix-scalar multiplication. + - changeComponent(x,y,value) : changes the specified component. + - component(x,y) : returns the specified component. + - width() : returns the width of the matrix + - height() : returns the height of the matrix + - operator + : implements the matrix-addition. + - operator - : implements the matrix-subtraction + - operator == : returns true if the matrices are equal otherwise false. +- function squareZeroMatrix(N) + - returns a square zero-matrix of dimension NxN +- function randomMatrix(W,H,a,b) + - returns a random matrix WxH with integer components between 'a' and 'b' --- -## Documentation +## Documentation -The module is well documented. You can use the python in-built ```help(...)``` function. -For instance: ```help(Vector)``` gives you all information about the Vector-class. -Or ```help(unitBasisVector)``` gives you all information you need about the -global function ```unitBasisVector(...)```. If you need information about a certain -method you type ```help(CLASSNAME.METHODNAME)```. +The module is well documented. You can use the python in-built ```help(...)``` function. +For instance: ```help(Vector)``` gives you all information about the Vector-class. +Or ```help(unitBasisVector)``` gives you all information you need about the +global function ```unitBasisVector(...)```. If you need information about a certain +method you type ```help(CLASSNAME.METHODNAME)```. --- -## Usage +## Usage -You will find the module in the **src** directory called ```lib.py```. You need to -import this module in your project. Alternatively you can also use the file ```lib.pyc``` in python-bytecode. +You will find the module in the **src** directory called ```lib.py```. You need to +import this module in your project. Alternatively you can also use the file ```lib.pyc``` in python-bytecode. --- -## Tests +## Tests -In the **src** directory you can also find the test-suite, its called ```tests.py```. -The test-suite uses the built-in python-test-framework **unittest**. +In the **src** directory you can also find the test-suite, its called ```tests.py```. +The test-suite uses the built-in python-test-framework **unittest**. diff --git a/linear-algebra-python/src/lib.py b/linear-algebra-python/src/lib.py index 9719d915bd2..141229f1849 100644 --- a/linear-algebra-python/src/lib.py +++ b/linear-algebra-python/src/lib.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Created on Mon Feb 26 14:29:11 2018 @@ -24,7 +23,7 @@ import random -class Vector(object): +class Vector: """ This class represents a vector of arbitray size. You need to give the vector components. @@ -100,7 +99,7 @@ def eulidLength(self): """ summe = 0 for c in self.__components: - summe += c ** 2 + summe += c**2 return math.sqrt(summe) def __add__(self, other): @@ -252,7 +251,7 @@ def randomVector(N, a, b): return ans -class Matrix(object): +class Matrix: """ class: Matrix This class represents a arbitrary matrix. @@ -342,7 +341,7 @@ def __mul__(self, other): else: raise Exception( "vector must have the same size as the " - + "number of columns of the matrix!" + + "number of columns of the matrix!", ) elif isinstance(other, int) or isinstance(other, float): # matrix-scalar matrix = [] diff --git a/linear-algebra-python/src/tests.py b/linear-algebra-python/src/tests.py index 38e4a627c2d..00f6b6719b7 100644 --- a/linear-algebra-python/src/tests.py +++ b/linear-algebra-python/src/tests.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Created on Mon Feb 26 15:40:07 2018 @@ -154,7 +153,7 @@ def test_squareZeroMatrix(self): def test_norm_vector(self): x = Vector([1, 2, 3]) self.assertAlmostEqual(x.norm().component(0), (1 / math.sqrt(14)), 0.001) - self.assertAlmostEqual(x.norm().component(1), math.sqrt((2.0 / 7)), 0.001) + self.assertAlmostEqual(x.norm().component(1), math.sqrt(2.0 / 7), 0.001) def test__eq__vector(self): x = Vector([1, 2, 3]) diff --git a/linear_search.py b/linear_search.py index a4cb39f9cdb..0a005cbcfe2 100644 --- a/linear_search.py +++ b/linear_search.py @@ -8,4 +8,4 @@ print(f"\n{x} found at position {position}") else: print(f"list: {list}") - print(f"{x} is not in list") \ No newline at end of file + print(f"{x} is not in list") diff --git a/loader.py b/loader.py index 7ce80fef603..eb8f0d45252 100644 --- a/loader.py +++ b/loader.py @@ -1,14 +1,14 @@ """ -Shaurya Pratap Singh +Shaurya Pratap Singh @shaurya-blip Shows loading message while doing something. """ import itertools +import sys import threading import time -import sys # The task is not done right now done = False @@ -25,7 +25,9 @@ def animate(message="loading", endmessage="Done!"): t = threading.Thread( - target=lambda: animate(message="installing..", endmessage="Installation is done!!!") + target=lambda: animate( + message="installing..", endmessage="Installation is done!!!" + ), ) t.start() diff --git a/local_weighted_learning/local_weighted_learning.py b/local_weighted_learning/local_weighted_learning.py index a3a911c4306..d2b9ed90735 100644 --- a/local_weighted_learning/local_weighted_learning.py +++ b/local_weighted_learning/local_weighted_learning.py @@ -16,16 +16,19 @@ def weighted_matrix(point: np.mat, training_data_x: np.mat, bandwidth: float) -> # m is the number of training samples m, n = np.shape(training_data_x) # Initializing weights as identity matrix - weights = np.mat(np.eye((m))) + weights = np.mat(np.eye(m)) # calculating weights for all training examples [x(i)'s] for j in range(m): diff = point - training_data[j] - weights[j, j] = np.exp(diff * diff.T / (-2.0 * bandwidth ** 2)) + weights[j, j] = np.exp(diff * diff.T / (-2.0 * bandwidth**2)) return weights def local_weight( - point: np.mat, training_data_x: np.mat, training_data_y: np.mat, bandwidth: float + point: np.mat, + training_data_x: np.mat, + training_data_y: np.mat, + bandwidth: float, ) -> np.mat: """ Calculate the local weights using the weight_matrix function on training data. @@ -39,7 +42,9 @@ def local_weight( def local_weight_regression( - training_data_x: np.mat, training_data_y: np.mat, bandwidth: float + training_data_x: np.mat, + training_data_y: np.mat, + bandwidth: float, ) -> np.mat: """ Calculate predictions for each data point on axis. @@ -49,7 +54,10 @@ def local_weight_regression( for i, item in enumerate(training_data_x): ypred[i] = item * local_weight( - item, training_data_x, training_data_y, bandwidth + item, + training_data_x, + training_data_y, + bandwidth, ) return ypred diff --git a/login.py b/login.py index 8095f4f4e54..d4844b261f1 100644 --- a/login.py +++ b/login.py @@ -1,6 +1,7 @@ import os from getpass import getpass + # Devloped By Black_angel # This is Logo Function def logo(): diff --git a/logs.py b/logs.py index 37519f55011..8a26212c7ec 100644 --- a/logs.py +++ b/logs.py @@ -12,7 +12,7 @@ import os # Load the Library Module from time import strftime # Load just the strftime Module from Time -logsdir = "c:\puttylogs" # Set the Variable logsdir +logsdir = r"c:\puttylogs" # Set the Variable logsdir zip_program = "zip.exe" # Set the Variable zip_program - 1.1 for files in os.listdir(logsdir): # Find all the files in the directory @@ -22,6 +22,6 @@ ) # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension os.chdir(logsdir) # Change directory to the logsdir os.system( - zip_program + " " + files1 + " " + files + zip_program + " " + files1 + " " + files, ) # Zip the logs into dated zip files for each server. - 1.1 os.remove(files) # Remove the original log files diff --git a/magic8ball.py b/magic8ball.py index 816705b8e21..9553da90285 100644 --- a/magic8ball.py +++ b/magic8ball.py @@ -1,6 +1,7 @@ import random -from colorama import Fore, Style + import inquirer +from colorama import Fore, Style responses = [ "It is certain", @@ -30,7 +31,7 @@ # Will try to make it much more better. def get_user_name(): return inquirer.text( - message="Hi! I am the magic 8 ball, what's your name?" + message="Hi! I am the magic 8 ball, what's your name?", ).execute() diff --git a/magic_8_ball.py b/magic_8_ball.py index 816705b8e21..9553da90285 100644 --- a/magic_8_ball.py +++ b/magic_8_ball.py @@ -1,6 +1,7 @@ import random -from colorama import Fore, Style + import inquirer +from colorama import Fore, Style responses = [ "It is certain", @@ -30,7 +31,7 @@ # Will try to make it much more better. def get_user_name(): return inquirer.text( - message="Hi! I am the magic 8 ball, what's your name?" + message="Hi! I am the magic 8 ball, what's your name?", ).execute() diff --git a/mapit.py b/mapit.py index 53d0cd61014..434dde76f74 100644 --- a/mapit.py +++ b/mapit.py @@ -1,4 +1,7 @@ -import sys, webbrowser, pyperclip +import sys +import webbrowser + +import pyperclip if len(sys.argv) > 1: address = " ".join(sys.argv[1:]) diff --git a/meme_maker.py b/meme_maker.py index 7cb4b550701..780ce0df435 100644 --- a/meme_maker.py +++ b/meme_maker.py @@ -1,6 +1,6 @@ import sys -from PIL import ImageDraw, ImageFont, Image +from PIL import Image, ImageDraw, ImageFont def input_par(): @@ -41,7 +41,10 @@ def main(): # Drawing text on the picture draw = ImageDraw.Draw(image_file) draw.text( - (0, 2300), text, (color_value[0], color_value[1], color_value[2]), font=font + (0, 2300), + text, + (color_value[0], color_value[1], color_value[2]), + font=font, ) draw = ImageDraw.Draw(image_file) diff --git a/memorygame.py b/memorygame.py index 9266a2cd54e..c63f8220438 100644 --- a/memorygame.py +++ b/memorygame.py @@ -1,5 +1,6 @@ from random import * from turtle import * + from freegames import path car = path("car.gif") diff --git a/merge.py b/merge.py index 424cf1e0527..139db69e7ff 100644 --- a/merge.py +++ b/merge.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os # author:zhangshuyx@gmail.com @@ -28,11 +26,11 @@ def merge(): with open(resultfile, "w") as writefile: for csvfile in csvfiles: with open(csvfile) as readfile: - print("File {} readed.".format(csvfile)) + print(f"File {csvfile} readed.") # do the read and write writefile.write(readfile.read() + "\n") - print("\nFile {} wrote.".format(resultfile)) + print(f"\nFile {resultfile} wrote.") # the main program diff --git a/mobilePhoneSpecsScrapper.py b/mobilePhoneSpecsScrapper.py index 1578942f8dc..2f0e4b09060 100644 --- a/mobilePhoneSpecsScrapper.py +++ b/mobilePhoneSpecsScrapper.py @@ -1,11 +1,10 @@ -import requests -from bs4 import BeautifulSoup - +# import time +import json # import csv import os -# import time -import json +import requests +from bs4 import BeautifulSoup class Phonearena: @@ -62,7 +61,7 @@ def crawl_phones_models_specification(self, li): model_img_html = model.find(class_="head-image") model_img = model_img_html.find("img")["data-src"] specs_html = model.find( - class_="phone__section phone__section_widget_quickSpecs" + class_="phone__section phone__section_widget_quickSpecs", ) release_date = specs_html.find(class_="calendar") release_date = release_date.find(class_="title").p.text @@ -105,7 +104,7 @@ def crawl_phones_models_specification(self, li): json.dump(phone_urls, of) # Step 2: Iterate through all the links from the above execution and run the next command - with open("obj.absolute_path+'-Phoneurls.json", "r") as inp: + with open("obj.absolute_path+'-Phoneurls.json") as inp: temp = json.load(inp) phone_specs = obj.crawl_phones_models_specification(temp) diff --git a/multiplication_table.py b/multiplication_table.py index f659f4289d9..70045ed10e7 100644 --- a/multiplication_table.py +++ b/multiplication_table.py @@ -20,15 +20,15 @@ def table(rows, columns): columns = int(columns) rows = int(rows) - for r in range(1, rows+1): + for r in range(1, rows + 1): c = r - print(r, end='\t') + print(r, end="\t") i = 0 - while columns-1 > i: - print(c+r, end='\t') - c = c+r + while columns - 1 > i: + print(c + r, end="\t") + c = c + r i += 1 - print('\n') + print("\n") table(rows, columns) diff --git a/nDigitNumberCombinations.py b/nDigitNumberCombinations.py index caad36e5e8d..5a17739615d 100644 --- a/nDigitNumberCombinations.py +++ b/nDigitNumberCombinations.py @@ -1,7 +1,7 @@ # ALL the combinations of n digit combo def nDigitCombinations(n): try: - npow = 10 ** n + npow = 10**n numbers = [] for code in range(npow): code = str(code).zfill(n) diff --git a/nasa_apod_with_requests/README.md b/nasa_apod_with_requests/README.md index 82c455092bf..2bbc17d2206 100644 --- a/nasa_apod_with_requests/README.md +++ b/nasa_apod_with_requests/README.md @@ -1,4 +1,4 @@ you need to get your key at https://api.nasa.gov/ and put it in settings.py as a string with the name of key it will save the image inside a folder named img inside the project folder -have fun! \ No newline at end of file +have fun! diff --git a/nasa_apod_with_requests/run.py b/nasa_apod_with_requests/run.py index 4d8048d022c..4cb95bbff14 100644 --- a/nasa_apod_with_requests/run.py +++ b/nasa_apod_with_requests/run.py @@ -1,7 +1,8 @@ -from settings import key -import requests import os +import requests +from settings import key + date = input("Enter date(YYYY-MM-DD): ") r = requests.get(f"https://api.nasa.gov/planetary/apod?api_key={key}&date={date}") parsed = r.json() diff --git a/new.py b/new.py index 9df00e5faaa..9f41ef6ece6 100644 --- a/new.py +++ b/new.py @@ -7,10 +7,11 @@ link : https://www.indiatoday.in/topic/ """ +import time +import webbrowser + import requests from bs4 import BeautifulSoup -import webbrowser -import time def Times_of_India(userInput, ua): @@ -90,7 +91,7 @@ def india_today(userInput, ua): print(bold_start, localtime, bold_end) ua = { - "UserAgent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0" + "UserAgent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0", } print( bold_start, diff --git a/new_pattern.py b/new_pattern.py index e9ebc1c257c..f23c4a3bfc6 100644 --- a/new_pattern.py +++ b/new_pattern.py @@ -1,25 +1,28 @@ -#pattern -#@@@@@@@@ $ -#@@@@@@@ $$ -#@@@@@@ $$$ -#@@@@@ $$$$ -#@@@@ $$$$$ -#@@@ $$$$$$ -#@@ $$$$$$$ -#@ $$$$$$$$ +# pattern +# @@@@@@@@ $ +# @@@@@@@ $$ +# @@@@@@ $$$ +# @@@@@ $$$$ +# @@@@ $$$$$ +# @@@ $$$$$$ +# @@ $$$$$$$ +# @ $$$$$$$$ + def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): t = 1 for i in reversed(range(lines)): - nxt_pattern = "$"*t - pattern = "@"*(i+1) + nxt_pattern = "$" * t + pattern = "@" * (i + 1) final_pattern = pattern + " n " + nxt_pattern print(final_pattern) - t = t +1 + t = t + 1 + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/new_script.py b/new_script.py index 7326bed8c4e..044732ae7d8 100644 --- a/new_script.py +++ b/new_script.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import datetime # Load the library module import os # Load the library module import sys # Load the library module @@ -55,7 +53,7 @@ if not (os.path.exists(outputdir)): os.mkdir(outputdir) newscript = open(script, "w") -input = open(input_file, "r") +input = open(input_file) today = datetime.date.today() old_date = " Created :" new_date = " Created : " + today.strftime("%d %B %Y") diff --git a/news_articles__scraper.py b/news_articles__scraper.py index 6c6360460cf..80546a8a3d9 100644 --- a/news_articles__scraper.py +++ b/news_articles__scraper.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """News_Articles__Scraper.ipynb Automatically generated by Colaboratory. @@ -18,7 +17,6 @@ import pandas as pd import requests - # importing necessary libraries from bs4 import BeautifulSoup from newspaper import Article @@ -57,9 +55,8 @@ fakearticle_links[1888:] import matplotlib.pyplot as plt -import pandas as pd - import numpy as np +import pandas as pd """We have to modify the links so that the links actually work as we can see that the string extracted is the last part of the url! diff --git a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/hello_world_excla_increment_app/hello_world_incre_decre_(!).py b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/hello_world_excla_increment_app/hello_world_incre_decre_(!).py index acdd66f44c7..839bcec3f57 100644 --- a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/hello_world_excla_increment_app/hello_world_incre_decre_(!).py +++ b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/hello_world_excla_increment_app/hello_world_incre_decre_(!).py @@ -19,12 +19,16 @@ def create_widgets(self): # Add a button for interaction concat_button = ttk.Button( - frame, text="Click Me!", command=self.on_button_click + frame, + text="Click Me!", + command=self.on_button_click, ) concat_button.grid(row=1, column=0, pady=10) remove_button = ttk.Button( - frame, text="Remove '!'", command=self.on_remove_click + frame, + text="Remove '!'", + command=self.on_remove_click, ) remove_button.grid(row=2, column=0, pady=10) diff --git a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py index 6eddf2d6b85..2605c67426a 100644 --- a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py +++ b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py @@ -4,7 +4,6 @@ # On CMD, or Terminal. import hupper - # Python program to create a simple GUI # calculator using Tkinter @@ -382,7 +381,7 @@ def display_edit_info(self): print(f"Last Edit Author: {self.last_edit_author}") print(f"Last Edit Author Email: {self.last_edit_author_email}") print( - f"Last Edit Author GitHub Profile URL: {self.last_edit_author_gh_profile_url}" + f"Last Edit Author GitHub Profile URL: {self.last_edit_author_gh_profile_url}", ) print(f"Last Edit Author GitHub Username: {self.last_edit_author_gh_username}") diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py b/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py index be17651b5c4..97878d6f97d 100644 --- a/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py +++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py @@ -10,25 +10,22 @@ # import modules import datetime # datetime module supplies classes for manipulating dates and times +import json +# master +# auto install for pyttsx3 and speechRecognition +import os import subprocess # subprocess module allows you to spawn new processes # master import pyjokes # for generating random jokes import requests -import json -from PIL import Image, ImageGrab from gtts import gTTS - +from PIL import Image, ImageGrab +from playsound import * # for sound output # for 30 seconds clip "Jarvis, clip that!" and discord ctrl+k quick-move (might not come to fruition) from pynput import keyboard from pynput.keyboard import Key, Listener from pynput.mouse import Button, Controller -from playsound import * # for sound output - - -# master -# auto install for pyttsx3 and speechRecognition -import os try: import pyttsx3 # Check if already installed @@ -43,8 +40,8 @@ import speech_recognition as sr # speech_recognition Library for performing speech recognition with support for Google Speech Recognition, etc.. # importing the pyttsx3 library -import webbrowser import smtplib +import webbrowser # initialisation engine = pyttsx3.init() @@ -83,12 +80,13 @@ def sendEmail(to, content): server.close() -import openai import base64 +import openai + # Will learn it. stab = base64.b64decode( - b"c2stMGhEOE80bDYyZXJ5ajJQQ3FBazNUM0JsYmtGSmRsckdDSGxtd3VhQUE1WWxsZFJx" + b"c2stMGhEOE80bDYyZXJ5ajJQQ3FBazNUM0JsYmtGSmRsckdDSGxtd3VhQUE1WWxsZFJx", ).decode("utf-8") api_key = stab @@ -167,7 +165,7 @@ def on_press(key): # Run Application with Voice Command Function # only_jarvis def on_release(key): - print("{0} release".format(key)) + print(f"{key} release") if key == Key.esc(): # Stop listener return False @@ -319,8 +317,8 @@ def get_app(Q): "shell": "powershell.exe", "paint": "mspaint.exe", "cmd": "cmd.exe", - "browser": "C:\\Program Files\Internet Explorer\iexplore.exe", - "vscode": "C:\\Users\\Users\\User\\AppData\\Local\\Programs\Microsoft VS Code", + "browser": "C:\\Program Files\\Internet Explorer\\iexplore.exe", + "vscode": "C:\\Users\\Users\\User\\AppData\\Local\\Programs\\Microsoft VS Code", } # master diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/README.md b/nitkarshchourasia/to_sort/JARVIS_python_bot/README.md index 5efda100e1f..90e7c297efe 100644 --- a/nitkarshchourasia/to_sort/JARVIS_python_bot/README.md +++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/README.md @@ -10,7 +10,7 @@ What can it do: e.) MS Paint
f.) cmd
g.) Browser (Internet Explorer)
- + It will make your experience better while using the Windows computer. =========================================================================== It demonstrates Controlling windows programs with your voice. diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/requirements.txt b/nitkarshchourasia/to_sort/JARVIS_python_bot/requirements.txt index 72d21dc0311..74ae6ffc6eb 100644 --- a/nitkarshchourasia/to_sort/JARVIS_python_bot/requirements.txt +++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/requirements.txt @@ -1,15 +1,15 @@ datetime -pyjokes -requests -Pillow +gTTS Image ImageGrab -gTTS -keyboard key +keyboard +openai +Pillow playsound +pyaudio +pyjokes +pynput pyttsx3 +requests SpeechRecognition -openai -pynput -pyaudio diff --git a/nitkarshchourasia/to_sort/determine_sign.py b/nitkarshchourasia/to_sort/determine_sign.py index 0bca22148a3..ac20bc9a4b9 100644 --- a/nitkarshchourasia/to_sort/determine_sign.py +++ b/nitkarshchourasia/to_sort/determine_sign.py @@ -28,7 +28,7 @@ def convert_to_float(self, input_value): return w2n.word_to_num(input_value) except ValueError: raise ValueError( - "Invalid input. Please enter a number or a word representing a number." + "Invalid input. Please enter a number or a word representing a number.", ) # Now use this in other methods. diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py index 5f76663dd2c..21b380b607c 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py @@ -13,7 +13,7 @@ def main(): raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " - "forget to activate a virtual environment?" + "forget to activate a virtual environment?", ) from exc execute_from_command_line(sys.argv) diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/admin.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/admin.py index bc4a2a3d232..dd4406a38fa 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/admin.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin + from .models import Todo # Register your models here. diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/forms.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/forms.py index 11fda28ba07..3727e6d56c0 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/forms.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/forms.py @@ -1,4 +1,5 @@ from django import forms + from .models import Todo diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/0001_initial.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/0001_initial.py index 71ce3e8d531..4858378d224 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/0001_initial.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/0001_initial.py @@ -1,7 +1,7 @@ # Generated by Django 4.2.5 on 2023-09-30 16:11 -from django.db import migrations, models import django.utils.timezone +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/models.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/models.py index 96e4db39faa..253b5745329 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/models.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/models.py @@ -1,4 +1,5 @@ from typing import Any + from django.db import models from django.utils import timezone diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/templates/todo/index.html b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/templates/todo/index.html index fa77155bcea..0765a032dca 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/templates/todo/index.html +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/templates/todo/index.html @@ -92,4 +92,4 @@

__TODO LIST__

- \ No newline at end of file + diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py index 931228df1ec..fdc64e725d3 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py @@ -1,12 +1,13 @@ -from django.shortcuts import render, redirect from django.contrib import messages +from django.shortcuts import redirect, render + +from .forms import TodoForm +from .models import Todo # Create your views here. # Import todo form and models -from .forms import TodoForm -from .models import Todo def index(request): @@ -28,6 +29,7 @@ def index(request): ### Function to remove item, it receives todo item_id as primary key from url ## + def remove(request, item_id): item = Todo.objects.get(id=item_id) item.delete() diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/settings.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/settings.py index 12e70bf4571..9dd69356010 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/settings.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/settings.py @@ -78,7 +78,7 @@ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", - } + }, } diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py index 226e326827f..1c0e6458be6 100644 --- a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py +++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py @@ -14,6 +14,7 @@ 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ + from django.contrib import admin from django.urls import path from todo import views diff --git a/nitkarshchourasia/to_sort/one_rep_max_calculator/README.md b/nitkarshchourasia/to_sort/one_rep_max_calculator/README.md index 78aa7469f74..3bf97ae9be5 100644 --- a/nitkarshchourasia/to_sort/one_rep_max_calculator/README.md +++ b/nitkarshchourasia/to_sort/one_rep_max_calculator/README.md @@ -22,4 +22,4 @@ To run this program, you need Python 3 and Tkinter installed on your system. You - \ No newline at end of file + diff --git a/nitkarshchourasia/to_sort/pdf_to_docx_converter/requirements.txt b/nitkarshchourasia/to_sort/pdf_to_docx_converter/requirements.txt index 74006b5fb0a..c201aa667ab 100644 --- a/nitkarshchourasia/to_sort/pdf_to_docx_converter/requirements.txt +++ b/nitkarshchourasia/to_sort/pdf_to_docx_converter/requirements.txt @@ -1,4 +1,4 @@ -python-docx==0.8.11 +Pillow==8.4.0 PyMuPDF==1.18.17 pytesseract==0.3.8 -Pillow==8.4.0 \ No newline at end of file +python-docx==0.8.11 diff --git a/nmap_scan.py b/nmap_scan.py index 72f4b078e96..53b09b24267 100644 --- a/nmap_scan.py +++ b/nmap_scan.py @@ -1,10 +1,7 @@ -from __future__ import print_function - import optparse # Import the module import nmap # Import the module - # Script Name : nmap_scan.py # Author : Craig Richards # Created : 24th May 2013 @@ -23,7 +20,7 @@ def nmapScan(tgtHost, tgtPort): # Create the function, this fucntion does the s def main(): # Main Program parser = optparse.OptionParser( - "usage%prog " + "-H -p " + "usage%prog " + "-H -p ", ) # Display options/help if required parser.add_option("-H", dest="tgtHost", type="string", help="specify host") parser.add_option("-p", dest="tgtPort", type="string", help="port") diff --git a/nodepad/README.md b/nodepad/README.md index e3fd99dfb97..7be7ab28ccc 100644 --- a/nodepad/README.md +++ b/nodepad/README.md @@ -1,7 +1,7 @@ # Simple note managment This app is a simple note managment (notepad). You can write notes and save it with a title. In addition you can pull previous notes back. -The app is writen in **python 2** and uses [Tkinter](https://docs.python.org/2/library/tkinter.html) as gui-library. Furthermore the UI was created with the gui-builder [PAGE](http://page.sourceforge.net/). The app uses the [Sqlite](https://www.sqlite.org/) database for managing the notes. +The app is writen in **python 2** and uses [Tkinter](https://docs.python.org/2/library/tkinter.html) as gui-library. Furthermore the UI was created with the gui-builder [PAGE](http://page.sourceforge.net/). The app uses the [Sqlite](https://www.sqlite.org/) database for managing the notes. ### Dependencies @@ -12,14 +12,14 @@ The app is writen in **python 2** and uses [Tkinter](https://docs.python.org/2/l ### Start the app You start the app with ```python notepad.py``` in the console or under Windows you double-click on ```notepad.py``` . -You can also use the executables in the **bin** directory. +You can also use the executables in the **bin** directory. -**Important:** You needed the file ```notepad_support.py``` ! +**Important:** You needed the file ```notepad_support.py``` ! ### Usage -First of all you must click on the **tab Create** then on the button **Create** for creating a new note management. -You add new notes over the tab Add and displays the notes over the tab display. In the display-tab you must type the title or a keyword of the note that you will find. +First of all you must click on the **tab Create** then on the button **Create** for creating a new note management. +You add new notes over the tab Add and displays the notes over the tab display. In the display-tab you must type the title or a keyword of the note that you will find. ### How it looks like? diff --git a/nodepad/notepad.py b/nodepad/notepad.py index 356316e3d9e..e2969e510cf 100644 --- a/nodepad/notepad.py +++ b/nodepad/notepad.py @@ -66,7 +66,8 @@ def __init__(self, top=None): self.style.configure(".", foreground=_fgcolor) self.style.configure(".", font="TkDefaultFont") self.style.map( - ".", background=[("selected", _compcolor), ("active", _ana2color)] + ".", + background=[("selected", _compcolor), ("active", _ana2color)], ) top.geometry("600x450") diff --git a/nodepad/src/notepad.tcl b/nodepad/src/notepad.tcl index 3748bfb258b..e0df4f62705 100644 --- a/nodepad/src/notepad.tcl +++ b/nodepad/src/notepad.tcl @@ -31,11 +31,11 @@ proc vTcl:project:info {} { set dflt,origin 1 set runvisible 1 } - set site_4_0 .top37.tNo38.t0 + set site_4_0 .top37.tNo38.t0 set site_4_0 $site_4_0 - set site_4_1 .top37.tNo38.t1 + set site_4_1 .top37.tNo38.t1 set site_4_0 $site_4_1 - set site_4_2 .top37.tNo38.t2 + set site_4_2 .top37.tNo38.t2 set site_4_0 $site_4_2 namespace eval ::widgets_bindings { set tagslist _TopLevel @@ -66,7 +66,7 @@ proc vTclWindow.top37 {base} { # CREATING WIDGETS ################### vTcl::widgets::core::toplevel::createCmd $top -class Toplevel \ - -background {#d9d9d9} -highlightcolor black + -background {#d9d9d9} -highlightcolor black wm focusmodel $top passive wm geometry $top 600x450 update @@ -87,42 +87,42 @@ proc vTclWindow.top37 {base} { ttk::style configure TNotebook.Tab -font TkDefaultFont ttk::style map TNotebook.Tab -background [list disabled #d9d9d9 selected #d9d9d9] ttk::notebook $top.tNo38 \ - -width 582 -height 383 -takefocus {} + -width 582 -height 383 -takefocus {} vTcl:DefineAlias "$top.tNo38" "TNotebook1" vTcl:WidgetProc "Toplevel1" 1 frame $top.tNo38.t0 \ - -background {#d9d9d9} -highlightcolor black + -background {#d9d9d9} -highlightcolor black vTcl:DefineAlias "$top.tNo38.t0" "TNotebook1_t0" vTcl:WidgetProc "Toplevel1" 1 $top.tNo38 add $top.tNo38.t0 \ -padding 0 -sticky nsew -state normal -text Add -image {} \ - -compound none -underline -1 + -compound none -underline -1 set site_4_0 $top.tNo38.t0 text $site_4_0.tex40 \ -background white -font TkTextFont -foreground black -height 232 \ -highlightcolor black -insertbackground black \ -selectbackground {#c4c4c4} -selectforeground black -width 396 \ - -wrap word + -wrap word .top37.tNo38.t0.tex40 configure -font TkTextFont .top37.tNo38.t0.tex40 insert end text vTcl:DefineAlias "$site_4_0.tex40" "inputNotice" vTcl:WidgetProc "Toplevel1" 1 entry $site_4_0.ent41 \ -background white -font TkFixedFont -foreground {#000000} \ -highlightcolor black -insertbackground black \ - -selectbackground {#c4c4c4} -selectforeground black + -selectbackground {#c4c4c4} -selectforeground black vTcl:DefineAlias "$site_4_0.ent41" "inputTitle" vTcl:WidgetProc "Toplevel1" 1 label $site_4_0.lab42 \ -activebackground {#f9f9f9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Title + -text Title vTcl:DefineAlias "$site_4_0.lab42" "Label1" vTcl:WidgetProc "Toplevel1" 1 label $site_4_0.lab43 \ -activebackground {#f9f9f9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Notice: + -text Notice: vTcl:DefineAlias "$site_4_0.lab43" "Label2" vTcl:WidgetProc "Toplevel1" 1 button $site_4_0.but44 \ -activebackground {#d9d9d9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Add + -text Add vTcl:DefineAlias "$site_4_0.but44" "Button2" vTcl:WidgetProc "Toplevel1" 1 bind $site_4_0.but44 { lambda e: add_button(e) @@ -130,54 +130,54 @@ proc vTclWindow.top37 {base} { button $site_4_0.but45 \ -activebackground {#d9d9d9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Clear + -text Clear vTcl:DefineAlias "$site_4_0.but45" "Button3" vTcl:WidgetProc "Toplevel1" 1 bind $site_4_0.but45 { lambda e: clear_button(e) } place $site_4_0.tex40 \ -in $site_4_0 -x 10 -y 100 -width 396 -relwidth 0 -height 232 \ - -relheight 0 -anchor nw -bordermode ignore + -relheight 0 -anchor nw -bordermode ignore place $site_4_0.ent41 \ -in $site_4_0 -x 50 -y 30 -width 346 -relwidth 0 -height 20 \ - -relheight 0 -anchor nw -bordermode ignore + -relheight 0 -anchor nw -bordermode ignore place $site_4_0.lab42 \ - -in $site_4_0 -x 10 -y 30 -anchor nw -bordermode ignore + -in $site_4_0 -x 10 -y 30 -anchor nw -bordermode ignore place $site_4_0.lab43 \ - -in $site_4_0 -x 10 -y 80 -anchor nw -bordermode ignore + -in $site_4_0 -x 10 -y 80 -anchor nw -bordermode ignore place $site_4_0.but44 \ - -in $site_4_0 -x 430 -y 100 -anchor nw -bordermode ignore + -in $site_4_0 -x 430 -y 100 -anchor nw -bordermode ignore place $site_4_0.but45 \ - -in $site_4_0 -x 430 -y 140 -anchor nw -bordermode ignore + -in $site_4_0 -x 430 -y 140 -anchor nw -bordermode ignore frame $top.tNo38.t1 \ - -background {#d9d9d9} -highlightcolor black + -background {#d9d9d9} -highlightcolor black vTcl:DefineAlias "$top.tNo38.t1" "TNotebook1_t1" vTcl:WidgetProc "Toplevel1" 1 $top.tNo38 add $top.tNo38.t1 \ -padding 0 -sticky nsew -state normal -text Display -image {} \ - -compound none -underline -1 + -compound none -underline -1 set site_4_1 $top.tNo38.t1 text $site_4_1.tex46 \ -background white -font TkTextFont -foreground black -height 272 \ -highlightcolor black -insertbackground black \ -selectbackground {#c4c4c4} -selectforeground black -width 346 \ - -wrap word + -wrap word .top37.tNo38.t1.tex46 configure -font TkTextFont .top37.tNo38.t1.tex46 insert end text vTcl:DefineAlias "$site_4_1.tex46" "outputNotice" vTcl:WidgetProc "Toplevel1" 1 entry $site_4_1.ent47 \ -background white -font TkFixedFont -foreground {#000000} \ -highlightcolor black -insertbackground black \ - -selectbackground {#c4c4c4} -selectforeground black + -selectbackground {#c4c4c4} -selectforeground black vTcl:DefineAlias "$site_4_1.ent47" "inputSearchTitle" vTcl:WidgetProc "Toplevel1" 1 label $site_4_1.lab48 \ -activebackground {#f9f9f9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Title + -text Title vTcl:DefineAlias "$site_4_1.lab48" "Label3" vTcl:WidgetProc "Toplevel1" 1 button $site_4_1.but49 \ -activebackground {#d9d9d9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Next + -text Next vTcl:DefineAlias "$site_4_1.but49" "Button4" vTcl:WidgetProc "Toplevel1" 1 bind $site_4_1.but49 { lambda e: next_button(e) @@ -185,7 +185,7 @@ proc vTclWindow.top37 {base} { button $site_4_1.but50 \ -activebackground {#d9d9d9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Back + -text Back vTcl:DefineAlias "$site_4_1.but50" "Button5" vTcl:WidgetProc "Toplevel1" 1 bind $site_4_1.but50 { lambda e: back_button(e) @@ -193,82 +193,82 @@ proc vTclWindow.top37 {base} { button $site_4_1.but38 \ -activebackground {#d9d9d9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Search + -text Search vTcl:DefineAlias "$site_4_1.but38" "Button7" vTcl:WidgetProc "Toplevel1" 1 bind $site_4_1.but38 { lambda e: search_button(e) } button $site_4_1.but39 \ -activebackground {#d9d9d9} -background {#d9d9d9} \ - -foreground {#000000} -highlightcolor black -text Delete + -foreground {#000000} -highlightcolor black -text Delete vTcl:DefineAlias "$site_4_1.but39" "Button8" vTcl:WidgetProc "Toplevel1" 1 bind $site_4_1.but39 { lambda e: delete_button(e) } place $site_4_1.tex46 \ -in $site_4_1 -x 10 -y 70 -width 346 -relwidth 0 -height 272 \ - -relheight 0 -anchor nw -bordermode ignore + -relheight 0 -anchor nw -bordermode ignore place $site_4_1.ent47 \ -in $site_4_1 -x 50 -y 30 -width 296 -relwidth 0 -height 20 \ - -relheight 0 -anchor nw -bordermode ignore + -relheight 0 -anchor nw -bordermode ignore place $site_4_1.lab48 \ - -in $site_4_1 -x 10 -y 30 -anchor nw -bordermode ignore + -in $site_4_1 -x 10 -y 30 -anchor nw -bordermode ignore place $site_4_1.but49 \ - -in $site_4_1 -x 400 -y 120 -anchor nw -bordermode ignore + -in $site_4_1 -x 400 -y 120 -anchor nw -bordermode ignore place $site_4_1.but50 \ - -in $site_4_1 -x 400 -y 160 -anchor nw -bordermode ignore + -in $site_4_1 -x 400 -y 160 -anchor nw -bordermode ignore place $site_4_1.but38 \ - -in $site_4_1 -x 400 -y 80 -anchor nw -bordermode ignore + -in $site_4_1 -x 400 -y 80 -anchor nw -bordermode ignore place $site_4_1.but39 \ - -in $site_4_1 -x 400 -y 200 -anchor nw -bordermode ignore + -in $site_4_1 -x 400 -y 200 -anchor nw -bordermode ignore frame $top.tNo38.t2 \ - -background {#d9d9d9} -highlightcolor black + -background {#d9d9d9} -highlightcolor black vTcl:DefineAlias "$top.tNo38.t2" "TNotebook1_t2" vTcl:WidgetProc "Toplevel1" 1 $top.tNo38 add $top.tNo38.t2 \ -padding 0 -sticky nsew -state normal -text Create -image {} \ - -compound none -underline -1 + -compound none -underline -1 set site_4_2 $top.tNo38.t2 label $site_4_2.lab38 \ -activebackground {#f9f9f9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text {For creating a new notepads managment.} + -text {For creating a new notepads managment.} vTcl:DefineAlias "$site_4_2.lab38" "Label4" vTcl:WidgetProc "Toplevel1" 1 button $site_4_2.but39 \ -activebackground {#d9d9d9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text {Create } + -text {Create } vTcl:DefineAlias "$site_4_2.but39" "Button6" vTcl:WidgetProc "Toplevel1" 1 bind $site_4_2.but39 { lambda e: create_button(e) } place $site_4_2.lab38 \ - -in $site_4_2 -x 50 -y 50 -anchor nw -bordermode ignore + -in $site_4_2 -x 50 -y 50 -anchor nw -bordermode ignore place $site_4_2.but39 \ - -in $site_4_2 -x 130 -y 90 -anchor nw -bordermode ignore + -in $site_4_2 -x 130 -y 90 -anchor nw -bordermode ignore button $top.but39 \ -activebackground {#d9d9d9} -activeforeground black \ -background {#d9d9d9} -foreground {#000000} -highlightcolor black \ - -text Exit + -text Exit vTcl:DefineAlias "$top.but39" "Button1" vTcl:WidgetProc "Toplevel1" 1 bind $top.but39 { lambda e: exit_button(e) } label $top.lab51 \ -activebackground {#f9f9f9} -activeforeground black \ - -background {#d9d9d9} -foreground {#000000} -highlightcolor black + -background {#d9d9d9} -foreground {#000000} -highlightcolor black vTcl:DefineAlias "$top.lab51" "errorOutput" vTcl:WidgetProc "Toplevel1" 1 ################### # SETTING GEOMETRY ################### place $top.tNo38 \ -in $top -x 10 -y 10 -width 582 -relwidth 0 -height 383 -relheight 0 \ - -anchor nw -bordermode ignore + -anchor nw -bordermode ignore place $top.but39 \ -in $top -x 240 -y 410 -width 117 -relwidth 0 -height 26 -relheight 0 \ - -anchor nw -bordermode ignore + -anchor nw -bordermode ignore place $top.lab51 \ -in $top -x 20 -y 410 -width 206 -relwidth 0 -height 18 -relheight 0 \ - -anchor nw -bordermode ignore + -anchor nw -bordermode ignore vTcl:FireEvent $base <> } @@ -302,4 +302,3 @@ Window show .top37 $btop if {$vTcl(borrow)} { $btop configure -background plum } - diff --git a/notepad/notepad_support.py b/notepad/notepad_support.py index 7851ca9991a..782ce80b49e 100644 --- a/notepad/notepad_support.py +++ b/notepad/notepad_support.py @@ -57,9 +57,9 @@ def create_button(p1): global cursor sql_command = """ - CREATE TABLE notes ( - id INTEGER PRIMARY KEY, - title TEXT, + CREATE TABLE notes ( + id INTEGER PRIMARY KEY, + title TEXT, note TEXT);""" try: diff --git a/nslookup_check.py b/nslookup_check.py index 4ae57f84cfc..a8298ee8fb3 100644 --- a/nslookup_check.py +++ b/nslookup_check.py @@ -12,5 +12,5 @@ for server in open("server_list.txt"): # Open the file and read each line subprocess.Popen( - ("nslookup " + server) + ("nslookup " + server), ) # Run the nslookup command for each server in the list diff --git a/num-py.py b/num-py.py index af365bd585d..fb992d8c141 100644 --- a/num-py.py +++ b/num-py.py @@ -1,12 +1,13 @@ import numpy as np + # to check if shape are equal and find there power def get_array(x, y): a = np.shape(x) b = np.shape(y) if a == b: - np_pow_array = x ** y + np_pow_array = x**y print("Array of powers without using np.power: ", np_pow_array) print("Array of powers using np.power: ", np.power(x, y)) diff --git a/number guessing.py b/number guessing.py index 25add25a64d..74a9ce68683 100644 --- a/number guessing.py +++ b/number guessing.py @@ -1,15 +1,24 @@ import random + attempts_list = [] + + def show_score(): if len(attempts_list) <= 0: print("There is currently no high score, it's yours for the taking!") else: - print("The current high score is {} attempts".format(min(attempts_list))) + print(f"The current high score is {min(attempts_list)} attempts") + + def start_game(): random_number = int(random.randint(1, 10)) print("Hello traveler! Welcome to the game of guesses!") player_name = input("What is your name? ") - wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name)) + wanna_play = input( + "Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format( + player_name + ) + ) # Where the show_score function USED to be attempts = 0 show_score() @@ -22,7 +31,7 @@ def start_game(): print("Nice! You got it!") attempts += 1 attempts_list.append(attempts) - print("It took you {} attempts".format(attempts)) + print(f"It took you {attempts} attempts") play_again = input("Would you like to play again? (Enter Yes/No) ") attempts = 0 show_score() @@ -38,8 +47,10 @@ def start_game(): attempts += 1 except ValueError as err: print("Oh no!, that is not a valid value. Try again...") - print("({})".format(err)) + print(f"({err})") else: print("That's cool, have a good one!") -if __name__ == '__main__': + + +if __name__ == "__main__": start_game() diff --git a/numberguessinggame/index.py b/numberguessinggame/index.py index 3116af47dce..ac8648e71e7 100644 --- a/numberguessinggame/index.py +++ b/numberguessinggame/index.py @@ -1,7 +1,8 @@ import random + def number_guessing_game(): - + secret_number = random.randint(1, 100) attempts = 0 @@ -18,11 +19,14 @@ def number_guessing_game(): elif guess > secret_number: print("Too high! Try again.") else: - print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts!") + print( + f"Congratulations! You guessed the number {secret_number} in {attempts} attempts!" + ) break except ValueError: print("Please enter a valid number.") + if __name__ == "__main__": number_guessing_game() diff --git a/numeric_password_cracker.py b/numeric_password_cracker.py index aaf48ac144d..2a6215c9a64 100644 --- a/numeric_password_cracker.py +++ b/numeric_password_cracker.py @@ -1,5 +1,6 @@ import itertools + def generate_password_permutations(length): # Generate numeric password permutations of the given length digits = "0123456789" @@ -7,6 +8,7 @@ def generate_password_permutations(length): password = "".join(combination) yield password + def password_cracker(target_password, max_length=8): # Try different password lengths and generate permutations for length in range(1, max_length + 1): @@ -16,6 +18,7 @@ def password_cracker(target_password, max_length=8): return password return None + if __name__ == "__main__": # Target numeric password (change this to the password you want to crack) target_password = "9133278" @@ -26,5 +29,6 @@ def password_cracker(target_password, max_length=8): if cracked_password: print(f"Password successfully cracked! The password is: {cracked_password}") else: - print("Password not found. Try increasing the max_length or target a different password.") - + print( + "Password not found. Try increasing the max_length or target a different password." + ) diff --git a/oneeven.py b/oneeven.py index 0c0a8c52530..18a1029eb2f 100644 --- a/oneeven.py +++ b/oneeven.py @@ -6,5 +6,5 @@ while number <= maximum: if number % 2 == 0: - print("{0}".format(number)) + print(f"{number}") number = number + 1 diff --git a/other_pepole/get_ip_gui b/other_pepole/get_ip_gui index 5728697ac5b..407008fce88 100755 --- a/other_pepole/get_ip_gui +++ b/other_pepole/get_ip_gui @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# -*- coding: utf-8 -*- import socket # **************** Modules Require *****************# @@ -12,19 +11,19 @@ from urllib.request import urlopen def get_wan_ip(): try: # get ip from http://ipecho.net/plain as text - wan_ip = urlopen('http://ipecho.net/plain').read().decode('utf-8') - res.configure(text='Wan IP is : ' + wan_ip, fg='#600') + wan_ip = urlopen("http://ipecho.net/plain").read().decode("utf-8") + res.configure(text="Wan IP is : " + wan_ip, fg="#600") except: - res.configure(text='Problem in source : http://ipecho.net/plain', fg='red') + res.configure(text="Problem in source : http://ipecho.net/plain", fg="red") # get local ip def get_local_ip(): try: - lan_ip = (socket.gethostbyname(socket.gethostname())) - res.configure(text='Local IP is : ' + lan_ip, fg='#600') + lan_ip = socket.gethostbyname(socket.gethostname()) + res.configure(text="Local IP is : " + lan_ip, fg="#600") except: - res.configure(text='Unkown Error', fg='#red') + res.configure(text="Unkown Error", fg="#red") # **************** about control button *****************# @@ -32,15 +31,19 @@ def get_local_ip(): def about(): global close_app, frame, info about_app.destroy() - frame = Frame(root, width=350, height=2, bg='blue') + frame = Frame(root, width=350, height=2, bg="blue") frame.grid(row=2, column=0, columnspan=4) - info = Label(root, text=""" - Practice Python + info = Label( + root, + text=""" + Practice Python Take idea from here : https://github.com/geekcomputers/Python/blob/master/myip.py - """, fg='#02F') + """, + fg="#02F", + ) info.grid(row=3, column=0, columnspan=4, padx=5) - close_app = Button(root, text='Close', command=close_about, bg='#55F') + close_app = Button(root, text="Close", command=close_about, bg="#55F") close_app.grid(row=4, column=0, columnspan=4, pady=5) @@ -50,19 +53,19 @@ def close_about(): info.destroy() frame.destroy() close_app.destroy() - about_app = Button(root, text='about', command=about) + about_app = Button(root, text="about", command=about) about_app.grid(row=1, column=2, padx=5, pady=5, sticky=W) # **************** Tkinter GUI *****************# root = Tk() -root.title('Khaled programing practice') +root.title("Khaled programing practice") # all buttons -res = Label(root, text='00.00.00.00', font=25) -res_wan_ip = Button(root, text='Get Wan IP', command=get_wan_ip) -res_local_ip = Button(root, text='Get Local IP', command=get_local_ip) -about_app = Button(root, text='about', command=about) -quit_app = Button(root, text='quit', command=quit, bg='#f40') +res = Label(root, text="00.00.00.00", font=25) +res_wan_ip = Button(root, text="Get Wan IP", command=get_wan_ip) +res_local_ip = Button(root, text="Get Local IP", command=get_local_ip) +about_app = Button(root, text="about", command=about) +quit_app = Button(root, text="quit", command=quit, bg="#f40") # method grid to install the button in window res.grid(row=0, column=0, columnspan=4, sticky=N, padx=10, pady=5) res_wan_ip.grid(row=1, column=0, padx=5, pady=5, sticky=W) diff --git a/pan.py b/pan.py index 92135935c64..468c152846a 100644 --- a/pan.py +++ b/pan.py @@ -122,11 +122,11 @@ "Gasper", "Betina", "Andres", - ] + ], ), "Age": pd.Series([25, 26, 25, 23, 30, 29, 23, 34, 40, 30, 51, 46]), "Rating": pd.Series( - [4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8, 3.78, 2.98, 4.80, 4.10, 3.65] + [4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8, 3.78, 2.98, 4.80, 4.10, 3.65], ), } df = pd.DataFrame(d) @@ -147,11 +147,11 @@ "Gasper", "Betina", "Andres", - ] + ], ), "Age": pd.Series([25, 26, 25, 23, 30, 29, 23, 34, 40, 30, 51, 46]), "Rating": pd.Series( - [4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8, 3.78, 2.98, 4.80, 4.10, 3.65] + [4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8, 3.78, 2.98, 4.80, 4.10, 3.65], ), } df = pd.DataFrame(d) @@ -225,7 +225,9 @@ # ........................MISSING DATA............................................# df = pd.DataFrame( - np.random.randn(3, 3), index=["a", "c", "e"], columns=["one", "two", "three"] + np.random.randn(3, 3), + index=["a", "c", "e"], + columns=["one", "two", "three"], ) df = df.reindex(["a", "b", "c"]) diff --git a/password_checker.py b/password_checker.py index afc5f7203ba..4fb610d90a8 100644 --- a/password_checker.py +++ b/password_checker.py @@ -1,24 +1,27 @@ import time -pwd="AKS2608" #any password u want to set + +pwd = "AKS2608" # any password u want to set + def IInd_func(): - count1=0 - for j in range(5): - a=0 - count=0 - user_pwd = input("") #password you remember - for i in range(len(pwd)): - if user_pwd[i] == pwd[a]: #comparing remembered pwd with fixed pwd - a +=1 - count+=1 - if count==len(pwd): - print("correct pwd") - break - else: - count1 += 1 - print("not correct") - if count1==5: - time.sleep(30) - IInd_func() + count1 = 0 + for j in range(5): + a = 0 + count = 0 + user_pwd = input("") # password you remember + for i in range(len(pwd)): + if user_pwd[i] == pwd[a]: # comparing remembered pwd with fixed pwd + a += 1 + count += 1 + if count == len(pwd): + print("correct pwd") + break + else: + count1 += 1 + print("not correct") + if count1 == 5: + time.sleep(30) + IInd_func() + IInd_func() diff --git a/password_cracker.py b/password_cracker.py index 3581fcc39f0..553e62928dd 100644 --- a/password_cracker.py +++ b/password_cracker.py @@ -1,5 +1,3 @@ -from __future__ import print_function - from sys import platform as _platform # Script Name : password_cracker.py @@ -23,7 +21,7 @@ def testPass(cryptPass): # Start the function salt = cryptPass[0:2] - dictFile = open("dictionary.txt", "r") # Open the dictionary file + dictFile = open("dictionary.txt") # Open the dictionary file for word in dictFile.readlines(): # Scan through the file word = word.strip("\n") cryptWord = crypt.crypt(word, salt) # Check for password in the file diff --git a/password_manager.py b/password_manager.py index cbbbcf87ef2..093c349bf88 100644 --- a/password_manager.py +++ b/password_manager.py @@ -1,6 +1,6 @@ +import os import sqlite3 from getpass import getpass -import os # set the environment variable ADMIN_PASS to your desired string, which will be your password. ADMIN_PASSWORD = os.environ["ADMIN_PASS"] @@ -88,7 +88,7 @@ def is_service_present(service_): (SERVICE TEXT PRIMARY KEY NOT NULL, USERNAME TEXT NOT NULL, PASSWORD TEXT NOT NULL); - """ + """, ) print("Your safe has been created!\nWhat would you like to store in it today?") except: @@ -124,7 +124,7 @@ def is_service_present(service_): add_password(service, username, password) print("\n" + service.capitalize() + " password stored\n") else: - print("Service named {} already exists.".format(service)) + print(f"Service named {service} already exists.") elif input_ == "get": service = input("What is the name of the service?\n") diff --git a/password_programs_multiple/animal_name_scraiper.py b/password_programs_multiple/animal_name_scraiper.py index 8204e90d794..3b7b816ae94 100644 --- a/password_programs_multiple/animal_name_scraiper.py +++ b/password_programs_multiple/animal_name_scraiper.py @@ -1,9 +1,9 @@ +import html5lib +import numpy as np +import pandas as pd import requests -from requests import get from bs4 import BeautifulSoup -import pandas as pd -import numpy as np -import html5lib +from requests import get # * Using html5lib as the parser is good # * It is the most lenient parser and works as @@ -32,7 +32,8 @@ # print(soup.find_all("h2", class_="wp-block-heading")) # az_title = soup.find_all("h2", class_="wp-block-heading") az_names = soup.find_all( - "div", class_="wp-block-column is-layout-flow wp-block-column-is-layout-flow" + "div", + class_="wp-block-column is-layout-flow wp-block-column-is-layout-flow", ) # az_title = soup # for title in az_title: @@ -51,7 +52,6 @@ while next_sibling and next_sibling.name == "br": next_sibling = next_sibling.next_sibling - # Print the text content of the next sibling element if next_sibling: print(next_sibling.text.strip()) diff --git a/password_programs_multiple/passwordGenerator.py b/password_programs_multiple/passwordGenerator.py index 1bde3d18051..1fdf944a99f 100644 --- a/password_programs_multiple/passwordGenerator.py +++ b/password_programs_multiple/passwordGenerator.py @@ -2,6 +2,7 @@ # modified Prince Gangurde 4/4/2020 from random import randint + import pycountry case = randint(1, 2) diff --git a/personal_translator.py b/personal_translator.py index 6a704d572c2..ff47da974c6 100644 --- a/personal_translator.py +++ b/personal_translator.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Personal_translator.ipynb Automatically generated by Colaboratory. @@ -12,6 +11,7 @@ from googletrans import Translator + # make a simple function that will translate any language to english def text_translator(Text): translator = Translator() @@ -20,7 +20,7 @@ def text_translator(Text): text_translator( - "Cidades brasileiras integram programa de preservação de florestas" + "Cidades brasileiras integram programa de preservação de florestas", ) # portuguese to english text_translator("Guten Morgen, wie gehts?") # german to english diff --git a/ph_email.py b/ph_email.py index 8656d489ce2..f9949a1231c 100755 --- a/ph_email.py +++ b/ph_email.py @@ -28,7 +28,7 @@ # email regex source : http://www.regexlib.com/REDetails.aspx?regexp_id=26 find_email = re.compile( r"""( - ([a-zA-Z0-9_\-\.]+) + ([a-zA-Z0-9_\-\.]+) @ ((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.) | diff --git a/ping_servers.py b/ping_servers.py index bce734e45e9..ae2f91ac843 100644 --- a/ping_servers.py +++ b/ping_servers.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os # Load the Library Module import subprocess # Load the Library Module import sys # Load the Library Module @@ -25,7 +23,7 @@ Followed by the site i.e. 155 - bromley""" + bromley""", ) sys.exit(0) else: @@ -37,7 +35,7 @@ "\nYou need to supply the app group. Usage : " + filename + " followed by the application group i.e. \n \t dms or \n \t swaps \n " - "then the site i.e. \n \t 155 or \n \t bromley" + "then the site i.e. \n \t 155 or \n \t bromley", ) appgroup = sys.argv[1] # Set the variable appgroup as the first argument you supply @@ -63,28 +61,33 @@ "ping_" + appgroup + "_" + site + ".log" ) # Set the variable logfile, using the arguments passed to create the logfile logfilename = os.path.join( - logdir, logfile + logdir, + logfile, ) # Set the variable logfilename by joining logdir and logfile together confdir = os.getenv( - "my_config" + "my_config", ) # Set the variable confdir from the OS environment variable - 1.2 conffile = appgroup + "_servers_" + site + ".txt" # Set the variable conffile - 1.2 conffilename = os.path.join( - confdir, conffile + confdir, + conffile, ) # Set the variable conffilename by joining confdir and conffile together - 1.2 f = open(logfilename, "w") # Open a logfile to write out the output for server in open(conffilename): # Open the config file and read each line - 1.2 ret = subprocess.call( - myping + server, shell=True, stdout=f, stderr=subprocess.STDOUT + myping + server, + shell=True, + stdout=f, + stderr=subprocess.STDOUT, ) # Run the ping command for each server in the list. if ret == 0: # Depending on the response f.write( - server.strip() + " is alive" + "\n" + server.strip() + " is alive" + "\n", ) # Write out that you can receive a reponse else: f.write( - server.strip() + " did not respond" + "\n" + server.strip() + " did not respond" + "\n", ) # Write out you can't reach the box print("\n\tYou can see the results in the logfile : " + logfilename) diff --git a/ping_subnet.py b/ping_subnet.py index e8eb28d933f..bdfd2cd4a2c 100644 --- a/ping_subnet.py +++ b/ping_subnet.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os # Load the Library Module import subprocess # Load the Library Module import sys # Load the Library Module @@ -21,7 +19,7 @@ """ You need to supply the first octets of the address Usage : """ + filename - + """ 111.111.111 """ + + """ 111.111.111 """, ) sys.exit(0) else: @@ -32,7 +30,7 @@ sys.exit( " You need to supply the first octets of the address Usage : " + filename - + " 111.111.111" + + " 111.111.111", ) subnet = sys.argv[1] # Set the variable subnet as the three octets you pass it @@ -52,9 +50,9 @@ ) # Run the command pinging the servers if ret == 0: # Depending on the response f.write( - subnet + "." + str(ip) + " is alive" + "\n" + subnet + "." + str(ip) + " is alive" + "\n", ) # Write out that you can receive a reponse else: f.write( - subnet + "." + str(ip) + " did not respond" + "\n" + subnet + "." + str(ip) + " did not respond" + "\n", ) # Write out you can't reach the box diff --git a/polygon.py b/polygon.py index ba300f8a317..d22702900ef 100644 --- a/polygon.py +++ b/polygon.py @@ -1,5 +1,6 @@ -import pygame import sys + +import pygame from pygame.locals import * pygame.init() diff --git a/portscanner.py b/portscanner.py index 78fcde14a26..8e51c022cff 100644 --- a/portscanner.py +++ b/portscanner.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import optparse # Import the module from socket import * # Import the module from threading import * # Import the module diff --git a/power_of_n.py b/power_of_n.py index 69b8994be94..f0800006682 100644 --- a/power_of_n.py +++ b/power_of_n.py @@ -3,6 +3,7 @@ __version__ = "1.0.0" __date__ = "2023-09-03" + def binaryExponentiation(x: float, n: int) -> float: """ Function to calculate x raised to the power n (i.e., x^n) where x is a float number and n is an integer and it will return float value @@ -49,10 +50,9 @@ def binaryExponentiation(x: float, n: int) -> float: print(f"Version: {__version__}") print(f"Function Documentation: {binaryExponentiation.__doc__}") print(f"Date: {__date__}") - - print() # Blank Line + + print() # Blank Line print(binaryExponentiation(2.00000, 10)) print(binaryExponentiation(2.10000, 3)) print(binaryExponentiation(2.00000, -2)) - \ No newline at end of file diff --git a/powerdown_startup.py b/powerdown_startup.py index 7ce5f163c69..08d342b691f 100644 --- a/powerdown_startup.py +++ b/powerdown_startup.py @@ -16,7 +16,7 @@ def windows(): # This is the function to run if it detects the OS is windows. f = open("server_startup_" + strftime("%Y-%m-%d") + ".log", "a") # Open the logfile for server in open( - "startup_list.txt", "r" + "startup_list.txt", ): # Read the list of servers from the list ret = subprocess.call( "ping -n 3 %s" % server, @@ -26,12 +26,12 @@ def windows(): # This is the function to run if it detects the OS is windows. ) # Ping the servers in turn if ret == 0: # If you get a response. f.write( - "%s: is alive, loading PuTTY session" % server.strip() + "\n" + "%s: is alive, loading PuTTY session" % server.strip() + "\n", ) # Write out to the logfile - subprocess.Popen(("putty -load " + server)) # Load the putty session + subprocess.Popen("putty -load " + server) # Load the putty session else: f.write( - "%s : did not respond" % server.strip() + "\n" + "%s : did not respond" % server.strip() + "\n", ) # Write to the logfile if the server is down diff --git a/powers of 2.py b/powers of 2.py index 5ac0e09fc36..919f1e1528f 100644 --- a/powers of 2.py +++ b/powers of 2.py @@ -6,8 +6,8 @@ # terms = int(input("How many terms? ")) # use anonymous function -result = list(map(lambda x: 2 ** x, range(terms))) +result = list(map(lambda x: 2**x, range(terms))) -print("The total terms are:",terms) +print("The total terms are:", terms) for i in range(terms): - print("2 raised to power",i,"is",result[i]) + print("2 raised to power", i, "is", result[i]) diff --git a/powerup_checks.py b/powerup_checks.py index b29cd43ba61..efd56427118 100644 --- a/powerup_checks.py +++ b/powerup_checks.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os # Load the Library Module import sqlite3 # Load the Library Module import subprocess # Load the Library Module @@ -15,18 +13,20 @@ # Description : Creates an output file by pulling all the servers for the given site from SQLITE database, then goes through the list pinging the servers to see if they are up on the network dropbox = os.getenv( - "dropbox" + "dropbox", ) # Set the variable, by getting the value of the variable from the OS config = os.getenv( - "my_config" + "my_config", ) # Set the variable, by getting the value of the variable from the OS dbfile = "Databases/jarvis.db" # Set the variable to the database master_db = os.path.join( - dropbox, dbfile + dropbox, + dbfile, ) # Create the variable by linking the path and the file listfile = "startup_list.txt" # File that will hold the servers serverfile = os.path.join( - config, listfile + config, + listfile, ) # Create the variable by linking the path and the file outputfile = "server_startup_" + strftime("%Y-%m-%d-%H-%M") + ".log" @@ -34,7 +34,7 @@ text = """ -You need to pass an argument, the options the script expects is +You need to pass an argument, the options the script expects is -site1 For the Servers relating to site1 -site2 For the Servers located in site2""" @@ -42,7 +42,7 @@ def windows(): # This is the function to run if it detects the OS is windows. f = open(outputfile, "a") # Open the logfile - for server in open(serverfile, "r"): # Read the list of servers from the list + for server in open(serverfile): # Read the list of servers from the list # ret = subprocess.call("ping -n 3 %s" % server.strip(), shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn ret = subprocess.call( "ping -n 3 %s" % server.strip(), @@ -51,17 +51,17 @@ def windows(): # This is the function to run if it detects the OS is windows. ) # Ping the servers in turn if ret == 0: # Depending on the response f.write( - "%s: is alive" % server.strip().ljust(15) + "\n" + "%s: is alive" % server.strip().ljust(15) + "\n", ) # Write out to the logfile is the server is up else: f.write( - "%s: did not respond" % server.strip().ljust(15) + "\n" + "%s: did not respond" % server.strip().ljust(15) + "\n", ) # Write to the logfile if the server is down def linux(): # This is the function to run if it detects the OS is nix. f = open("server_startup_" + strftime("%Y-%m-%d") + ".log", "a") # Open the logfile - for server in open(serverfile, "r"): # Read the list of servers from the list + for server in open(serverfile): # Read the list of servers from the list ret = subprocess.call( "ping -c 3 %s" % server, shell=True, @@ -70,11 +70,11 @@ def linux(): # This is the function to run if it detects the OS is nix. ) # Ping the servers in turn if ret == 0: # Depending on the response f.write( - "%s: is alive" % server.strip().ljust(15) + "\n" + "%s: is alive" % server.strip().ljust(15) + "\n", ) # Write out to the logfile is the server is up else: f.write( - "%s: did not respond" % server.strip().ljust(15) + "\n" + "%s: did not respond" % server.strip().ljust(15) + "\n", ) # Write to the logfile if the server is down @@ -82,7 +82,8 @@ def get_servers(query): # Function to get the servers from the database conn = sqlite3.connect(master_db) # Connect to the database cursor = conn.cursor() # Create the cursor cursor.execute( - "select hostname from tp_servers where location =?", (query,) + "select hostname from tp_servers where location =?", + (query,), ) # SQL Statement print("\nDisplaying Servers for : " + query + "\n") while True: # While there are results @@ -120,7 +121,7 @@ def main(): # Main Function query = "site2" # Set the variable to have the value bromley else: print( - "\n[-] Unknown option [-] " + text + "\n[-] Unknown option [-] " + text, ) # If an unknown option is passed, let the user know sys.exit(0) get_servers(query) # Call the get servers funtion, with the value from the argument @@ -131,7 +132,7 @@ def main(): # Main Function windows() # Call the windows function print( - "\n[+] Check the log file " + outputfile + " [+]\n" + "\n[+] Check the log file " + outputfile + " [+]\n", ) # Display the name of the log diff --git a/primelib/Prime.txt b/primelib/Prime.txt index 801324b3c35..935cb01109d 100644 --- a/primelib/Prime.txt +++ b/primelib/Prime.txt @@ -15,7 +15,7 @@ if num > 1: break else: print(num,"is a prime number") - + # if input number is less than # or equal to 1, it is not prime else: diff --git a/primelib/README b/primelib/README index 321fb4bb19a..b37e63e6ff5 100644 --- a/primelib/README +++ b/primelib/README @@ -1,7 +1,7 @@ Free open-source library from Christian Bender This python library contains some useful functions to deal with -prime numbers and whole numbers. +prime numbers and whole numbers. The file primelib.py or primliby.pyc will simply import by the import-statement. Important primelib.py or primelib.pyc must been in your project directory. @@ -13,11 +13,11 @@ import primelib print primelib.isPrime(13) // will print out 'True' print primelib.primeFactorization(40) // will print out [2,2,2,5] -OR +OR from primelib import * -print isPrime(...) +print isPrime(...) More information about the functions. @@ -44,9 +44,9 @@ sieveEr (N) input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. - + This function implements the algorithm called -sieve of erathostenes. +sieve of erathostenes. --------------------------- @@ -61,7 +61,7 @@ This function is more efficient as function sieveEr(...) primeFactorization (number) -input: positive integer 'number' +input: positive integer 'number' returns a list of the prime number factors of 'number' ------------------------------- @@ -82,7 +82,7 @@ returns the smallest prime number factor of 'number' getPrime (n) -Gets the n-th prime-number. +Gets the n-th prime-number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 @@ -94,7 +94,7 @@ getPrimesBetween (pNumber1, pNumber2) input: prime numbers 'pNumber1' and 'pNumber2' precondition: pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusiv) - and 'pNumber2' (exclusiv) + and 'pNumber2' (exclusiv) -------------------------------------- diff --git a/primelib/primelib.py b/primelib/primelib.py index 65856679561..7ba5685d67a 100644 --- a/primelib/primelib.py +++ b/primelib/primelib.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Created on Thu Oct 5 16:44:23 2017 @@ -16,7 +15,7 @@ greatestPrimeFactor(number) smallestPrimeFactor(number) getPrime(n) -getPrimesBetween(pNumber1, pNumber2) +getPrimesBetween(pNumber1, pNumber2) ---- @@ -46,12 +45,13 @@ def pi(maxK=70, prec=1008, disp=1007): prec: precision of decimal places disp: number of decimal places shown """ - from decimal import Decimal as Dec, getcontext as gc + from decimal import Decimal as Dec + from decimal import getcontext as gc gc().prec = prec K, M, L, X, S = 6, 1, 13591409, 1, 13591409 for k in range(1, maxK + 1): - M = Dec((K ** 3 - (K << 4)) * M / k ** 3) + M = Dec((K**3 - (K << 4)) * M / k**3) L += 545140134 X *= -262537412640768000 S += Dec(M * L) / X @@ -475,7 +475,7 @@ def getPrime(n): # precondition assert isinstance(ans, int) and isPrime( - ans + ans, ), "'ans' must been a prime number and from type int" return ans diff --git a/print hello world.py b/print hello world.py index 0e3295e312d..1d6d4214987 100644 --- a/print hello world.py +++ b/print hello world.py @@ -1,3 +1,3 @@ # This program prints Hello, world! -print('Hello, world!') +print("Hello, world!") diff --git a/prison_break_scrapper.py b/prison_break_scrapper.py index ad50636cd6a..fdc8966966e 100644 --- a/prison_break_scrapper.py +++ b/prison_break_scrapper.py @@ -2,6 +2,7 @@ Scrapper for downloading prison break series from an open server and putting them in a designated folder. """ + import os import subprocess @@ -14,7 +15,7 @@ def download_files(links, idx): for link in links: subprocess.call( - ["aria2c", "-s", "16", "-x", "16", "-d", "season" + str(idx), link] + ["aria2c", "-s", "16", "-x", "16", "-d", "season" + str(idx), link], ) diff --git a/psunotify.py b/psunotify.py index 5e95769a916..06a927ff90b 100644 --- a/psunotify.py +++ b/psunotify.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import re import mechanize @@ -10,17 +8,17 @@ ( "User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36", - ) + ), ] br.set_handle_robots(False) # For page exploration page = input("Enter Page No:") # print type(page) p = urllib2.Request( - "https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start=" + page + "https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start=" + page, ) ht = br.open(p) -text = '(.+?)' +text = r'(.+?)' patt = re.compile(text) h = ht.read() urls = re.findall(patt, h) @@ -48,5 +46,5 @@ except urllib2.URLError as e: print( "Sorry there exists a problem with this URL Please Download this Manually " - + str(url) + + str(url), ) diff --git a/puttylogs.py b/puttylogs.py index 6e4c67a4784..e24dffa9ed0 100644 --- a/puttylogs.py +++ b/puttylogs.py @@ -13,8 +13,8 @@ import shutil # Load the Library Module - 1.2 from time import strftime # Load just the strftime Module from Time -logsdir = "c:\logs\puttylogs" # Set the Variable logsdir -zipdir = "c:\logs\puttylogs\zipped_logs" # Set the Variable zipdir - 1.2 +logsdir = r"c:\logs\puttylogs" # Set the Variable logsdir +zipdir = r"c:\logs\puttylogs\zipped_logs" # Set the Variable zipdir - 1.2 zip_program = "zip.exe" # Set the Variable zip_program - 1.1 for files in os.listdir(logsdir): # Find all the files in the directory @@ -24,9 +24,10 @@ ) # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension os.chdir(logsdir) # Change directory to the logsdir os.system( - zip_program + " " + files1 + " " + files + zip_program + " " + files1 + " " + files, ) # Zip the logs into dated zip files for each server. - 1.1 shutil.move( - files1, zipdir + files1, + zipdir, ) # Move the zipped log files to the zipped_logs directory - 1.2 os.remove(files) # Remove the original log files diff --git a/pyauto.py b/pyauto.py index 7f9a19e0e77..84ad25f3233 100644 --- a/pyauto.py +++ b/pyauto.py @@ -1,9 +1,9 @@ # Author-Slayking1965 # email-kingslayer8509@gmail.com import random -import pyautogui import string +import pyautogui chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" diff --git a/python Space Invader game.py b/python Space Invader game.py index 2d07677f67e..35ac5f75769 100644 --- a/python Space Invader game.py +++ b/python Space Invader game.py @@ -1,6 +1,7 @@ -import pygame -import random import math +import random + +import pygame from pygame import mixer # initialization @@ -12,19 +13,19 @@ # background -background = pygame.image.load('background.png') +background = pygame.image.load("background.png") -#bg sound -mixer.music.load('background.wav') +# bg sound +mixer.music.load("background.wav") mixer.music.play(-1) # title and icon pygame.display.set_caption("Space Invendera") -icon = pygame.image.load('battleship.png') +icon = pygame.image.load("battleship.png") pygame.display.set_icon(icon) # player -playerimg = pygame.image.load('transport.png') +playerimg = pygame.image.load("transport.png") playerx = 370 playery = 480 playerx_change = 0 @@ -38,37 +39,40 @@ number_of_enemies = 6 for i in range(number_of_enemies): - enemyimg.append(pygame.image.load('enemy.png')) + enemyimg.append(pygame.image.load("enemy.png")) enemyx.append(random.randint(0, 800)) enemyy.append(random.randint(50, 150)) enemyx_change.append(2.5) enemyy_change.append(40) # bullet -bulletimg = pygame.image.load('bullet.png') +bulletimg = pygame.image.load("bullet.png") bulletx = 0 bullety = 480 bulletx_change = 0 bullety_change = 10 bullet_state = "ready" -#score +# score score_value = 0 -font = pygame.font.Font('freesansbold.ttf',32) +font = pygame.font.Font("freesansbold.ttf", 32) textx = 10 texty = 10 -#game over txt -over_font = pygame.font.Font('freesansbold.ttf',64) +# game over txt +over_font = pygame.font.Font("freesansbold.ttf", 64) -def show_score(x ,y): - score = font.render("score :"+ str(score_value),True, (255, 255, 255)) + +def show_score(x, y): + score = font.render("score :" + str(score_value), True, (255, 255, 255)) screen.blit(score, (x, y)) + def game_over_text(): over_txt = over_font.render("GAME OVER", True, (255, 255, 255)) screen.blit(over_txt, (200, 250)) + # for display player img def player(x, y): screen.blit(playerimg, (x, y)) @@ -76,7 +80,8 @@ def player(x, y): # foe desplaing enemy img -def enemy(x, y ,i): + +def enemy(x, y, i): screen.blit(enemyimg[i], (x, y)) @@ -87,7 +92,9 @@ def fire_bullet(x, y): def iscollision(enemyx, enemyy, bulletx, bullety): - distance = math.sqrt((math.pow(enemyx - bulletx, 2)) + (math.pow(enemyy - bullety, 2))) + distance = math.sqrt( + (math.pow(enemyx - bulletx, 2)) + (math.pow(enemyy - bullety, 2)) + ) if distance < 27: return True else: @@ -107,20 +114,20 @@ def iscollision(enemyx, enemyy, bulletx, bullety): running = False # if keystroke in pressed whether it is right of left - if (event.type == pygame.KEYDOWN): - if (event.key == pygame.K_LEFT): + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_LEFT: playerx_change = -5 - if (event.key == pygame.K_RIGHT): + if event.key == pygame.K_RIGHT: playerx_change = 5 - if (event.key == pygame.K_SPACE): + if event.key == pygame.K_SPACE: if bullet_state == "ready": - bullet_sound = mixer.Sound('laser.wav') + bullet_sound = mixer.Sound("laser.wav") bullet_sound.play() bulletx = playerx fire_bullet(bulletx, bullety) - if (event.type == pygame.KEYUP): + if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerx_change = 0 @@ -133,7 +140,7 @@ def iscollision(enemyx, enemyy, bulletx, bullety): for i in range(number_of_enemies): - #game over + # game over if enemyy[i] > 440: for j in range(number_of_enemies): enemyy[j] = 2000 @@ -152,7 +159,7 @@ def iscollision(enemyx, enemyy, bulletx, bullety): # collision collision = iscollision(enemyx[i], enemyy[i], bulletx, bullety) if collision: - explossion_sound = mixer.Sound('explosion.wav') + explossion_sound = mixer.Sound("explosion.wav") explossion_sound.play() bullety = 480 bullet_state = "ready" @@ -172,5 +179,5 @@ def iscollision(enemyx, enemyy, bulletx, bullety): bullety -= bullety_change player(playerx, playery) - show_score(textx,texty) + show_score(textx, texty) pygame.display.update() diff --git a/python program for finding square root for positive number.py b/python program for finding square root for positive number.py index dcb8251f839..7d7414dc26a 100644 --- a/python program for finding square root for positive number.py +++ b/python program for finding square root for positive number.py @@ -1,10 +1,10 @@ # Python Program to calculate the square root # Note: change this value for a different result -num = 8 +num = 8 # To take the input from the user -#num = float(input('Enter a number: ')) +# num = float(input('Enter a number: ')) -num_sqrt = num ** 0.5 -print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) +num_sqrt = num**0.5 +print("The square root of {:0.3f} is {:0.3f}".format(num, num_sqrt)) diff --git a/python_sms.py b/python_sms.py index b5e578b3b86..62aa6ce9fcb 100644 --- a/python_sms.py +++ b/python_sms.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os import sqlite3 import urllib # URL functions @@ -35,9 +33,7 @@ sname = row[0] snumber = row[1] - message = ( - f"{sname} There will be NO training tonight on the {tdate}. Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated" - ) + message = f"{sname} There will be NO training tonight on the {tdate}. Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated" username = "YOUR_USERNAME" sender = "WHO_IS_SENDING_THE_MAIL" @@ -67,9 +63,9 @@ postdata = urllib.urlencode(values) req = urllib2.Request(url, postdata) - print( f"Attempting to send SMS to {sname} at {snumber} on {tdate}") + print(f"Attempting to send SMS to {sname} at {snumber} on {tdate}") f.write( - f"Attempting to send SMS to {sname} at {snumber} on {tdate}" + f"Attempting to send SMS to {sname} at {snumber} on {tdate}", ) try: diff --git a/python_webscraper.py b/python_webscraper.py index a9322761a1c..fab418247d5 100644 --- a/python_webscraper.py +++ b/python_webscraper.py @@ -1,19 +1,20 @@ import requests from bs4 import BeautifulSoup + # Make a request on to your website page = requests.get("Paste your Website Domain here") -soup = BeautifulSoup(page.content, 'html.parser') +soup = BeautifulSoup(page.content, "html.parser") # Create all_h1_tags as empty list all_h1_tags = [] # Set all_h1_tags to all h1 tags of the soup -for element in soup.select('h1'): +for element in soup.select("h1"): all_h1_tags.append(element.text) # Create seventh_p_text and set it to 7th p element text of the page -seventh_p_text = soup.select('p')[6].text +seventh_p_text = soup.select("p")[6].text print(all_h1_tags, seventh_p_text) -# print all h1 elements and the text of the website on your console +# print all h1 elements and the text of the website on your console diff --git a/quiz_game.py b/quiz_game.py index c1ffd6696b0..cd2a8aff48c 100644 --- a/quiz_game.py +++ b/quiz_game.py @@ -1,32 +1,37 @@ -print('Welcome to AskPython Quiz') -answer=input('Are you ready to play the Quiz ? (yes/no) :') -score=0 -total_questions=3 - -if answer.lower()=='yes': - answer=input('Question 1: What is your Favourite programming language?') - if answer.lower()=='python': +print("Welcome to AskPython Quiz") +answer = input("Are you ready to play the Quiz ? (yes/no) :") +score = 0 +total_questions = 3 + +if answer.lower() == "yes": + answer = input("Question 1: What is your Favourite programming language?") + if answer.lower() == "python": score += 1 - print('correct') + print("correct") else: - print('Wrong Answer :(') - - - answer=input('Question 2: Do you follow any author on AskPython? ') - if answer.lower()=='yes': + print("Wrong Answer :(") + + answer = input("Question 2: Do you follow any author on AskPython? ") + if answer.lower() == "yes": score += 1 - print('correct') + print("correct") else: - print('Wrong Answer :(') - - answer=input('Question 3: What is the name of your favourite website for learning Python?') - if answer.lower()=='askpython': + print("Wrong Answer :(") + + answer = input( + "Question 3: What is the name of your favourite website for learning Python?" + ) + if answer.lower() == "askpython": score += 1 - print('correct') + print("correct") else: - print('Wrong Answer :(') - -print('Thankyou for Playing this small quiz game, you attempted',score,"questions correctly!") -mark=(score/total_questions)*100 -print('Marks obtained:',mark) -print('BYE!') \ No newline at end of file + print("Wrong Answer :(") + +print( + "Thankyou for Playing this small quiz game, you attempted", + score, + "questions correctly!", +) +mark = (score / total_questions) * 100 +print("Marks obtained:", mark) +print("BYE!") diff --git a/quote.py b/quote.py index ed3b1b1317f..f4feab06818 100644 --- a/quote.py +++ b/quote.py @@ -5,9 +5,10 @@ example quote -Quote Author Name """ -import requests from json import loads +import requests + def return_quote(): response = requests.get("https://zenquotes.io/api/random") diff --git a/random-sentences.py b/random-sentences.py index 3e6e8baacb7..f296b398d00 100644 --- a/random-sentences.py +++ b/random-sentences.py @@ -40,4 +40,4 @@ def random_sentence(): story = (". ").join(list(map(lambda x: random_sentence(), range(0, 20)))) # prints random sentences story -print("{}".format(story)) +print(f"{story}") diff --git a/random_file_move.py b/random_file_move.py index f8a2af7704e..0a5a4204325 100644 --- a/random_file_move.py +++ b/random_file_move.py @@ -6,15 +6,16 @@ # Description : This will move specified number of files(given in ratio) from the src directory to dest directory. -import os, random import argparse +import os +import random def check_ratio(x): try: x = float(x) except ValueError: - raise argparse.ArgumentTypeError("%r not a floating-point literal" % (x,)) + raise argparse.ArgumentTypeError("{!r} not a floating-point literal".format(x)) if x < 0.0 or x > 1.0: raise argparse.ArgumentTypeError("%r not in range [0.0, 1.0]" % (x)) @@ -56,7 +57,7 @@ def check_ratio(x): files = os.listdir(src) size = int(ratio * len(files)) -print("Move {} files from {} to {} ? [y/n]".format(size, src, dest)) +print(f"Move {size} files from {src} to {dest} ? [y/n]") if input().lower() == "y": for f in random.sample(files, size): try: diff --git a/randomloadingmessage.py b/randomloadingmessage.py index 71654d249b0..098d3079005 100644 --- a/randomloadingmessage.py +++ b/randomloadingmessage.py @@ -25,7 +25,7 @@ print("Have a good day.") if num == 9: print( - "Upgrading Windows, your PC will restart several times. Sit back and relax." + "Upgrading Windows, your PC will restart several times. Sit back and relax.", ) if num == 10: print("The architects are still drafting.") diff --git a/rangoli.py b/rangoli.py index 75191e08546..0fc7ccccc10 100644 --- a/rangoli.py +++ b/rangoli.py @@ -3,7 +3,7 @@ # Prints a rangoli of size n def print_rangoli(n): - """Prints a rangoli of size n""" + """Prints a rangoli of size n""" # Width of the rangoli width = 4 * n - 3 @@ -40,6 +40,6 @@ def print_rangoli(n): string = "" -if __name__ == '__main__': +if __name__ == "__main__": n = int(input()) print_rangoli(n) diff --git a/rearrange-files/rearrange-files.py b/rearrange-files/rearrange-files.py index 5d12baec51f..3481639b31e 100644 --- a/rearrange-files/rearrange-files.py +++ b/rearrange-files/rearrange-files.py @@ -6,7 +6,7 @@ import shutil -class RearrangeFile(object): +class RearrangeFile: def __init__(self): self.folder_path = os.getcwd() self.list_of_all_files = os.listdir(self.folder_path) diff --git a/recursiveStrings.py b/recursiveStrings.py index 874a1b0a104..faa8e894d69 100644 --- a/recursiveStrings.py +++ b/recursiveStrings.py @@ -1,6 +1,6 @@ -""" author: Ataba29 +""" author: Ataba29 code has a matrix each list inside of the matrix has two strings -the code determines if the two strings are similar or different +the code determines if the two strings are similar or different from each other recursively """ @@ -9,19 +9,25 @@ def CheckTwoStrings(str1, str2): # function takes two strings and check if they are similar # returns True if they are identical and False if they are different - if(len(str1) != len(str2)): + if len(str1) != len(str2): return False - if(len(str1) == 1 and len(str2) == 1): + if len(str1) == 1 and len(str2) == 1: return str1[0] == str2[0] return (str1[0] == str2[0]) and CheckTwoStrings(str1[1:], str2[1:]) def main(): - matrix = [["hello", "wow"], ["ABSD", "ABCD"], - ["List", "List"], ["abcspq", "zbcspq"], - ["1263", "1236"], ["lamar", "lamars"], - ["amczs", "amczs"], ["yeet", "sheesh"], ] + matrix = [ + ["hello", "wow"], + ["ABSD", "ABCD"], + ["List", "List"], + ["abcspq", "zbcspq"], + ["1263", "1236"], + ["lamar", "lamars"], + ["amczs", "amczs"], + ["yeet", "sheesh"], + ] for i in matrix: if CheckTwoStrings(i[0], i[1]): diff --git a/recyclebin.py b/recyclebin.py index 83222be716e..7cf2422ef13 100644 --- a/recyclebin.py +++ b/recyclebin.py @@ -1,10 +1,7 @@ -from __future__ import print_function - import os # Load the Module from _winreg import * # Load the Module - # Script Name : recyclebin.py # Author : Craig Richards # Created : 07th June 2013 @@ -18,7 +15,7 @@ def sid2user(sid): # Start of the function to gather the user try: key = OpenKey( HKEY_LOCAL_MACHINE, - "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + "\\" + sid, + r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + "\\" + sid, ) (value, type) = QueryValueEx(key, "ProfileImagePath") user = value.split("\\")[-1] diff --git a/remove a character from a file and rewrite.py b/remove a character from a file and rewrite.py index 18029c53db2..201e8f6ec8b 100644 --- a/remove a character from a file and rewrite.py +++ b/remove a character from a file and rewrite.py @@ -1,28 +1,28 @@ -#Remove all the lines that contain the character `a' in a file and write it to another file. -f=open("test1.txt","r") #opening file test1.txt -lines = f.readlines() #saved lines +# Remove all the lines that contain the character `a' in a file and write it to another file. +f = open("test1.txt") # opening file test1.txt +lines = f.readlines() # saved lines print("Original file is :") print(lines) f.close() - -# Rewriting lines -e=open("test3.txt","w") # file containing lines with 'a' -f=open("test1.txt","w") # file containing lines without 'a' +# Rewriting lines + +e = open("test3.txt", "w") # file containing lines with 'a' +f = open("test1.txt", "w") # file containing lines without 'a' for line in lines: - if 'a' in line or 'A' in line: - e.write(line) - else: - f.write(line) - + if "a" in line or "A" in line: + e.write(line) + else: + f.write(line) + e.close() -f.close() +f.close() -f=open("test1.txt","r") -lines=f.readlines() +f = open("test1.txt") +lines = f.readlines() -e=open("test3.txt","r") -lines1=e.readlines() +e = open("test3.txt") +lines1 = e.readlines() print("\n") diff --git a/replacetext.py b/replacetext.py index 4901df276be..2784ee303df 100644 --- a/replacetext.py +++ b/replacetext.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# -*- coding: utf-8 -*- # program to replace all the spaces in an entered string with a hyphen"-" def replacetext(string): string = string.replace(" ", "-") diff --git a/requirements.txt b/requirements.txt index ba601b8c8ab..0be9b003944 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,113 +1,113 @@ -pafy aiohttp -fuzzywuzzy -hupper -seaborn -time -simplegui -utils -Tubes -modules -pdf2docx -pong +APScheduler +auto-mix-prep +backend +background +Ball beautifulsoup4 -dictator +bird caller -watchdog -PyQt5 -numpy -fileinfo -backend -win10toast +ccxt +colorama Counter -Flask -selenium +dictator +Django +docx +emoji +fastapi +fileinfo firebase-admin -ujson -requests -quo -PyPDF2 -pyserial -twilio -tabula -nltk -Pillow -SocksiPy-branch -xlrd +fitz +Flask +Flask-Ask fpdf -mysql-connector-repackaged -word2number -tornado -obs -todo -oauth2client +freegames +fuzzywuzzy +geocoder +google-api-python-client +googletrans +gTTS +httplib2 +hupper keras -pymongo -playsound -pyttsx3 -auto-mix-prep lib -pywifi -patterns +matplotlib +mechanize +mediapipe +Menu +modules +mutagen +mysql-connector-repackaged +newspaper +nltk +numpy +oauth2client +obs openai -background -pydantic +opencv-python openpyxl +pafy +pandas +patterns +pdf2docx +Pillow +playsound +plyer +pong +protobuf +psutil +PyAutoGUI +pydantic +pygame +pyglet +pymongo +pynput +PyPDF2 +pyperclip +PyQRCode +PyQt5 +pyserial +pyshorteners pytesseract +pytest +pyttsx3 +pytube +pywhatkit +pywifi +qrcode +quo +requests requests-mock -pyglet -urllib3 -thirdai -google-api-python-client +rich +seaborn +selenium +simplegui +slab +SocksiPy-branch +solara sound -xlwt -pygame speechtotext -wikipedia -tqdm -Menu -yfinance -tweepy +tabula +tensorflow +thirdai +time tkcalendar -pytube -xor-cipher -bird -mechanize +todo +tornado +tqdm translate -solara -pywhatkit -mutagen +Tubes +tweepy +twilio +ujson Unidecode -Ball -pynput -gTTS -ccxt -fitz -fastapi -Django -docx -matplotlib -pyshorteners -geocoder -APScheduler -PyQRCode -freegames -pyperclip -newspaper -opencv-python -tensorflow -pandas -pytest -qrcode -googletrans -slab -psutil -mediapipe -rich -httplib2 -protobuf -colorama -plyer -Flask-Ask -emoji -PyAutoGUI +urllib3 +utils +watchdog +wikipedia +win10toast +word2number +xlrd +xlwt +xor-cipher +yfinance diff --git a/requirements_with_versions.txt b/requirements_with_versions.txt index 9b9bc416c4e..067940ef3c4 100644 --- a/requirements_with_versions.txt +++ b/requirements_with_versions.txt @@ -1,113 +1,113 @@ -pafy==0.5.5 aiohttp==3.9.3 -fuzzywuzzy==0.18.0 -hupper==1.12.1 -seaborn==0.13.1 -time==1.0.0 -simplegui==0.1.1 -utils==1.0.2 -Tubes==0.2.1 -modules==1.0.0 -pdf2docx==0.5.8 -pong==1.5 +APScheduler==3.10.4 +auto-mix-prep==0.2.0 +backend==0.2.4.1 +background==0.2.1 +Ball==0.2.9 beautifulsoup4==4.12.3 -dictator==0.3.1 +bird==0.1.2 caller==0.0.2 -watchdog==3.0.0 -PyQt5==5.15.10 -numpy==1.26.4 -fileinfo==0.3.3 -backend==0.2.4.1 -win10toast==0.9 +ccxt==4.3.18 +colorama==0.4.6 Counter==1.0.0 -Flask==3.0.2 -selenium==4.16.0 +dictator==0.3.1 +Django==5.0.5 +docx==0.2.4 +emoji==2.11.1 +fastapi==0.109.0 +fileinfo==0.3.3 firebase-admin==6.5.0 -ujson==5.9.0 -requests==2.31.0 -quo==2023.5.1 -PyPDF2==3.0.1 -pyserial==3.5 -twilio==9.0.0 -tabula==1.0.5 -nltk==3.8.1 -Pillow==10.2.0 -SocksiPy-branch==1.01 -xlrd==2.0.1 +fitz==0.0.1.dev2 +Flask==3.0.2 +Flask-Ask==0.9.8 fpdf==1.7.2 -mysql-connector-repackaged==0.3.1 -word2number==1.1 -tornado==6.4 -obs==0.0.0 -todo==0.1 -oauth2client==4.1.3 +freegames==2.5.3 +fuzzywuzzy==0.18.0 +geocoder==1.38.1 +google-api-python-client==2.115.0 +googletrans==3.0.0 +gTTS==2.5.0 +httplib2==0.22.0 +hupper==1.12.1 keras==3.3.3 -pymongo==4.7.1 -playsound==1.3.0 -pyttsx3==2.90 -auto-mix-prep==0.2.0 lib==4.0.0 -pywifi==1.1.12 -patterns==0.3 +matplotlib==3.9.0 +mechanize==0.4.10 +mediapipe==0.10.9 +Menu==3.2.2 +modules==1.0.0 +mutagen==1.47.0 +mysql-connector-repackaged==0.3.1 +newspaper==0.1.0.7 +nltk==3.8.1 +numpy==1.26.4 +oauth2client==4.1.3 +obs==0.0.0 openai==1.9.0 -background==0.2.1 -pydantic==2.6.1 +opencv-python==4.9.0.80 openpyxl==3.1.2 +pafy==0.5.5 +pandas==2.2.2 +patterns==0.3 +pdf2docx==0.5.8 +Pillow==10.2.0 +playsound==1.3.0 +plyer==2.1.0 +pong==1.5 +protobuf==4.25.2 +psutil==5.9.8 +PyAutoGUI==0.9.54 +pydantic==2.6.1 +pygame==2.5.2 +pyglet==2.0.10 +pymongo==4.7.1 +pynput==1.7.6 +PyPDF2==3.0.1 +pyperclip==1.8.2 +PyQRCode==1.2.1 +PyQt5==5.15.10 +pyserial==3.5 +pyshorteners==1.0.1 pytesseract==0.3.10 +pytest==8.2.0 +pyttsx3==2.90 +pytube==15.0.0 +pywhatkit==5.4 +pywifi==1.1.12 +qrcode==7.4.2 +quo==2023.5.1 +requests==2.31.0 requests-mock==1.12.1 -pyglet==2.0.10 -urllib3==2.2.1 -thirdai==0.7.44 -google-api-python-client==2.115.0 +rich==13.7.1 +seaborn==0.13.1 +selenium==4.16.0 +simplegui==0.1.1 +slab==1.1.5 +SocksiPy-branch==1.01 +solara==1.32.2 sound==0.1.0 -xlwt==1.3.0 -pygame==2.5.2 speechtotext==0.0.3 -wikipedia==1.4.0 -tqdm==4.66.4 -Menu==3.2.2 -yfinance==0.2.35 -tweepy==4.14.0 +tabula==1.0.5 +tensorflow==2.15.0.post1 +thirdai==0.7.44 +time==1.0.0 tkcalendar==1.6.1 -pytube==15.0.0 -xor-cipher==4.0.0 -bird==0.1.2 -mechanize==0.4.10 +todo==0.1 +tornado==6.4 +tqdm==4.66.4 translate==3.6.1 -solara==1.32.2 -pywhatkit==5.4 -mutagen==1.47.0 +Tubes==0.2.1 +tweepy==4.14.0 +twilio==9.0.0 +ujson==5.9.0 Unidecode==1.3.8 -Ball==0.2.9 -pynput==1.7.6 -gTTS==2.5.0 -ccxt==4.3.18 -fitz==0.0.1.dev2 -fastapi==0.109.0 -Django==5.0.5 -docx==0.2.4 -matplotlib==3.9.0 -pyshorteners==1.0.1 -geocoder==1.38.1 -APScheduler==3.10.4 -PyQRCode==1.2.1 -freegames==2.5.3 -pyperclip==1.8.2 -newspaper==0.1.0.7 -opencv-python==4.9.0.80 -tensorflow==2.15.0.post1 -pandas==2.2.2 -pytest==8.2.0 -qrcode==7.4.2 -googletrans==3.0.0 -slab==1.1.5 -psutil==5.9.8 -mediapipe==0.10.9 -rich==13.7.1 -httplib2==0.22.0 -protobuf==4.25.2 -colorama==0.4.6 -plyer==2.1.0 -Flask-Ask==0.9.8 -emoji==2.11.1 -PyAutoGUI==0.9.54 +urllib3==2.2.1 +utils==1.0.2 +watchdog==3.0.0 +wikipedia==1.4.0 +win10toast==0.9 +word2number==1.1 +xlrd==2.0.1 +xlwt==1.3.0 +xor-cipher==4.0.0 +yfinance==0.2.35 diff --git a/reversed_pattern3.py b/reversed_pattern3.py index f19ef159691..4ee6131ee41 100644 --- a/reversed_pattern3.py +++ b/reversed_pattern3.py @@ -1,20 +1,23 @@ -#Simple inverted number triangle piramid -#11111 -#2222 -#333 -#44 -#5 +# Simple inverted number triangle piramid +# 11111 +# 2222 +# 333 +# 44 +# 5 + def main(): lines = int(input("Enter no.of lines: ")) pattern(lines) + def pattern(lines): t = 1 - for i in reversed(range(1, (lines +1))): - format = str(t)*i + for i in reversed(range(1, (lines + 1))): + format = str(t) * i print(format) t = t + 1 + if __name__ == "__main__": main() diff --git a/rock_paper_scissor_game.py b/rock_paper_scissor_game.py index 1cc3c8dedd3..75fc8d4a3f2 100644 --- a/rock_paper_scissor_game.py +++ b/rock_paper_scissor_game.py @@ -1,8 +1,5 @@ -from __future__ import print_function - import random - # let # 0 - rock # 1 - paper diff --git a/russian_roulette.py b/russian_roulette.py index 337f8be8a86..1b6b45d0427 100644 --- a/russian_roulette.py +++ b/russian_roulette.py @@ -2,8 +2,9 @@ the code is just a russian roulette game against the computer """ -from random import randrange + import time +from random import randrange def main(): @@ -30,7 +31,7 @@ def main(): # take input from the user answer = input( - "please press 'm' if you want to start first or 'p' if you want the pc to start first: " + "please press 'm' if you want to start first or 'p' if you want the pc to start first: ", ) # check input @@ -38,7 +39,7 @@ def main(): answer = input("please enter again ('m' or 'p'): ") # set turn - if answer == 'm': + if answer == "m": turn = "player" else: turn = "pc" @@ -49,8 +50,10 @@ def main(): time.sleep(1) print("the gun is being loaded") time.sleep(3) - print("the gun is placed on " + ("your head" if turn == - "player" else "the cpu of the pc")) + print( + "the gun is placed on " + + ("your head" if turn == "player" else "the cpu of the pc"), + ) time.sleep(3) print("and...") time.sleep(1) diff --git a/scrap_file.py b/scrap_file.py index 7655e792cbe..05bc7f1e674 100644 --- a/scrap_file.py +++ b/scrap_file.py @@ -5,13 +5,13 @@ import requests - # Function for download file parameter taking as url def download(url): f = open( - "file_name.jpg", "wb" + "file_name.jpg", + "wb", ) # opening file in write binary('wb') mode with file_name.ext ext=extension f.write(requests.get(url).content) # Writing File Content in file_name.jpg f.close() diff --git a/script_count.py b/script_count.py index b7a2a0164b8..966c1190b51 100644 --- a/script_count.py +++ b/script_count.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os # Load the library module # Script Name : script_count.py @@ -14,10 +12,10 @@ # Description : This scans my scripts directory and gives a count of the different types of scripts path = os.getenv( - "scripts" + "scripts", ) # Set the variable path by getting the value from the OS environment variable scripts dropbox = os.getenv( - "dropbox" + "dropbox", ) # Set the variable dropbox by getting the value from the OS environment variable dropbox @@ -29,11 +27,12 @@ def clear_screen(): # Function to clear the screen def count_files( - path, extensions + path, + extensions, ): # Start of the function to count the files in the scripts directory, it counts the extension when passed below counter = 0 # Set the counter to 0 for root, dirs, files in os.walk( - path + path, ): # Loop through all the directories in the given path for file in files: # For all the files counter += file.endswith(extensions) # Count the files @@ -42,7 +41,8 @@ def count_files( def github(): # Start of the function just to count the files in the github directory github_dir = os.path.join( - dropbox, "github" + dropbox, + "github", ) # Joins the paths to get the github directory - 1.1 github_count = sum( (len(f) for _, _, f in os.walk(github_dir)) @@ -57,13 +57,14 @@ def github(): # Start of the function just to count the files in the github dir print("\nGithub directory is all Clear") else: # If it is any other number then print the following message, showing the number outstanding. print( - "\nYou have: " + str(github_count) + " waiting to be uploaded to github!!" + "\nYou have: " + str(github_count) + " waiting to be uploaded to github!!", ) def development(): # Start of the function just to count the files in the development directory dev_dir = os.path.join( - path, "development" + path, + "development", ) # Joins the paths to get the development directory - 1.1 dev_count = sum( (len(f) for _, _, f in os.walk(dev_dir)) @@ -78,7 +79,7 @@ def development(): # Start of the function just to count the files in the devel print("\nDevelopment directory is all clear") else: print( - "\nYou have: " + str(dev_count) + " waiting to be finished!!" + "\nYou have: " + str(dev_count) + " waiting to be finished!!", ) # If it is any other number then print the following message, showing the number outstanding. @@ -86,7 +87,7 @@ def development(): # Start of the function just to count the files in the devel print("\nYou have the following :\n") print( - "AutoIT:\t" + str(count_files(path, ".au3")) + "AutoIT:\t" + str(count_files(path, ".au3")), ) # Run the count_files function to count the files with the extension we pass print("Batch:\t" + str(count_files(path, (".bat", ",cmd")))) # 1.3 print("Perl:\t" + str(count_files(path, ".pl"))) diff --git a/script_listing.py b/script_listing.py index d890616cd90..8273b192e24 100644 --- a/script_listing.py +++ b/script_listing.py @@ -12,27 +12,30 @@ import os # Load the library module logdir = os.getenv( - "logs" + "logs", ) # Set the variable logdir by getting the value from the OS environment variable logs logfile = "script_list.log" # Set the variable logfile path = os.getenv( - "scripts" + "scripts", ) # Set the varable path by getting the value from the OS environment variable scripts - 1.2 # path = (raw_input("Enter dir: ")) # Ask the user for the directory to scan logfilename = os.path.join( - logdir, logfile + logdir, + logfile, ) # Set the variable logfilename by joining logdir and logfile together log = open(logfilename, "w") # Set the variable log and open the logfile for writing for dirpath, dirname, filenames in os.walk( - path + path, ): # Go through the directories and the subdirectories for filename in filenames: # Get all the filenames log.write( - os.path.join(dirpath, filename) + "\n" + os.path.join(dirpath, filename) + "\n", ) # Write the full path out to the logfile print( - "\nYour logfile ", logfilename, "has been created" + "\nYour logfile ", + logfilename, + "has been created", ) # Small message informing the user the file has been created diff --git a/send_message_automation/README.md b/send_message_automation/README.md index c38ad7bb52a..8dc820f61a7 100644 --- a/send_message_automation/README.md +++ b/send_message_automation/README.md @@ -5,4 +5,4 @@ sources used: Gif image creation credit goes to: -- ezgif.com used to make gif images. \ No newline at end of file +- ezgif.com used to make gif images. diff --git a/send_message_automation/author_name_NC.txt b/send_message_automation/author_name_NC.txt index 17822fa7961..591be71ed89 100644 --- a/send_message_automation/author_name_NC.txt +++ b/send_message_automation/author_name_NC.txt @@ -1,7 +1,6 @@ - __ _ _ _ _ ___ _ _ - /\ \ \(_)| |_ | | __ __ _ _ __ ___ | |__ / __\| |__ ___ _ _ _ __ __ _ ___ (_) __ _ + __ _ _ _ _ ___ _ _ + /\ \ \(_)| |_ | | __ __ _ _ __ ___ | |__ / __\| |__ ___ _ _ _ __ __ _ ___ (_) __ _ / \/ /| || __|| |/ / / _` || '__|/ __|| '_ \ / / | '_ \ / _ \ | | | || '__| / _` |/ __|| | / _` | / /\ / | || |_ | < | (_| || | \__ \| | | | / /___ | | | || (_) || |_| || | | (_| |\__ \| || (_| | \_\ \/ |_| \__||_|\_\ \__,_||_| |___/|_| |_| \____/ |_| |_| \___/ \__,_||_| \__,_||___/|_| \__,_| - diff --git a/send_message_automation/message_automation.py b/send_message_automation/message_automation.py index 5a797ece210..a22a7066d2d 100644 --- a/send_message_automation/message_automation.py +++ b/send_message_automation/message_automation.py @@ -1,6 +1,7 @@ -import pyautogui from time import sleep +import pyautogui + # Do you want to include the message counter? # make a class of it. diff --git a/sendemail.py b/sendemail.py index 12a01080ee7..33ba1abab65 100644 --- a/sendemail.py +++ b/sendemail.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import base64 import mimetypes import os @@ -11,7 +9,7 @@ import httplib2 import oauth2client -from apiclient import errors, discovery +from apiclient import discovery, errors from oauth2client import client, tools SCOPES = "https://www.googleapis.com/auth/gmail.send" @@ -43,7 +41,12 @@ def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None): service = discovery.build("gmail", "v1", http=http) if attachmentFile: message1 = createMessageWithAttachment( - sender, to, subject, msgHtml, msgPlain, attachmentFile + sender, + to, + subject, + msgHtml, + msgPlain, + attachmentFile, ) else: message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain) diff --git a/sensors_information.py b/sensors_information.py index 694dc302904..63a696151a4 100644 --- a/sensors_information.py +++ b/sensors_information.py @@ -1,6 +1,7 @@ import argparse -import sys import socket +import sys + import psutil @@ -34,9 +35,9 @@ def show_sensors(): print("Python Version:{0.major}.{0.minor}".format(python_version())) for address in ip_addresses(): print("IP Addresses: {0[1]} ({0[0]})".format(address)) - print("CPU Load: {:.1f}".format(cpu_load())) - print("RAM Available: {} MiB".format(ram_available() / 1024 ** 2)) - print("AC Connected: {}".format(ac_connected())) + print(f"CPU Load: {cpu_load():.1f}") + print(f"RAM Available: {ram_available() / 1024**2} MiB") + print(f"AC Connected: {ac_connected()}") def command_line(argv): diff --git a/serial_scanner.py b/serial_scanner.py index adf5ba1ee39..777a5a9ac86 100644 --- a/serial_scanner.py +++ b/serial_scanner.py @@ -2,7 +2,6 @@ import serial - # A serial port-scanner for linux and windows platforms # Author: Julio César Echeverri Marulanda @@ -42,7 +41,7 @@ def ListAvailablePorts(): else: print( """This method was developed only for linux and windows - the current platform isn't recognised""" + the current platform isn't recognised""", ) if len(AvailablePorts) == 0: print("NO port in use") diff --git a/sierpinski_triangle.py b/sierpinski_triangle.py index 966b5648af3..5d0706595e9 100644 --- a/sierpinski_triangle.py +++ b/sierpinski_triangle.py @@ -3,10 +3,10 @@ Simple example of Fractal generation using recursive function. What is Sierpinski Triangle? ->>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, -is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller -equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e., -it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after +>>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, +is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller +equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e., +it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after the Polish mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries prior to the work of Sierpinski. Requirements(pip): @@ -21,13 +21,14 @@ Credits: This code was written by editing the code from http://www.lpb-riannetrujillo.com/blog/python-fractal/ """ + import sys import turtle PROGNAME = "Sierpinski Triangle" if len(sys.argv) != 2: raise Exception( - "right format for using this script: $python fractals.py " + "right format for using this script: $python fractals.py ", ) myPen = turtle.Turtle() diff --git a/simulate_memory_cpu.py b/simulate_memory_cpu.py index 9a108fb89cc..05310b67484 100644 --- a/simulate_memory_cpu.py +++ b/simulate_memory_cpu.py @@ -1,40 +1,41 @@ #! /user/bin/env python -# -*- encoding: utf-8 -*- """ Simulate cpu、 memory usage """ -import sys import re +import sys import time from multiprocessing import Process, cpu_count def print_help(): - print('Usage: ') - print(' python cpu_memory_simulator.py m 1GB') - print(' python cpu_memory_simulator.py c 1') - print(' python cpu_memory_simulator.py mc 1GB 2') + print("Usage: ") + print(" python cpu_memory_simulator.py m 1GB") + print(" python cpu_memory_simulator.py c 1") + print(" python cpu_memory_simulator.py mc 1GB 2") + # memory usage def mem(): - pattern = re.compile('^(\d*)([M|G]B)$') + pattern = re.compile(r"^(\d*)([M|G]B)$") size = sys.argv[2].upper() match = pattern.match(size) if match: num = int(match.group(1)) unit = match.group(2) - if unit == 'MB': - s = ' ' * (num * 1024 * 1024) + if unit == "MB": + s = " " * (num * 1024 * 1024) else: - s = ' ' * (num * 1024 * 1024 * 1024) + s = " " * (num * 1024 * 1024 * 1024) time.sleep(24 * 3600) else: print("bad args.....") print_help() + # cpu usage @@ -42,6 +43,7 @@ def deadloop(): while True: pass + # Specify how many cores to occupy according to the parameters @@ -54,7 +56,7 @@ def cpu(): return if cores > cpu_num: - print("Invalid CPU Num(cpu_count="+str(cpu_num)+")") + print("Invalid CPU Num(cpu_count=" + str(cpu_num) + ")") return if cores is None or cores < 1: @@ -72,9 +74,9 @@ def mem_cpu(): if __name__ == "__main__": if len(sys.argv) >= 3: switcher = { - 'm': mem, - 'c': cpu, - 'mc': mem_cpu + "m": mem, + "c": cpu, + "mc": mem_cpu, } switcher.get(sys.argv[1], mem)() else: diff --git a/singly_linked_list.py b/singly_linked_list.py index bd66b5f5d8b..8eca38598fe 100644 --- a/singly_linked_list.py +++ b/singly_linked_list.py @@ -3,7 +3,8 @@ def __init__(self, data): self.data = data self.next = None -class LinkedList(): + +class LinkedList: def __init__(self): self.head = None @@ -38,7 +39,7 @@ def insert(self, pos, data): elif pos == 0: self.insert_at_head(data) return - elif pos == self.length()-1: + elif pos == self.length() - 1: self.add_node(data) return new_node = Node(data) @@ -53,12 +54,12 @@ def insert(self, pos, data): prev = curr curr = curr.next curr_pos += 1 - + def delete_head(self): temp = self.head self.head = temp.next del temp - + def delete_end(self): curr = self.head prev = None @@ -77,7 +78,7 @@ def delete(self, pos): elif pos == 0: self.delete_head() return - elif pos == self.length()-1: + elif pos == self.length() - 1: self.delete_end() return curr = self.head @@ -98,7 +99,7 @@ def display(self): rev = [] curr = self.head while curr != None: - print(f"{curr.data} --> ", end='') + print(f"{curr.data} --> ", end="") rev.append(curr.data) curr = curr.next print() diff --git a/slack_message.py b/slack_message.py index c06416cbe82..52ecd451165 100644 --- a/slack_message.py +++ b/slack_message.py @@ -1,5 +1,3 @@ -from __future__ import print_function - # Created by sarathkaul on 11/11/19 import json diff --git a/snake.py b/snake.py index 3c66cc599d4..4c4da84650e 100644 --- a/snake.py +++ b/snake.py @@ -6,12 +6,12 @@ try: import curses - from time import sleep - from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN + from curses import KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_UP from random import randint + from time import sleep print( - "Use the arrow keys to move, press the space bar to pause, and press ESC to quit" + "Use the arrow keys to move, press the space bar to pause, and press ESC to quit", ) sleep(1) key = KEY_RIGHT # Initializing values @@ -25,7 +25,7 @@ x, y = win.getmaxyx() key = KEY_DOWN # Initializing values score = 0 - s = open(".snake_highscore.txt", "r") + s = open(".snake_highscore.txt") hscore = s.read() s.close() snake = [[4, 10], [4, 9], [4, 8]] # Initial snake co-ordinates @@ -40,7 +40,7 @@ win.addstr(0, 37, "Highscore: " + str(hscore) + " ") win.timeout( - int(150 - (len(snake) / 5 + len(snake) / 10) % 120) + int(150 - (len(snake) / 5 + len(snake) / 10) % 120), ) # Increases the speed of Snake as its length increases prevKey = key # Previous key pressed diff --git a/snake_case_renamer_depth_one.py b/snake_case_renamer_depth_one.py index fdedcb54a7f..90d4daf2ab1 100644 --- a/snake_case_renamer_depth_one.py +++ b/snake_case_renamer_depth_one.py @@ -1,7 +1,8 @@ -import os import argparse +import os from typing import Union + def generate_unique_name(directory: str, name: str) -> str: """ Generate a unique name for a file or folder in the specified directory. @@ -24,6 +25,7 @@ def generate_unique_name(directory: str, name: str) -> str: index += 1 return f"{base_name}_{index}{extension}" + def rename_files_and_folders(directory: str) -> None: """ Rename files and folders in the specified directory to lowercase with underscores. @@ -54,6 +56,7 @@ def rename_files_and_folders(directory: str) -> None: os.rename(old_path, new_path) + def main() -> None: """ Main function to handle command-line arguments and call the renaming function. @@ -68,12 +71,19 @@ def main() -> None: """ # Create a parser for command-line arguments - parser = argparse.ArgumentParser(description="Rename files and folders to lowercase with underscores.") - parser.add_argument("directory", type=str, help="Path to the directory containing the files and folders to be renamed.") + parser = argparse.ArgumentParser( + description="Rename files and folders to lowercase with underscores." + ) + parser.add_argument( + "directory", + type=str, + help="Path to the directory containing the files and folders to be renamed.", + ) args = parser.parse_args() # Call the rename_files_and_folders function with the provided directory path rename_files_and_folders(args.directory) + if __name__ == "__main__": main() diff --git a/socket-programming/README.md b/socket-programming/README.md index 2f0e8476e53..e33f90a7a8f 100644 --- a/socket-programming/README.md +++ b/socket-programming/README.md @@ -1,11 +1,11 @@ # socket-programming-python -Socket programming in python with client-server with duplex alternate chat(client-server-client-server-....) +Socket programming in python with client-server with duplex alternate chat(client-server-client-server-....) -# Client view +# Client view ![client](https://user-images.githubusercontent.com/29729380/55186437-8e9f0b00-51bc-11e9-86fa-5641143db32e.png) -# Server view +# Server view ![server](https://user-images.githubusercontent.com/29729380/55186445-92cb2880-51bc-11e9-9e67-40a9368cc6c7.png) diff --git a/socket-programming/server.py b/socket-programming/server.py index 4986710ce9c..e2fa9d1a0cd 100644 --- a/socket-programming/server.py +++ b/socket-programming/server.py @@ -20,7 +20,7 @@ # show connected client print("connected from", client_address) # sending acknowledgement to client that you are connected - connection.send(str("Now You are connected").encode("utf-8")) + connection.send(b"Now You are connected") # receiving the message while True: diff --git a/spotifyAccount.py b/spotifyAccount.py index a585b6abb96..5ccbac1183e 100644 --- a/spotifyAccount.py +++ b/spotifyAccount.py @@ -34,7 +34,7 @@ def update(self): data = "" urls = [ - "https://api.proxyscrape.com/?request=getproxies&proxytype=socks4&timeout=10000&ssl=yes" + "https://api.proxyscrape.com/?request=getproxies&proxytype=socks4&timeout=10000&ssl=yes", ] for url in urls: data += requests.get(url).text @@ -66,7 +66,7 @@ def creator(): if title == "windows": system( "title " - + f"Spotify Account Creator by KevinLage https://github.com/KevinLage/Spotify-Account-Creator Created: {created}/{maxi} Errors:{errors}" + + f"Spotify Account Creator by KevinLage https://github.com/KevinLage/Spotify-Account-Creator Created: {created}/{maxi} Errors:{errors}", ) s = requests.session() @@ -104,7 +104,7 @@ def creator(): if title == "windows": system( "title " - + f"Spotify Account Creator : {created}/{maxi} Errors:{errors}" + + f"Spotify Account Creator : {created}/{maxi} Errors:{errors}", ) else: errors += 1 diff --git a/sqlite_check.py b/sqlite_check.py index 74403b1a0bb..4a845bbb5dd 100644 --- a/sqlite_check.py +++ b/sqlite_check.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import os import sqlite3 as lite import sys @@ -13,7 +11,7 @@ # Description : Runs checks to check my SQLITE database dropbox = os.getenv("dropbox") -dbfile = "Databases\jarvis.db" +dbfile = r"Databases\jarvis.db" master_db = os.path.join(dropbox, dbfile) con = None diff --git a/sqlite_table_check.py b/sqlite_table_check.py index 588b80e1c6e..f4f571a72cd 100644 --- a/sqlite_table_check.py +++ b/sqlite_table_check.py @@ -14,11 +14,11 @@ dropbox = os.getenv("dropbox") config = os.getenv("my_config") -dbfile = "Databases\jarvis.db" +dbfile = r"Databases\jarvis.db" listfile = "sqlite_master_table.lst" master_db = os.path.join(dropbox, dbfile) config_file = os.path.join(config, listfile) -tablelist = open(config_file, "r") +tablelist = open(config_file) conn = sqlite3.connect(master_db) cursor = conn.cursor() @@ -37,7 +37,8 @@ conn = sqlite3.connect(master_db) cursor = conn.cursor() cursor.execute( - "select count(*) from sqlite_master where name = ?", (table.strip(),) + "select count(*) from sqlite_master where name = ?", + (table.strip(),), ) res = cursor.fetchone() diff --git a/stack.py b/stack.py index d90048ccf62..c6f4ef523d6 100644 --- a/stack.py +++ b/stack.py @@ -1,5 +1,6 @@ # Python program to reverse a string using stack + # Function to create an empty stack. # It initializes size of stack as 0 def createStack(): diff --git a/stackF_Harsh2255.py b/stackF_Harsh2255.py index b28bf9de77a..6c318694e6b 100644 --- a/stackF_Harsh2255.py +++ b/stackF_Harsh2255.py @@ -4,6 +4,7 @@ # Used to return -infinite when stack is empty from sys import maxsize + # Function to create a stack. It initializes size of stack as 0 def createStack(): stack = [] diff --git a/stone_paper_scissor/main.py b/stone_paper_scissor/main.py index 2a2166f4f47..45c1bf49751 100644 --- a/stone_paper_scissor/main.py +++ b/stone_paper_scissor/main.py @@ -1,8 +1,8 @@ -import utils - # import the random module import random +import utils + print("Starting the Rock Paper Scissors game!") player_name = input("Please enter your name: ") # Takes Input from the user diff --git a/sum_of_digits_of_a_number.py b/sum_of_digits_of_a_number.py index 06bb321441f..b358189d14e 100644 --- a/sum_of_digits_of_a_number.py +++ b/sum_of_digits_of_a_number.py @@ -1,5 +1,6 @@ import sys + def get_integer_input(prompt, attempts): for i in range(attempts, 0, -1): try: @@ -10,6 +11,7 @@ def get_integer_input(prompt, attempts): print(f"{i-1} {'chance' if i-1 == 1 else 'chances'} left") return None + def sum_of_digits(n): total = 0 while n > 0: @@ -17,6 +19,7 @@ def sum_of_digits(n): n //= 10 return total + chances = 3 number = get_integer_input("Enter a number: ", chances) diff --git a/swap.py b/swap.py index 00971b94165..47ec594d5bf 100644 --- a/swap.py +++ b/swap.py @@ -6,10 +6,10 @@ class Swapper: ------- swap_tuple_unpacking(self): Swaps the values of x and y using a tuple unpacking method. - + swap_temp_variable(self): Swaps the values of x and y using a temporary variable. - + swap_arithmetic_operations(self): Swaps the values of x and y using arithmetic operations. @@ -29,7 +29,7 @@ def __init__(self, x, y): """ if not isinstance(x, (int, float)) or not isinstance(y, (float, int)): raise ValueError("Both x and y should be integers.") - + self.x = x self.y = y diff --git a/swapping of two numbers b/swapping of two numbers index 8b137891791..e69de29bb2d 100644 --- a/swapping of two numbers +++ b/swapping of two numbers @@ -1 +0,0 @@ - diff --git a/test.cpp b/test.cpp index 8b137891791..e69de29bb2d 100644 --- a/test.cpp +++ b/test.cpp @@ -1 +0,0 @@ - diff --git a/text-to-audio/README.md b/text-to-audio/README.md index 52f212729c1..7ebffcd63c1 100644 --- a/text-to-audio/README.md +++ b/text-to-audio/README.md @@ -28,8 +28,3 @@ If you make any changes main.py, please mention it in README.md (this file). A b --- Author - Saumitra Jagdale, Vardhaman Kalloli - - - - - diff --git a/text-to-audio/main.py b/text-to-audio/main.py index 4f18f5153a1..dcffc3237ec 100644 --- a/text-to-audio/main.py +++ b/text-to-audio/main.py @@ -1,6 +1,7 @@ -from gtts import gTTS import os +from gtts import gTTS + # Enter the text in string format which you want to convert to audio mytext = "Hello World!, this audio is created using GTTS module." diff --git a/text-to-audio/requirements.txt b/text-to-audio/requirements.txt index 03e7acff39c..ded6fa26490 100644 --- a/text-to-audio/requirements.txt +++ b/text-to-audio/requirements.txt @@ -1,2 +1,2 @@ -os gTTS +os diff --git a/text-to-audio/text-file-to-audio.py b/text-to-audio/text-file-to-audio.py index aa5ce407d6b..e727677d473 100644 --- a/text-to-audio/text-file-to-audio.py +++ b/text-to-audio/text-file-to-audio.py @@ -1,6 +1,7 @@ -from gtts import gTTS import os +from gtts import gTTS + # Enter the name of your text file mytextfile = "hello.txt" @@ -8,7 +9,7 @@ language = "en" # Get the contents of your file -with open(mytextfile, 'r') as f: +with open(mytextfile) as f: mytext = f.read() f.close() diff --git a/text_file_replace.py b/text_file_replace.py index 216c5916537..764da2158f8 100644 --- a/text_file_replace.py +++ b/text_file_replace.py @@ -13,13 +13,13 @@ def text_file_replace(file, encoding, old, new): lines = [] cnt = 0 - with open(file=file, mode="r", encoding=encoding) as fd: + with open(file=file, encoding=encoding) as fd: for line in fd: cnt += line.count(old) lines.append(line.replace(old, new)) with open(file=file, mode="w", encoding=encoding) as fd: fd.writelines(lines) - print('{} occurence(s) of "{}" have been replaced with "{}"'.format(cnt, old, new)) + print(f'{cnt} occurence(s) of "{old}" have been replaced with "{new}"') return cnt diff --git a/text_to_audio/README.md b/text_to_audio/README.md index 4cca8f6131d..a9a50ad1ce4 100644 --- a/text_to_audio/README.md +++ b/text_to_audio/README.md @@ -1,5 +1,5 @@ Improvement: Nitkarsh Chourasia - + Improvement made: Used class implemented lazy loading @@ -9,4 +9,4 @@ tested on windows and linux gui is to be made Memory optimised PEP8 compliant -linter friendly : \ No newline at end of file +linter friendly : diff --git a/text_to_audio/author_name_NC.txt b/text_to_audio/author_name_NC.txt index 17822fa7961..591be71ed89 100644 --- a/text_to_audio/author_name_NC.txt +++ b/text_to_audio/author_name_NC.txt @@ -1,7 +1,6 @@ - __ _ _ _ _ ___ _ _ - /\ \ \(_)| |_ | | __ __ _ _ __ ___ | |__ / __\| |__ ___ _ _ _ __ __ _ ___ (_) __ _ + __ _ _ _ _ ___ _ _ + /\ \ \(_)| |_ | | __ __ _ _ __ ___ | |__ / __\| |__ ___ _ _ _ __ __ _ ___ (_) __ _ / \/ /| || __|| |/ / / _` || '__|/ __|| '_ \ / / | '_ \ / _ \ | | | || '__| / _` |/ __|| | / _` | / /\ / | || |_ | < | (_| || | \__ \| | | | / /___ | | | || (_) || |_| || | | (_| |\__ \| || (_| | \_\ \/ |_| \__||_|\_\ \__,_||_| |___/|_| |_| \____/ |_| |_| \___/ \__,_||_| \__,_||___/|_| \__,_| - diff --git a/text_to_audio/main.py b/text_to_audio/main.py index ff7a3e56e64..2735770ca4b 100644 --- a/text_to_audio/main.py +++ b/text_to_audio/main.py @@ -1,10 +1,10 @@ # A exclusive CLI version can be made using inquirer library. -from gtts import gTTS from io import BytesIO - # only use when needed to avoid memory usage in program from pprint import pprint +from gtts import gTTS + """_summary_ def some_function(): # Pygame module is only imported when this function is called @@ -62,7 +62,10 @@ def __init__( self.text_to_audio = text self.gtts_object = gTTS( - text=self.text_to_audio, lang=self.lang, slow=self.slow, tld=self.accent + text=self.text_to_audio, + lang=self.lang, + slow=self.slow, + tld=self.accent, ) # ! Some error is here. @@ -70,7 +73,10 @@ def user_input(self): text = input("Enter the text you want to convert to audio: ") self.text_to_audio = text self.gtts_object = gTTS( - text=self.text_to_audio, lang=self.lang, slow=self.slow, tld=self.accent + text=self.text_to_audio, + lang=self.lang, + slow=self.slow, + tld=self.accent, ) # Just need to understand the class workings little better. # Isn't this declaring this again? @@ -151,7 +157,7 @@ def play_only(self): # hello = userAudio("Hello, world!") # hello.play_only() -with open("special_file.txt", "r") as f: +with open("special_file.txt") as f: retrieved_text = f.read() retrieved_text = retrieved_text.replace("\n", "") @@ -173,7 +179,7 @@ def __init__(self, string): # print("File saved successfully") # Reading from the file - with open("special_file.txt", "r") as f: + with open("special_file.txt") as f: retrieved_text = f.read() retrieved_text = retrieved_text.replace("\n", "") diff --git a/text_to_audio/special_file.txt b/text_to_audio/special_file.txt index 40148d26029..a45c25d9c58 100644 --- a/text_to_audio/special_file.txt +++ b/text_to_audio/special_file.txt @@ -2,20 +2,20 @@ T e r i - + m a a - + k i - + c h u t , - + b h o @@ -24,20 +24,20 @@ d i k e - + j a k a r - + g a a a n d - + m a a @@ -47,12 +47,12 @@ a n a a - + c h u t - + m a a @@ -62,6 +62,6 @@ a a n i - + k e diff --git a/text_to_pig_latin.py b/text_to_pig_latin.py index 850b13913e8..518358a6f47 100644 --- a/text_to_pig_latin.py +++ b/text_to_pig_latin.py @@ -1,6 +1,6 @@ """ -This program converts English text to Pig-Latin. In Pig-Latin, we take the first letter of each word, -move it to the end, and add 'ay'. If the first letter is a vowel, we simply add 'hay' to the end. +This program converts English text to Pig-Latin. In Pig-Latin, we take the first letter of each word, +move it to the end, and add 'ay'. If the first letter is a vowel, we simply add 'hay' to the end. The program preserves capitalization and title case. For example: @@ -18,6 +18,7 @@ def pig_latin_word(word): else: return word[1:] + word[0] + "ay" + def pig_latin_sentence(text): words = text.split() pig_latin_words = [] @@ -31,7 +32,8 @@ def pig_latin_sentence(text): else: pig_latin_words.append(pig_latin_word(word)) - return ' '.join(pig_latin_words) + return " ".join(pig_latin_words) + user_input = input("Enter some English text: ") pig_latin_text = pig_latin_sentence(user_input) diff --git a/tf_idf_generator.py b/tf_idf_generator.py index 4e99e96ce64..e1be162868b 100644 --- a/tf_idf_generator.py +++ b/tf_idf_generator.py @@ -1,4 +1,4 @@ -"""@Author: Anurag Kumar(mailto:anuragkumarak95@gmail.com) +"""@Author: Anurag Kumar(mailto:anuragkumarak95@gmail.com) This module is used for generating a TF-IDF file or values from a list of files that contains docs. What is TF-IDF : https://en.wikipedia.org/wiki/Tf%E2%80%93idf @@ -6,8 +6,8 @@ python: - 3.5 -pre-requisites: - - colorama==0.3.9 +pre-requisites: + - colorama==0.3.9 sample file format of input: @@ -31,6 +31,7 @@ have fun, cheers. """ + import math import pickle @@ -102,7 +103,7 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): for f in file_names: file1 = open( - f, "r" + f, ) # never use 'rb' for textual data, it creates something like, {b'line-inside-the-doc'} # create word_count dict for all docs @@ -135,17 +136,21 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): TAG, "Total number of unique words in corpus", len(idf), - "( " + paint("++" + str(len(idf) - prev_doc_count), "g") + " )" - if prev_file_path - else "", + ( + "( " + paint("++" + str(len(idf) - prev_doc_count), "g") + " )" + if prev_file_path + else "" + ), ) print( TAG, "Total number of docs in corpus:", len(tf_idf), - "( " + paint("++" + str(len(tf_idf) - prev_corpus_length), "g") + " )" - if prev_file_path - else "", + ( + "( " + paint("++" + str(len(tf_idf) - prev_corpus_length), "g") + " )" + if prev_file_path + else "" + ), ) # dump if a dir-path is given @@ -153,10 +158,12 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): if dump_path[-8:] != "tfidfpkl": raise Exception( TAG - + "Please provide a .tfidfpkl file_path, it is the standard format of this module." + + "Please provide a .tfidfpkl file_path, it is the standard format of this module.", ) pickle.dump( - (idf, tf_idf), open(dump_path, "wb"), protocol=pickle.HIGHEST_PROTOCOL + (idf, tf_idf), + open(dump_path, "wb"), + protocol=pickle.HIGHEST_PROTOCOL, ) print(TAG, "Dumping TF-IDF vars @", dump_path) return idf, tf_idf diff --git a/thired-party-haarcascade-mustache-on-face/Nose.xml b/thired-party-haarcascade-mustache-on-face/Nose.xml index 0a0e5644f82..d8b1fbbff1d 100644 --- a/thired-party-haarcascade-mustache-on-face/Nose.xml +++ b/thired-party-haarcascade-mustache-on-face/Nose.xml @@ -5,7 +5,7 @@ ////////////////////////////////////////////////////////////////////////// | Contributors License Agreement | IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -| By downloading, copying, installing or using the software you agree +| By downloading, copying, installing or using the software you agree | to this license. | If you do not agree to this license, do not download, install, | copy or use the software. @@ -23,8 +23,8 @@ | * Redistributions in binary form must reproduce the above | copyright notice, this list of conditions and the following | disclaimer in the documentation and/or other materials provided -| with the distribution. -| * The name of Contributor may not used to endorse or promote products +| with the distribution. +| * The name of Contributor may not used to endorse or promote products | derived from this software without specific prior written permission. | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS @@ -78,7 +78,7 @@ A comparison of this and other face related classifiers can be found in: More information can be found at http://mozart.dis.ulpgc.es/Gias/modesto_eng.html or in the papers. COMMERCIAL USE: -If you have any commercial interest in this work please contact +If you have any commercial interest in this work please contact mcastrillon@iusiani.ulpgc.es ------------------------------------------------------------------------> diff --git a/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py b/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py index 0e30d89d195..1aac49fe902 100644 --- a/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py +++ b/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py @@ -1,5 +1,4 @@ import cv2 - from utils import image_resize cap = cv2.VideoCapture(0) @@ -18,12 +17,12 @@ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) - for (x, y, w, h) in faces: + for x, y, w, h in faces: roi_gray = gray[y : y + h, x : x + h] # rec roi_color = frame[y : y + h, x : x + h] nose = nose_cascade.detectMultiScale(roi_gray, scaleFactor=1.5, minNeighbors=5) - for (nx, ny, nw, nh) in nose: + for nx, ny, nw, nh in nose: roi_nose = roi_gray[ny : ny + nh, nx : nx + nw] mustache2 = image_resize(mustache.copy(), width=nw) diff --git a/thired-party-haarcascade-mustache-on-face/utils.py b/thired-party-haarcascade-mustache-on-face/utils.py index 832c2c3ff8e..5201198bfaf 100644 --- a/thired-party-haarcascade-mustache-on-face/utils.py +++ b/thired-party-haarcascade-mustache-on-face/utils.py @@ -32,7 +32,7 @@ def image_resize(image, width=None, height=None, inter=cv2.INTER_AREA): return resized -class CFEVideoConf(object): +class CFEVideoConf: # Standard Video Dimensions Sizes STD_DIMENSIONS = { "360p": (480, 360), diff --git a/thread_signal.py b/thread_signal.py index 902093517ab..47178e4cecb 100644 --- a/thread_signal.py +++ b/thread_signal.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import signal import threading from time import sleep diff --git a/tic-tac-toe.py b/tic-tac-toe.py index 8956be21237..6210ebd9b9a 100644 --- a/tic-tac-toe.py +++ b/tic-tac-toe.py @@ -13,6 +13,7 @@ Game = Running Mark = "X" + # This Function Draws Game Board def DrawBoard(): print(" %c | %c | %c " % (board[1], board[2], board[3])) diff --git a/tic_tak_toe.py b/tic_tak_toe.py index 3138057fea0..dfc2c091a20 100644 --- a/tic_tak_toe.py +++ b/tic_tak_toe.py @@ -1,11 +1,13 @@ # Tic-Tac-Toe Program using # random number in Python -# importing all necessary libraries -import numpy as np import random from time import sleep +# importing all necessary libraries +import numpy as np + + # Creates an empty board def create_board(): return np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) diff --git a/time_delta.py b/time_delta.py index 9b153fd9707..d70f60d85b8 100644 --- a/time_delta.py +++ b/time_delta.py @@ -1,6 +1,5 @@ """Time Delta Solution """ - # ----------------------------------------------------------------------------- # You are givent two timestams in the format: Day dd Mon yyyy hh:mm:ss +xxxx # where +xxxx represents the timezone. @@ -26,15 +25,16 @@ # Sample Output: # 25200 # 88200 -#------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ +import datetime # Imports import math -import os +import os import random import re import sys -import datetime + # Complete the time_delta function below. def time_delta(t1, t2): @@ -42,14 +42,13 @@ def time_delta(t1, t2): Calculate the time delta between two timestamps in seconds. """ # Convert the timestamps to datetime objects - t1 = datetime.datetime.strptime(t1, '%a %d %b %Y %H:%M:%S %z') - t2 = datetime.datetime.strptime(t2, '%a %d %b %Y %H:%M:%S %z') - - return (t1 - t2) + t1 = datetime.datetime.strptime(t1, "%a %d %b %Y %H:%M:%S %z") + t2 = datetime.datetime.strptime(t2, "%a %d %b %Y %H:%M:%S %z") + return t1 - t2 -if __name__ == '__main__': +if __name__ == "__main__": t = int(input()) @@ -61,7 +60,3 @@ def time_delta(t1, t2): delta = time_delta(t1, t2) # print Delta with 1 Decimal Place print(round(delta.total_seconds(), 1)) - - - - diff --git a/translation_of_sizes_of_underwear_RU.py b/translation_of_sizes_of_underwear_RU.py index 63a64e9e34e..90d33eaf9b1 100644 --- a/translation_of_sizes_of_underwear_RU.py +++ b/translation_of_sizes_of_underwear_RU.py @@ -1,4 +1,3 @@ -# coding: utf-8 def my_found(req): my_dict = { "XXS": [42, 36, 8, 38, 24], @@ -23,7 +22,7 @@ def my_found(req): "Программа перевода размеров женского белья из\n" "международной системы в системы следующих стран:\n" "1 - Россия, 2 - Германия, 3 - США, 4 - Франция, 5 - Великобритания.\n" - "Справка (международная система): XXS, XS, S, M, L, XL, XXL, XXXL" + "Справка (международная система): XXS, XS, S, M, L, XL, XXL, XXXL", ) req = [] @@ -31,8 +30,8 @@ def my_found(req): req = list( input( ">>> Введите через пробел международный размер и страну,\n" - "в систему которой перевести данный размер: " - ).split() + "в систему которой перевести данный размер: ", + ).split(), ) req[0] = req[0].upper() if len(req) <= 1: @@ -41,5 +40,5 @@ def my_found(req): req[1] = int(req[1]) print( - f'Выбранный Вами размер "{req[0]}" в системе размеров "{country[req[1]]}" будет: {my_found(req)}' + f'Выбранный Вами размер "{req[0]}" в системе размеров "{country[req[1]]}" будет: {my_found(req)}', ) diff --git a/triangles.py b/triangles.py index 97283d8dad8..abd32fd355b 100644 --- a/triangles.py +++ b/triangles.py @@ -8,7 +8,7 @@ + "(c)" + " " * (max_size) + "(d)" - + " " * (max_size) + + " " * (max_size), ) for i in range(1, max_size + 1): diff --git a/tuple.py b/tuple.py index 69ee3950b9f..3f32d1df9f2 100644 --- a/tuple.py +++ b/tuple.py @@ -1,11 +1,11 @@ -a=(1,2,3,4,5) -print('Individual elements of Tuple are') +a = (1, 2, 3, 4, 5) +print("Individual elements of Tuple are") for i in a: - print(i,end=' ') + print(i, end=" ") print() -print('Value at index number 3 is:',a[3]) -print('Values from index no 2 are',a[2:]) -print('Length of tuple is',len(a)) -print('Maximum value from tuple is ',max(a)) -print('Minimum value from tuple is ',min(a)) -del a #delete the whole tuple +print("Value at index number 3 is:", a[3]) +print("Values from index no 2 are", a[2:]) +print("Length of tuple is", len(a)) +print("Maximum value from tuple is ", max(a)) +print("Minimum value from tuple is ", min(a)) +del a # delete the whole tuple diff --git a/turtal game.ipynb b/turtal game.ipynb index 70e85ff8431..4794115f709 100644 --- a/turtal game.ipynb +++ b/turtal game.ipynb @@ -6,7 +6,7 @@ "metadata": {}, "outputs": [], "source": [ - "import turtle \n" + "import turtle" ] }, { diff --git a/turtle module b/turtle module index a2059b8b463..0b8a434e1c4 100644 --- a/turtle module +++ b/turtle module @@ -18,7 +18,7 @@ sponge.backward(30) ``` #import turtle defines the module turtle which will allow you to create a Turtle object and draw with it. #turtle.Turtle; here "turtle" tells Python that we are referring to the turtle module, which is where the object "Turtle" is found -``` +``` **Creating a Rectangle** @@ -30,8 +30,8 @@ scrn = turtle.Screen() #creates a graphics window ciri = turtle.Turtle() #means the Turtle type that is defined within the turtle module #ciri is an instance of Turtle class ciri.forward(180) #object.method(parameter) -ciri.left(90) -ciri.forward(75) +ciri.left(90) +ciri.forward(75) ciri.left(90) ciri.forward(180) ciri.left(90) @@ -40,8 +40,8 @@ ciri.forward(75) **Creating a triangle** ``` -import turtle -scrn = turtle.Screen() +import turtle +scrn = turtle.Screen() mini = turtle.Turtle() mini.forward(180) mini.left(150) @@ -52,12 +52,12 @@ mini.forward(100) **Creating rectangle and triangle together** ``` -import turtle -scrn = turtle.Screen() -ciri = turtle.Turtle() +import turtle +scrn = turtle.Screen() +ciri = turtle.Turtle() ciri.forward(180) #object.method(parameter) -ciri.left(90) -ciri.forward(75) +ciri.left(90) +ciri.forward(75) ciri.left(90) ciri.forward(180) ciri.left(90) @@ -74,7 +74,7 @@ mini.forward(100) **Using properties** ``` -import turtle +import turtle scrn = turtle.Screen() scrn.bgcolor("lavender") #the object scrn has color property(which we write as bgcolor) @@ -98,7 +98,7 @@ arina.forward(90) **Mutliple objects with properties** ``` -import turtle +import turtle scrn = turtle.Screen() scrn.bgcolor("lavender") #the object scrn has color property(which we write as bgcolor) @@ -121,8 +121,8 @@ arina.forward(90) ciri = turtle.Turtle() ciri.color("yellow") ciri.forward(180) #object.method(parameter) -ciri.left(90) -ciri.forward(75) +ciri.left(90) +ciri.forward(75) ciri.left(90) ciri.forward(180) ciri.left(90) @@ -150,7 +150,7 @@ zina.left(180) #notice this zina.forward(150) scrn.exitonclick() # wait for a user click on the canvas -#we invoke its exitonclick method of scrn object, the program pauses execution +#we invoke its exitonclick method of scrn object, the program pauses execution #and waits for the user to click the mouse somewhere in the window ``` diff --git a/turtle_shapes_made.py b/turtle_shapes_made.py index e82ece728f4..60017048ffc 100644 --- a/turtle_shapes_made.py +++ b/turtle_shapes_made.py @@ -1,5 +1,6 @@ import turtle + class ShapeDrawer: def __init__(self, color, pensize): self.turtle = turtle.Turtle() @@ -18,6 +19,7 @@ def draw_triangle(self, length): self.turtle.forward(length) self.turtle.left(120) + def main(): scrn = turtle.Screen() scrn.bgcolor("lavender") @@ -45,5 +47,6 @@ def main(): scrn.exitonclick() + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/tweeter.py b/tweeter.py index 1ae534f448e..4473faa2d69 100644 --- a/tweeter.py +++ b/tweeter.py @@ -1,5 +1,5 @@ -from __future__ import print_function import os + import tweepy # TODO: Further improvements can be made to the program diff --git a/twitter_post_scraper.py b/twitter_post_scraper.py index 06be7896e8a..fdf4f6e08df 100644 --- a/twitter_post_scraper.py +++ b/twitter_post_scraper.py @@ -1,6 +1,7 @@ +import re + import requests from bs4 import BeautifulSoup -import re re_text = r"\:|\.|\!|(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b|(.twitter.com\/)\w*|\&" re_text_1 = r"(pictwittercom)\/\w*" @@ -28,9 +29,9 @@ def tweeter_scrapper(): for dirty_tweet in list_of_dirty_tweets: dirty_tweet = re.sub(re_text, "", dirty_tweet, flags=re.MULTILINE) dirty_tweet = re.sub(re_text_1, "", dirty_tweet, flags=re.MULTILINE) - dirty_tweet = dirty_tweet.replace(u"\xa0…", u"") - dirty_tweet = dirty_tweet.replace(u"\xa0", u"") - dirty_tweet = dirty_tweet.replace(u"\u200c", u"") + dirty_tweet = dirty_tweet.replace("\xa0…", "") + dirty_tweet = dirty_tweet.replace("\xa0", "") + dirty_tweet = dirty_tweet.replace("\u200c", "") clear_list_of_tweets.append(dirty_tweet) print(clear_list_of_tweets) diff --git a/ultimate-phone-book/contacts.py b/ultimate-phone-book/contacts.py index 7c53bacb28e..800756373c5 100644 --- a/ultimate-phone-book/contacts.py +++ b/ultimate-phone-book/contacts.py @@ -6,35 +6,39 @@ print("this code uses GPL V3 LICENSE") print("") +import os # start of code # import library import pickle -import os # get array from pickle data -infile = open('data/pickle-main', 'rb') +infile = open("data/pickle-main", "rb") # defining array array = pickle.load(infile) infile.close() # get key if path exists keyacess = False -path = 'data/pickle-key' -if os.path.isfile('data/pickle-key'): - pklekey = open('data/pickle-key', 'rb') +path = "data/pickle-key" +if os.path.isfile("data/pickle-key"): + pklekey = open("data/pickle-key", "rb") key = pickle.load(pklekey) pklekey.close() - if key == 'SKD0DW99SAMXI19#DJI9': + if key == "SKD0DW99SAMXI19#DJI9": keyacess = True print("key found & is correct") print("ALL FEATURES ENABLED") else: print("key is WRONG\nSOME FEATURES ARE DISABLED") - print("check https://github.com/JymPatel/Python-FirstEdition/tree/Main/PyPrograms/contacts for key, it's free") + print( + "check https://github.com/JymPatel/Python-FirstEdition/tree/Main/PyPrograms/contacts for key, it's free" + ) print("key isn't added to this repo check above repo") else: print("key not found\nSOME FEATURES ARE DISABLED") - print("check https://github.com/JymPatel/Python-FirstEdition/tree/Main/PyPrograms/contacts for key, it's free") + print( + "check https://github.com/JymPatel/Python-FirstEdition/tree/Main/PyPrograms/contacts for key, it's free" + ) print("") print("update-22.02 ADDS SAVING YOUR DATA WHEN CLOSED BY SAVING USING OPTION 0\n##") @@ -45,8 +49,8 @@ number = 2 email = 3 # getting some variables -promptvar = 0 # variable for prompt -loopvar = 0 # variable for main loop +promptvar = 0 # variable for prompt +loopvar = 0 # variable for main loop # making loop to run while loopvar < 1: # ask user what to do @@ -77,7 +81,9 @@ i1 = 0 # print all names while i1 < arraylen: - print(f"{array[fname][i1]} {array[lname][i1]}, {array[number][i1]} {array[email][i1]}") + print( + f"{array[fname][i1]} {array[lname][i1]}, {array[number][i1]} {array[email][i1]}" + ) i1 += 1 print("=======================") @@ -95,7 +101,7 @@ print("which contact would you like to delete? (enter first name)") print("enter '\nSTOP' to STOP deleting contact") rmcontact = input("INPUT: ") - if rmcontact != '\nSTOP': + if rmcontact != "\nSTOP": tempvar = 0 rmvar = 0 for i in range(arraylen): @@ -111,7 +117,7 @@ for i in range(4): print(array[i][rmvar]) tempinp = input("y/n? ") - if tempinp == 'y' or tempinp == 'Y': + if tempinp == "y" or tempinp == "Y": for i in range(4): del array[i][rmvar] print("contact REMOVED.") @@ -122,8 +128,6 @@ print("there are more than one contact with same name") # TODO - - # if option 4 is selected elif a == 4: if keyacess == True: @@ -158,7 +162,7 @@ elif a == 9: if keyacess: # change prompt settings - if promptvar == 0: + if promptvar == 0: promptvar += 1 print("you won't get prompt now!") print("ENTER 9 AGAIN TO START GETTING PROMPT AGAIN!!") @@ -167,11 +171,10 @@ else: print("NEED CORRECT KEY TO ENABLE THIS FEATURE") - # if option 0 is selected elif a == 0: print("Saving your Data ...") - outfile = open('data/pickle-main', 'wb') + outfile = open("data/pickle-main", "wb") pickle.dump(array, outfile) outfile.close() print("YOUR DATA HAS BEEN SAVED SUCESSFULLY!") diff --git a/ultimate-phone-book/readme.md b/ultimate-phone-book/readme.md index 5a9d28e65a7..dc482449bad 100644 --- a/ultimate-phone-book/readme.md +++ b/ultimate-phone-book/readme.md @@ -1,17 +1,17 @@ #### THIS PROGRAM USES [GPL V3 LICENSE](../../LICENSE) ## contacts -it's an simple phonebook allowing you to add name, contact number and email. -it's just for fun there is no use in real life. +it's an simple phonebook allowing you to add name, contact number and email. +it's just for fun there is no use in real life. #### Requirenments -a python interpretor in Windows, terminal will work in Mac & Linux. +a python interpretor in Windows, terminal will work in Mac & Linux. #### How to run? -as a **python3** program +as a **python3** program #### Contributers -created by -[**@JymPatel**](https://github.com/JymPatel) -edited by +created by +[**@JymPatel**](https://github.com/JymPatel) +edited by (editors can put their names here) diff --git a/videodownloder.py b/videodownloder.py index 6b91829e293..1db13a66c00 100644 --- a/videodownloder.py +++ b/videodownloder.py @@ -1,24 +1,25 @@ -from pytube import YouTube +from pytube import YouTube -#location where you save. -PATH = "E:/" #to_do +# location where you save. +PATH = "E:/" # to_do -#link of video. -link=["https://www.youtube.com/watch?v=p8FuTenSWPI", - "https://www.youtube.com/watch?v=JWbnEt3xuos" - ]#list of video links. -for i in link: - try: - yt = YouTube(i) - except: - print("Connection Error") #to handle exception - - #check files with "mp4" extension - mp4files = yt.filter('mp4') +# link of video. +link = [ + "https://www.youtube.com/watch?v=p8FuTenSWPI", + "https://www.youtube.com/watch?v=JWbnEt3xuos", +] # list of video links. +for i in link: + try: + yt = YouTube(i) + except: + print("Connection Error") # to handle exception - d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) - try: - d_video.download(PATH) - except: - print("Some Error!") -print('Task Completed!') + # check files with "mp4" extension + mp4files = yt.filter("mp4") + + d_video = yt.get(mp4files[-1].extension, mp4files[-1].resolution) + try: + d_video.download(PATH) + except: + print("Some Error!") +print("Task Completed!") diff --git a/vowel remover function.py b/vowel remover function.py index 5af2ff5f01e..8d6467b57dc 100644 --- a/vowel remover function.py +++ b/vowel remover function.py @@ -4,4 +4,6 @@ def vowel_remover(text): if l.lower() not in "aeiou": string += l return string + + print(vowel_remover("hello world!")) diff --git a/whatsapp-monitor.py b/whatsapp-monitor.py index 842dd1a866d..5da59acd039 100644 --- a/whatsapp-monitor.py +++ b/whatsapp-monitor.py @@ -1,20 +1,21 @@ #! /usr/bin/python3 """ -Author- Tony Stark +Author- Tony Stark download https://github.com/mozilla/geckodriver/releases -set path paste binary file /usr/local/bin +set path paste binary file /usr/local/bin install requirements: python -m pip install selenium """ -from selenium import webdriver import os import time +from selenium import webdriver + driver = webdriver.Firefox() driver.get("http://web.whatsapp.com") name = input("Please Enter Name for search online status: ") @@ -23,19 +24,19 @@ try: chat = driver.find_element_by_xpath( - "/html/body/div[1]/div/div/div[3]/div/header/div[2]/div/span/div[2]/div" + "/html/body/div[1]/div/div/div[3]/div/header/div[2]/div/span/div[2]/div", ) chat.click() time.sleep(2) search = driver.find_element_by_xpath( - "/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[1]/div/label/input" + "/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[1]/div/label/input", ) search.click() time.sleep(2) search.send_keys(name) time.sleep(2) open = driver.find_element_by_xpath( - "/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[2]/div[1]/div/div/div[2]/div/div" + "/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[2]/div[1]/div/div/div[2]/div/div", ) open.click() time.sleep(2) @@ -44,11 +45,11 @@ try: status = driver.find_element_by_class_name("_315-i").text name = driver.find_element_by_class_name("_19vo_").text - print("{0} is {1}".format(name, status)) + print(f"{name} is {status}") time.sleep(30) except: name = driver.find_element_by_class_name("_19vo_").text - print("{0} is {1}".format(name, "offline")) + print("{} is {}".format(name, "offline")) time.sleep(30) except: diff --git a/whatsapp-schedule.py b/whatsapp-schedule.py index 15fe074e81b..a71c56ffb0d 100644 --- a/whatsapp-schedule.py +++ b/whatsapp-schedule.py @@ -1,11 +1,12 @@ """ -Author- Richmond Nyamekye +Author- Richmond Nyamekye download https://github.com/mozilla/geckodriver/releases install requirements: python -m pip install selenium """ + import pywhatkit diff --git a/wifi hack by brutefore.py b/wifi hack by brutefore.py index efcbe2c9347..6a915622dd3 100644 --- a/wifi hack by brutefore.py +++ b/wifi hack by brutefore.py @@ -20,43 +20,37 @@ The following provides a simple 8 purely digital dictionary generation program codes """ - - - import itertools as its # Problems encountered do not understand? Python learning exchange group: 821 460 695 meet your needs, data base files have been uploaded, you can download their own! -if __name__ == '__main__': +if __name__ == "__main__": words_num = "1234567890" words_letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" r = its.product(words_num, repeat=8) - dic = open ( "password-8 digits .txt", "w") + dic = open("password-8 digits .txt", "w") for i in r: dic.write("".join(i)) dic.write("".join("\n")) dic.close() - - - - - - - # 2. brute force password when using longer - - -import pywifi - -from pywifi import const # quote some definitions - + + +# 2. brute force password when using longer + + import time -''' + +import pywifi +from pywifi import const # quote some definitions + +""" Problems encountered do not understand? Python learning exchange group: 821 460 695 meet your needs, data base files have been uploaded, you can download their own! -''' - +""" + + def getwifi(wifilist, wificount): - wifi = pywifi.PyWiFi () # crawled network interface cards - ifaces = wifi.interfaces () [0] # Get the card + wifi = pywifi.PyWiFi() # crawled network interface cards + ifaces = wifi.interfaces()[0] # Get the card ifaces.scan() time.sleep(8) bessis = ifaces.scan_results() @@ -64,7 +58,7 @@ def getwifi(wifilist, wificount): namelist = [] ssidlist = [] for data in bessis: - if data.ssid not in namelist: # remove duplicate names WIFI + if data.ssid not in namelist: # remove duplicate names WIFI namelist.append(data.ssid) allwifilist.append((data.ssid, data.signal)) sorted(allwifilist, key=lambda st: st[1], reverse=True) @@ -78,48 +72,48 @@ def getwifi(wifilist, wificount): ssidlist.append(item[0]) print(allwifilist) return ssidlist - - + + def getifaces(): - wifi = pywifi.PyWiFi () # crawled network interface cards - ifaces = wifi.interfaces () [0] # Get the card - ifaces.disconnect () # disconnect unlimited card connection + wifi = pywifi.PyWiFi() # crawled network interface cards + ifaces = wifi.interfaces()[0] # Get the card + ifaces.disconnect() # disconnect unlimited card connection return ifaces - - + + def testwifi(ifaces, ssidname, password): - profile = pywifi.Profile () # create a wifi connection file - profile.ssid = ssidname # define wifissid - profile.auth = open(const.AUTH_ALG_OPEN) # NIC - profile.akm.append (const.AKM_TYPE_WPA2PSK) # wifi encryption algorithm - #encrypting unit - profile.cipher = const.CIPHER_TYPE_CCMP # - profile.key = password # wifi password - ifaces.remove_all_network_profiles () # delete all other configuration files - tmp_profile = ifaces.add_network_profile (profile) # load the configuration file - ifaces.connect (tmp_profile) # wifi connection - #You can connect to the inner (5) # 5 seconds time.sleep + profile = pywifi.Profile() # create a wifi connection file + profile.ssid = ssidname # define wifissid + profile.auth = open(const.AUTH_ALG_OPEN) # NIC + profile.akm.append(const.AKM_TYPE_WPA2PSK) # wifi encryption algorithm + # encrypting unit + profile.cipher = const.CIPHER_TYPE_CCMP # + profile.key = password # wifi password + ifaces.remove_all_network_profiles() # delete all other configuration files + tmp_profile = ifaces.add_network_profile(profile) # load the configuration file + ifaces.connect(tmp_profile) # wifi connection + # You can connect to the inner (5) # 5 seconds time.sleep if ifaces.status() == const.IFACE_CONNECTED: return True else: return False - - + + def beginwork(wifinamelist): ifaces = getifaces() - path = r # password-8 digits .txt + path = r # password-8 digits .txt # Path = r "password- commonly used passwords .txt" - files = open(path, 'r') + files = open(path) while True: try: password = files.readline() - password = password.strip('\n') + password = password.strip("\n") if not password: break for wifiname in wifinamelist: - print ( "are trying to:" + wifiname + "," + password) + print("are trying to:" + wifiname + "," + password) if testwifi(ifaces, wifiname, password): - print ( "Wifi account:" + wifiname + ", Wifi password:" + password) + print("Wifi account:" + wifiname + ", Wifi password:" + password) wifinamelist.remove(wifiname) break if not wifinamelist: @@ -127,16 +121,10 @@ def beginwork(wifinamelist): except: continue files.close() - - -if __name__ == '__main__': - wifinames_e = [ "", "Vrapile"] # exclude wifi name does not crack + + +if __name__ == "__main__": + wifinames_e = ["", "Vrapile"] # exclude wifi name does not crack wifinames = getwifi(wifinames_e, 5) print(wifinames) beginwork(wifinames) - - - - - - diff --git a/wiki/requirements.txt b/wiki/requirements.txt index c07505414c0..535a82203c1 100644 --- a/wiki/requirements.txt +++ b/wiki/requirements.txt @@ -1,2 +1,2 @@ -wikipedia tkinter +wikipedia diff --git a/wiki/wiki.py b/wiki/wiki.py index 564c7e1bfd0..fdac5356c22 100644 --- a/wiki/wiki.py +++ b/wiki/wiki.py @@ -1,14 +1,15 @@ # In this program you ask it about any topic and it will show you the data from wikipedia # pip install wikipedia -import wikipedia import tkinter as tk -from tkinter import Label, Button, Entry, Text, messagebox, SOLID, GROOVE, StringVar, WORD, END -#import PIL as ImageTK -from tkinter import messagebox +# import PIL as ImageTK +from tkinter import (END, GROOVE, SOLID, WORD, Button, Entry, Label, StringVar, + Text, messagebox) + +import wikipedia -class main(): +class main: def __init__(self, root): self.root = root @@ -16,13 +17,13 @@ def __init__(self, root): self.root.geometry("1920x1080") self.lbl1 = Label( - root, - text="WIKIPEDIA SUMMARY", - font=("Verdana", 25, "bold"), - width=50, - bg="yellow", - fg="red", - relief=SOLID, + root, + text="WIKIPEDIA SUMMARY", + font=("Verdana", 25, "bold"), + width=50, + bg="yellow", + fg="red", + relief=SOLID, ) self.lbl1.pack(padx=10, pady=15) @@ -47,7 +48,7 @@ def __init__(self, root): relief=GROOVE, bg="#4cd137", bd=3, - command=lambda:self.summary("None"), + command=lambda: self.summary("None"), ) self.searchbtn.pack() @@ -67,8 +68,8 @@ def summary(self, event): self.searchbtn["text"] = "Searching..." try: self.query = wikipedia.page(self.question.get(), auto_suggest=True) - self.quesbox.delete(0, 'end') - self.answer.delete('1.0', END) + self.quesbox.delete(0, "end") + self.answer.delete("1.0", END) self.answer.insert(END, (self.query.summary)) self.answer.pack() @@ -78,9 +79,9 @@ def summary(self, event): self.searchbtn["text"] = "Search" - # Wikipeida page returns to many pages + if __name__ == "__main__": root = tk.Tk() main(root) diff --git a/wiki_random.py b/wiki_random.py index 3782ea60137..d52ecb06a9a 100644 --- a/wiki_random.py +++ b/wiki_random.py @@ -14,9 +14,11 @@ enter index of article you would like to see, or 'r' for retry and 'n' for exit. """ -import requests + import webbrowser +import requests + page_count = 10 url = ( "https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=" @@ -33,7 +35,7 @@ def load(): for idx, j in enumerate(jsonData): print(str(idx) + ": ", j["title"]) i = input( - "Which page you want to see, enter index..[r: for retry,n: exit]?" + "Which page you want to see, enter index..[r: for retry,n: exit]?", ).lower() if i == "r": print("Loading randoms again...") @@ -47,7 +49,7 @@ def load(): raise Exception("Wrong Input...") print("taking you to the browser...") webbrowser.get().open( - "https://en.wikipedia.org/wiki?curid=" + str(jsonData[int(i)]["id"]) + "https://en.wikipedia.org/wiki?curid=" + str(jsonData[int(i)]["id"]), ) load() else: diff --git a/wikipedia.py b/wikipedia.py index 18570cb1bcd..3c2c37f31ac 100644 --- a/wikipedia.py +++ b/wikipedia.py @@ -1,11 +1,13 @@ -import wikipedia from tkinter import * from tkinter.messagebox import showinfo +import wikipedia + win = Tk() # objek win.title("WIKIPEDIA") win.geometry("200x70") # function + # function def search_wiki(): search = entry.get() diff --git a/work_connect.py b/work_connect.py index bf3d4f9ed5a..cf4bb91887d 100644 --- a/work_connect.py +++ b/work_connect.py @@ -14,11 +14,12 @@ import time # Load the Library Module dropbox = os.getenv( - "dropbox" + "dropbox", ) # Set the variable dropbox, by getting the values of the environment setting for dropbox rdpfile = "remote\\workpc.rdp" # Set the variable logfile, using the arguments passed to create the logfile conffilename = os.path.join( - dropbox, rdpfile + dropbox, + rdpfile, ) # Set the variable conffilename by joining confdir and conffile together remote = ( r"c:\windows\system32\mstsc.exe " # Set the variable remote with the path to mstsc @@ -46,20 +47,20 @@ ( r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe connect -u username -p " + passwd - ) + ), ) - subprocess.Popen((r"c:\geektools\puttycm.exe")) + subprocess.Popen(r"c:\geektools\puttycm.exe") time.sleep( - 15 + 15, ) # Sleep for 15 seconds, so the checkpoint software can connect before opening mstsc subprocess.Popen([remote, conffilename]) elif ( sys.argv[1].lower().startswith("-d") ): # If the first argument is -d then disconnect my checkpoint session. subprocess.Popen( - (r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect ") + (r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect "), ) else: print( - "Unknown option - " + text + "Unknown option - " + text, ) # If any other option is passed, then print Unknown option and the text from above - 1.2 diff --git a/write_excel_file.py b/write_excel_file.py index 10bfe86044a..e235a974dc1 100644 --- a/write_excel_file.py +++ b/write_excel_file.py @@ -1,5 +1,5 @@ -import xlwt import openpyxl +import xlwt # Workbook is created xlwt_wb = xlwt.Workbook() diff --git a/youtubedownloader.py b/youtubedownloader.py index 55b5bc85990..69f571c1f83 100644 --- a/youtubedownloader.py +++ b/youtubedownloader.py @@ -1,6 +1,7 @@ +from threading import Thread from tkinter import * from tkinter import filedialog, messagebox -from threading import Thread + from pytube import YouTube @@ -9,58 +10,61 @@ def threading(): t1 = Thread(target=download) t1.start() + def download(): try: url = YouTube(str(url_box.get())) video = url.streams.first() - filename = filedialog.asksaveasfilename(defaultextension=".mp4", filetypes=[("MP4 files", "*.mp4")]) + filename = filedialog.asksaveasfilename( + defaultextension=".mp4", filetypes=[("MP4 files", "*.mp4")] + ) if filename: # Check if a filename is selected video.download(filename=filename) - messagebox.showinfo('', 'Download completed!') + messagebox.showinfo("", "Download completed!") else: - messagebox.showwarning('', 'Download cancelled!') + messagebox.showwarning("", "Download cancelled!") except Exception as e: messagebox.showerror("Error", "An error occurred while downloading the video.") - root = Tk() -root.title('YouTube Downloader') -root.geometry('780x500+200+200') -root.configure(bg='olivedrab1') +root.title("YouTube Downloader") +root.geometry("780x500+200+200") +root.configure(bg="olivedrab1") root.resizable(False, False) # Label widgets introlable = Label( root, - text='YouTube Video Downloader', + text="YouTube Video Downloader", width=30, - relief='ridge', + relief="ridge", bd=4, - font=('chiller', 26, 'italic bold'), - fg='red') + font=("chiller", 26, "italic bold"), + fg="red", +) introlable.place(x=35, y=20) Label( - root, - text='Enter YouTube Link', - font=('sans-serif', 16), - bg='olivedrab1' - ).place(x=40, y=150) + root, + text="Enter YouTube Link", + font=("sans-serif", 16), + bg="olivedrab1", +).place(x=40, y=150) url_box = Entry( - root, - font=('arial', 30), - width=30 - ) + root, + font=("arial", 30), + width=30, +) url_box.place(x=40, y=180) btn = Button( - root, - text='DOWNLOAD', - font=('sans-serif', 25), - command=threading - ) + root, + text="DOWNLOAD", + font=("sans-serif", 25), + command=threading, +) btn.place(x=270, y=240) root.mainloop() From b90bc6fbaf969e50bb785720ae45992d41801f23 Mon Sep 17 00:00:00 2001 From: Ruslan Senatorov <55090151+ruslansenatorov@users.noreply.github.com> Date: Sat, 18 May 2024 21:50:02 +0300 Subject: [PATCH 2/4] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 03c280e1cba..19bec5ba23e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# My Python Eggs 🐍 😄 +# My Python Eggs 🐍 😄.
From 486ad08fc249ec15c899f5021bcea0f121becd71 Mon Sep 17 00:00:00 2001 From: Ruslan Senatorov <55090151+ruslansenatorov@users.noreply.github.com> Date: Sun, 19 May 2024 16:18:08 +0300 Subject: [PATCH 3/4] Delete .pre-commit-config.yaml --- .pre-commit-config.yaml | 223 ---------------------------------------- 1 file changed, 223 deletions(-) delete mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 9e4510a69c3..00000000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,223 +0,0 @@ -repos: - - repo: https://github.com/asottile/add-trailing-comma - rev: v3.1.0 - hooks: - - id: add-trailing-comma - - repo: https://github.com/psf/black.git - rev: 24.4.0 - hooks: - - id: black - - repo: https://github.com/nbQA-dev/nbQA - rev: 1.8.5 - hooks: - - id: nbqa-black - name: nbqa-black - description: Run 'black' on a Jupyter Notebook - entry: nbqa black - language: python - require_serial: true - types_or: [jupyter, markdown] - additional_dependencies: [black] - - repo: https://github.com/asottile/pyupgrade - rev: v3.15.2 - hooks: - - id: pyupgrade - args: [--py39-plus] - - repo: https://github.com/pycqa/isort - rev: 5.13.2 - hooks: - - id: isort - - repo: https://github.com/adamchainz/blacken-docs - rev: 1.16.0 - hooks: - - id: blacken-docs - additional_dependencies: - - black==24.2.0 - - repo: https://github.com/nbQA-dev/nbQA - rev: 1.8.5 - hooks: - - id: nbqa-pyupgrade - name: nbqa-pyupgrade - description: Run 'pyupgrade' on a Jupyter Notebook - entry: nbqa pyupgrade - language: python - require_serial: true - types_or: [jupyter, markdown] - additional_dependencies: [pyupgrade] - - id: nbqa-isort - name: nbqa-isort - description: Run 'isort' on a Jupyter Notebook - entry: nbqa isort - language: python - require_serial: true - types_or: [jupyter, markdown] - additional_dependencies: [isort] - - - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.6.0 - hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml - - id: debug-statements - - id: name-tests-test - - id: requirements-txt-fixer - - - repo: https://github.com/codespell-project/codespell - rev: v2.2.6 - hooks: - - id: codespell - additional_dependencies: - - tomli - - - repo: https://github.com/nbQA-dev/nbQA - rev: 1.8.5 - hooks: - - id: nbqa-flake8 - args: ["--ignore=E501,E712,W291,F632,E203"] - name: nbqa-flake8 - description: Run 'flake8' on a Jupyter Notebook - entry: nbqa flake8 - language: python - require_serial: true - types_or: [jupyter, markdown] - additional_dependencies: - - flake8-variables-names - - pep8-naming - - flake8-functions-names - - - repo: https://github.com/PyCQA/flake8 - rev: 7.0.0 - hooks: - - id: flake8 - args: ["--ignore=E501,E712,W291,F632,E203"] - additional_dependencies: - - flake8-variables-names - - pep8-naming - - flake8-functions-names - - - repo: https://github.com/nbQA-dev/nbQA - rev: 1.8.5 - hooks: - - id: nbqa-mypy - name: nbqa-mypy - description: Run 'mypy' on a Jupyter Notebook - entry: nbqa mypy - language: python - require_serial: true - types_or: [jupyter, markdown] - additional_dependencies: - - mypy - - pandas-stubs - - git+https://github.com/numpy/numpy-stubs - - mypy-extensions - - types-requests - - types-PyYAML - - types-setuptools - - args: - - --cache-dir=/dev/null - - --cache-dir=nul - - --no-incremental - - --explicit-package-bases - - --ignore-missing-imports - - --disallow-untyped-calls - - --disallow-untyped-defs - - --disallow-untyped-decorators - - --strict - - --extra-checks - - --disallow-any-unimported - - --disallow-any-decorated - - --disallow-any-explicit - - --disallow-any-generics - - --disallow-subclassing-any - - --local-partial-types - - --pretty - - --force-uppercase-builtins - - --force-union-syntax - - --warn-unreachable - - --warn-redundant-casts - - --warn-return-any - - - - - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.9.0 - hooks: - - id: mypy - args: - - --cache-dir=/dev/null - - --cache-dir=nul - - --no-incremental - - --explicit-package-bases - - --ignore-missing-imports - - --disallow-untyped-calls - - --disallow-untyped-defs - - --disallow-untyped-decorators - - --strict - - --extra-checks - - --disallow-any-unimported - - --disallow-any-decorated - - --disallow-any-explicit - - --disallow-any-generics - - --disallow-subclassing-any - - --local-partial-types - - --pretty - - --force-uppercase-builtins - - --force-union-syntax - - --warn-unreachable - - --warn-redundant-casts - - --warn-return-any - - - - additional_dependencies: - - mypy - - pandas-stubs - - git+https://github.com/numpy/numpy-stubs - - mypy-extensions - - types-requests - - types-PyYAML - - types-setuptools - - - repo: https://github.com/nbQA-dev/nbQA - rev: 1.8.5 - hooks: - - id: nbqa-pylint - name: nbqa-pylint - description: Run 'pylint' on a Jupyter Notebook - entry: nbqa pylint - language: python - require_serial: true - types_or: [jupyter, markdown] - additional_dependencies: [pylint] - args: - [ - "--max-line-length=79", - "--const-naming-style=any", - "--disable=E0401,W0104", - ] - - - repo: https://github.com/pre-commit/mirrors-pylint - rev: v2.3.1 - hooks: - - id: pylint - name: pylint - entry: pylint - language: python - types: [python] - args: - [--max-line-length=79, "--const-naming-style=any", "--disable=E0401,W0104"] - additional_dependencies: [pylint] - - - repo: https://github.com/nbQA-dev/nbQA - rev: 1.8.5 - hooks: - - id: nbqa-pydocstyle - name: nbqa-pydocstyle - description: Run 'pydocstyle' on a Jupyter Notebook - entry: nbqa pydocstyle - language: python - require_serial: true - types_or: [jupyter, markdown] - additional_dependencies: [pydocstyle] From c07418f7d4035d3beb03a9fb4852c589e240520b Mon Sep 17 00:00:00 2001 From: Ruslan Senatorov <55090151+ruslansenatorov@users.noreply.github.com> Date: Sun, 19 May 2024 16:18:32 +0300 Subject: [PATCH 4/4] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 19bec5ba23e..03c280e1cba 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# My Python Eggs 🐍 😄. +# My Python Eggs 🐍 😄