├── .github └── workflows │ ├── auto_assign.yml │ ├── auto_comment.yml │ └── greetings.yml ├── AutomaticEmail ├── README.md └── customMail.py ├── BMI Calculator ├── BMI_calculator.py └── Readme.md ├── BudgetTracker └── budget_track.py ├── CO2 predictor ML model ├── About.md ├── CO2_predictor.ipynb └── vehicle_data.csv ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Calculator ├── calculator_pyside6.py └── tkinter calculator.py ├── CalculatorGUI └── main.py ├── Clock GUI └── Clock.py ├── Currency Converter └── currency_converter.py ├── Dice Rolling Simulator ├── assets │ ├── dice-six-faces-1.png │ ├── dice-six-faces-2.png │ ├── dice-six-faces-3.png │ ├── dice-six-faces-4.png │ ├── dice-six-faces-5.png │ └── dice-six-faces-6.png └── dice_rolling_sim.py ├── DigitalRecognition ├── main.py └── net.pth ├── Face Registration Recognition └── face_reg_rec.ipynb ├── Google_Logo ├── google_logo.py └── microsoft_logo.py ├── Guess_The_Number └── guess_the_number.py ├── Hand Recognition └── hand-detection.ipynb ├── ImageToTextConverter └── ImageToText.py ├── LICENSE ├── LIve Weather Using Python └── LiveWeather.py ├── Library Management System └── library.py ├── Meme Generator ├── input.png ├── meme.ipynb └── output.png ├── Merging or Spliting PDFs └── merge-split-pdfs.ipynb ├── Motivational Quotes Twitter Bot ├── main.py ├── readme └── requirements.txt ├── Number system calculator └── calculator.ipynb ├── Printing Excel sheet ├── Orders-With Nulls.xlsx ├── main.py └── readme.md ├── README.md ├── Regular-Expressions └── Regular-Expressions.py ├── Resize_Image ├── input_image.png ├── output_image.png └── resize_image.py ├── Resumenator ├── HomePage.py ├── Portfolio.png ├── Portfolio.py ├── README.md ├── Resume.jpeg ├── Resume.py ├── packages.txt ├── requirements.txt └── templates │ ├── PortfolioTemplate.html │ └── ResumeTemplate.html ├── Rock, Paper & Scissors └── game.py ├── SCRIPTS.md ├── Send_Mail └── send_mail.py ├── Shutdown └── shutdown.py ├── Speech Recognition └── speech.py ├── Talking Bot ├── about.md └── main.py ├── Task schedule ├── main.py └── tasks.db ├── Temperature Converter └── temperature_converter.py ├── Text Counter └── text_counter.py ├── Text based adventure game └── game.py ├── Text to ASCII └── ascii-art.ipynb ├── Tic Tac Toe ├── Readme.md └── tic_tac_toe.py ├── Todo-list-GUI-app └── app.py ├── Translator ├── Listen.py └── translator.ipynb ├── TurtleAnimations ├── CirclePattern.py ├── DigitalClock.py └── IndianFlag.py ├── URL Shortner └── url-shortner.ipynb ├── URL-Validator └── url_validator.py ├── Voice to text ├── Readme.md └── voice_to_text.py ├── Wallpaper └── wallpaper_changer.py ├── Weather app ├── Readme.md └── main.py ├── Weather └── weather.ipynb ├── Website_Blocker └── website_blocker.py ├── Xlsx-Writer ├── README.md ├── main.py └── modules │ ├── align.py │ └── font.py ├── anagram.py ├── concurrent-file-processing ├── README.md ├── concurrent-file-processing.py └── large_file.txt ├── desktop-notifier-task └── desktop-notifier-task.py ├── fibonacci-generation └── fibonacci-generation.py ├── hangman ├── __pycache__ │ └── words.cpython-310.pyc ├── hangman_cli.py └── words.py ├── image-gallery └── image.ipynb ├── matrix-multiplication-parallel └── matrix-multiplication-parallel.py ├── parallel_processing_example └── parallel_processing_example.py ├── passwordChecker ├── banned_passwords.txt ├── main.py └── weak_passwords.txt ├── reverse-number-script └── reverse_a_number.py ├── snake-game ├── food.py ├── main.py ├── scoreboard.py └── snake.py ├── sort-algorithm-comparison ├── comparision.py ├── quick-sort.py └── radix-sort.py ├── spark-data-transformation └── spark-data-transformation.py ├── sudoku-solver ├── __pycache__ │ ├── generate_board.cpython-310.pyc │ └── sudoku_lp.cpython-310.pyc ├── example.py ├── generate_board.py ├── main.py └── sudoku_lp.py ├── timer └── main.py ├── weatherAppCLI ├── .DS_Store ├── README.md ├── requirements.txt └── weatherAppCLI.py └── word_definitions ├── read_me.txt └── word_definition_and_meanings.py /.github/workflows/auto_assign.yml: -------------------------------------------------------------------------------- 1 | name: Auto Assign 2 | 3 | on: 4 | issue_comment: 5 | types: [created] 6 | 7 | jobs: 8 | assign_issues: 9 | if: > 10 | (github.event_name == 'issue_comment' && ( 11 | startsWith(github.event.comment.body, '/assign') || 12 | startsWith(github.event.comment.body, '/unassign') || 13 | contains(github.event.comment.body, 'assign to me') || 14 | contains(github.event.comment.body, 'please assign me this') || 15 | contains(github.event.comment.body, 'assign this to me') || 16 | contains(github.event.comment.body, 'assign this issue to me') || 17 | contains(github.event.comment.body, 'I can try fixing this') || 18 | contains(github.event.comment.body, 'i am interested in doing this') || 19 | contains(github.event.comment.body, 'I am interested in contributing'))) || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Check for issue assignees 23 | id: check-assignees 24 | uses: actions/github-script@v4 25 | with: 26 | github-token: ${{ secrets.GITHUB_TOKEN }} 27 | script: | 28 | const issueNumber = context.payload.issue.number; 29 | if (issueNumber) { 30 | const commenter = context.payload.comment.user.login; 31 | const { data: issueData } = await github.issues.get({ 32 | owner: 'Swapnil-Singh-99', 33 | repo: 'PythonScriptsHub', 34 | issue_number: issueNumber 35 | }); 36 | 37 | const assignees = issueData.assignees.map(assignee => assignee.login); 38 | 39 | if (!assignees.length) { 40 | const config = { 41 | owner: 'Swapnil-Singh-99', 42 | repo: 'PythonScriptsHub', 43 | issue_number: issueNumber, 44 | assignees: [commenter] 45 | }; 46 | return github.issues.addAssignees(config); 47 | } 48 | } 49 | return true; 50 | -------------------------------------------------------------------------------- /.github/workflows/auto_comment.yml: -------------------------------------------------------------------------------- 1 | name: Auto Comment 2 | on: 3 | issues: 4 | types: 5 | - opened 6 | - closed 7 | - assigned 8 | pull_request: 9 | types: 10 | - opened 11 | - closed 12 | 13 | jobs: 14 | run: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Check Author 18 | id: check_author 19 | run: echo "Author=${{ github.event.issue.user.login }}" 20 | 21 | - name: Auto Comment on Issues Opened 22 | uses: wow-actions/auto-comment@v1 23 | with: 24 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 25 | issuesOpened: | 26 | {{#if eq github.repository.owner.login author}} 27 | 👋 @{{ author }} 28 | 29 | Thank you for raising this issue! We'll look into it ASAP. 30 | 31 | Don't forget to give a ⭐️ & Happy coding!. 😊 32 | {{else}} 33 | 👋 @{{ author }} 34 | 35 | Thank you for raising this issue! We'll look into it ASAP. 36 | 37 | As a contributor, we appreciate your help in improving this project! 😊 38 | {{/if}} 39 | - name: Auto Comment on Issues Closed 40 | uses: wow-actions/auto-comment@v1 41 | with: 42 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 43 | issuesClosed: | 44 | 👋 @{{ assignee }} This issue is closed. 45 | Don't forget to give a ⭐️ & Happy coding!. 😊 46 | 47 | - name: Auto Comment on Pull Request Merged 48 | uses: wow-actions/auto-comment@v1 49 | with: 50 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 51 | pullRequestMerged: | 52 | 👋 @{{ author }} 🎉 Congrats on your merged pull request! Thanks for the valuable contribution! 53 | Don't forget to give a ⭐️ & Happy coding!. 😊 54 | 55 | - name: Auto Comment on Pull Request Opened 56 | uses: wow-actions/auto-comment@v1 57 | with: 58 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 59 | pullRequestOpened: | 60 | Hello👋 @{{ author }}, I hope you are doing well! 61 |
62 | Thank you for raising your pull request and contributing to our repository 🎉 63 | 64 | Please make sure you have followed our contributing guidelines. We will review it ASAP. 65 | 66 | Don't forget to give a ⭐️ & Happy coding!. 😊 67 | 68 | - name: Auto Comment on Issues Assigned 69 | uses: wow-actions/auto-comment@v1 70 | with: 71 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 72 | issuesAssigned: | 73 | Hello @{{ assignee }}, thank you for raising an issue. 🙌 I have assigned the issue to you. You can now start working on it. If you encounter any problems, please feel free to connect with us. 👍 74 | Don't forget to give a ⭐️ & Happy coding!. 😊 75 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request_target, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | steps: 12 | - uses: actions/first-interaction@v1 13 | with: 14 | repo-token: ${{ secrets.GITHUB_TOKEN }} 15 | issue-message: "Hello @${{ github.actor }}! \nCongratulations on opening your first issue in the PythonScriptsHub repository! 🎉 Your contribution is valuable to us! 😊 \n\nPlease make sure to follow our [Contributing Guidelines. 💪🏻](https://github.com/Swapnil-Singh-99/PythonScriptsHub/blob/main/CONTRIBUTING.md) \n\nOur review team will carefully assess the issue and reach out to you soon! \n We appreciate your patience! " 16 | pr-message: "Thank you, @${{ github.actor }}, on submitting your very first pull request to the PythonScriptsHub repository! 🥳\n\n The maintainers will review this Pull Request and provide feedback as soon as possible! \nWe appreciate your patience and contribution, Keep up the great work! 😀" 17 | -------------------------------------------------------------------------------- /AutomaticEmail/README.md: -------------------------------------------------------------------------------- 1 | To work with this script, ensure that 2 | 3 | 1. You replace "sender@email.com" with the sender's actual email ID. 4 | 5 | 2. Replace "receipient@email.com" with the necessary email ID. 6 | 7 | 3. Replace subject and message with relevant items 8 | 9 | 4. "App_password" needs to be replaced with the app password that can be set up on your google account - https://myaccount.google.com/u/4/apppasswords?utm_source=google-account&utm_medium=myaccountsecurity&utm_campaign=tsv-settings&rapt=AEjHL4PSmbgmsfHCUJm13fkwQMT63XUxJ_hRV6WWWWT958fGA7fUZBtskBV-hTNMcteXmkrZMZGH3hlMvoKHV-mhsuHXDgZM6Q 10 | 11 | -------------------------------------------------------------------------------- /AutomaticEmail/customMail.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | from email.mime.multipart import MIMEMultipart 3 | from email.mime.text import MIMEText 4 | 5 | sender_email = "sender@email.com" 6 | receiver_email = "receipient@email.com" 7 | password = "App_password" # App Password if using 2FA 8 | subject = "Custom Subject" 9 | message = "Hello, this is a custom email message!" 10 | 11 | msg = MIMEMultipart() 12 | msg['From'] = sender_email 13 | msg['To'] = receiver_email 14 | msg['Subject'] = subject 15 | msg.attach(MIMEText(message, 'plain')) 16 | 17 | try: 18 | s = smtplib.SMTP('smtp.gmail.com', 587) 19 | 20 | # start TLS for security 21 | s.starttls() 22 | 23 | # Authentication 24 | s.login(sender_email, password) 25 | 26 | # message to be sent 27 | text = msg.as_string() 28 | 29 | # sending the mail 30 | s.sendmail(sender_email, receiver_email, text) 31 | 32 | # terminating the session 33 | s.quit() 34 | 35 | print("email sent successfully") 36 | 37 | except Exception as e: 38 | 39 | print("An error occurred: ", str(e)) -------------------------------------------------------------------------------- /BMI Calculator/BMI_calculator.py: -------------------------------------------------------------------------------- 1 | height = float(input("enter your height in m: ")) 2 | weight = float(input("enter your weight in kg: ")) 3 | 4 | bmi = round(weight / (height**2)) 5 | 6 | if bmi <= 18.5: 7 | print(f"Your BMI is {bmi}, you are underweight.") 8 | elif bmi <= 25: 9 | print(f"Your BMI is {bmi}, you have a normal weight.") 10 | elif bmi <= 30: 11 | print(f"Your BMI is {bmi}, you are slightly overweight.") 12 | elif bmi <= 35: 13 | print(f"Your BMI is {bmi}, you are obese.") 14 | else: 15 | print(f"Your BMI is {bmi}, you are clinically obese.") -------------------------------------------------------------------------------- /BMI Calculator/Readme.md: -------------------------------------------------------------------------------- 1 | # BMI Calculator 2 | 3 | This Python script calculates your Body Mass Index (BMI) based on your height and weight and provides a classification of your weight status. 4 | 5 | ## Features 6 | 7 | - Calculates BMI based on user-provided height (in meters) and weight (in kilograms). 8 | - Provides a classification of weight status, including underweight, normal weight, slightly overweight, obese, and clinically obese. 9 | 10 | ## Usage 11 | 12 | 1. Run the script by executing the following command: 13 | 14 | ```bash 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /BudgetTracker/budget_track.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from random import choice 3 | import matplotlib.pyplot as plt 4 | 5 | print("BUDGET TRACKER\n") 6 | 7 | print("Enter amount of money spent on each category\nAlso reply with Y/N if asked.\n") 8 | 9 | tips = { 10 | "Food": ["Avoid fast food", "Do not go for shopping empty stomach", "Cook at home more often", "Plan meals ahead"], 11 | "Travel": ["Use public transport", "Look for travel deals", "Book flights in advance", "Stay in budget accommodations"], 12 | "Shopping": ["Make a shopping list", "Wait for sales and discounts", "Compare prices before buying", "Avoid impulsive purchases"], 13 | "HealthCare": ["Use generic medicines", "Opt for preventive care", "Shop around for healthcare services", "Maintain a healthy lifestyle"], 14 | "Miscellaneous": ["Limit impulse purchases", "Track small expenses", "Cancel unused subscriptions", "DIY whenever possible"] 15 | } 16 | 17 | spend_analytics = ["Food", "Travel", "Shopping", "HealthCare", "Miscellaneous", "Savings"] 18 | 19 | spending_data = {} 20 | 21 | # Asks user for income 22 | income = float(input("Enter your income: ")) 23 | 24 | # We use [:-1] to Exclude "Savings" 25 | for category in spend_analytics[:-1]: 26 | amount = float(input(f"Enter spending on {category}: ")) 27 | spending_data[category] = amount 28 | 29 | total_spending = sum(spending_data.values()) 30 | savings = income - total_spending 31 | spending_data["Savings"] = savings 32 | 33 | percentages = {} 34 | for category, amount in spending_data.items(): 35 | percentage = (amount / income) * 100 36 | percentages[category] = percentage 37 | 38 | # Display spending analysis 39 | print("\nSpending Analysis:") 40 | for category, percentage in percentages.items(): 41 | print(f"{category}: {percentage:.2f}% of total income") 42 | 43 | print(f"\nTotal Income: {income}") 44 | print(f"Total Savings: {savings}\n") 45 | 46 | major_spending_category = max(percentages, key=percentages.get) 47 | if major_spending_category in tips: 48 | random_tip = choice(tips[major_spending_category]) 49 | print(f"Tip for {major_spending_category}: {random_tip}") 50 | 51 | save_csv = input("Do you want to save to CSV? (Y/N): ") 52 | if save_csv.lower() in ["yes",'y']: 53 | with open('spending_data.csv', mode='w', newline='') as file: 54 | writer = csv.writer(file) 55 | writer.writerow(['Type', 'Amount']) 56 | writer.writerow(['Income', income]) 57 | for category, amount in spending_data.items(): 58 | writer.writerow([category, amount]) 59 | 60 | show_pie_chart = input("Do you want to view the pie chart? (Y/N): ") 61 | if show_pie_chart.lower() in ["yes",'y']: 62 | labels = list(percentages.keys()) 63 | sizes = list(percentages.values()) 64 | 65 | fig1, ax1 = plt.subplots() 66 | ax1.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90) 67 | ax1.axis('equal') 68 | plt.title("Spending Breakdown") 69 | plt.show() 70 | -------------------------------------------------------------------------------- /CO2 predictor ML model/About.md: -------------------------------------------------------------------------------- 1 | # CO2 emmision predictor 2 | - This is a Machine learning model which 3 | - It takes input of number of car engines, size of engine etc. 4 | - And predicts what can be the possible emmission of CO2 by the new model of car 5 | - The model uses linear regression 6 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | ---- 3 | 4 | ## Our Pledge 5 | 6 | As project administrators and mentors, we are committed to creating an environment where everyone can participate without facing harassment, regardless of race, gender, sexual orientation, age, education, experience level, nationality, religion, disability, or body size. 7 | 8 | We pledge to foster an inclusive, diverse, open, welcoming, and healthy community through our actions and interactions. 9 | 10 | ## Our Standards 11 | 12 | Examples of unacceptable behavior include: 13 | 14 | - Use of sexually explicit language or imagery, including unwelcome sexual advances. 15 | - Derogatory comments, personal attacks, or politically motivated statements. 16 | - Sharing others' private information without explicit permission. 17 | - Harassment in public or private contexts. 18 | - Any behavior that could be deemed inappropriate in a professional setting. 19 | 20 | Examples of behavior that contributes to a positive environment: 21 | 22 | - Demonstrating kindness and empathy towards others. 23 | - Using respectful, inclusive language. 24 | - Offering and receiving feedback gracefully. 25 | - Taking responsibility and apologizing for mistakes. 26 | - Prioritizing the well-being of the entire community. 27 | 28 | ## Enforcement Responsibilities 29 | 30 | The project maintainers are responsible for defining and enforcing acceptable behavior standards. They will take fair and appropriate corrective measures in response to any inappropriate behavior. 31 | 32 | Project maintainers have the authority to edit, remove, or reject comments, code, issues, pull requests, and other contributions that do not align with this Code of Conduct. They will communicate the reasons for moderation decisions when necessary. 33 | 34 | ## Scope 35 | 36 | This Code of Conduct applies to project administrators, mentors, and all participants across all community spaces. 37 | 38 | ## Enforcement 39 | 40 | Any instances of harassment, abuse, or unacceptable behavior can be reported to project administrators for enforcement by emailing [swapnilskumar99@gmail.com](mailto:swapnilskumar99@gmail.com). All reports will be promptly and fairly reviewed and investigated. 41 | 42 | Project administrators are committed to respecting the privacy of the person reporting the incident. 43 | 44 | ## Enforcement Guidelines 45 | 46 | Project administrators will follow these Community Impact Guidelines when determining consequences for actions that breach this Code of Conduct: 47 | 48 | ### 1. Correction 49 | 50 | **Community Impact**: Use of inappropriate language or any behavior deemed unprofessional or unwelcome in the community. 51 | 52 | **Consequence**: A private warning from project administrators, clearly outlining the violation and explaining why the behavior was inappropriate. An apology may be requested. 53 | 54 | ### 2. Warning 55 | 56 | **Community Impact**: A violation through a single incident or series of actions. 57 | 58 | **Consequence**: A warning issued with potential consequences for ongoing behavior. No contact with involved parties, including those enforcing the Code of Conduct, for a defined period. This includes refraining from engagement in all community spaces. Further violation could result in temporary or permanent banning. 59 | 60 | ### 4. Permanent Ban 61 | 62 | **Community Impact**: Demonstrating a consistent pattern of violating community standards, including continuous inappropriate behavior, harassment, or targeting specific individuals or groups. 63 | 64 | **Consequence**: A permanent ban from all community interactions. 65 | 66 | ## Attribution 67 | 68 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), with the Community Impact Guidelines inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 69 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Within this documentation, you'll find a collection of instructions designed to assist you as you contribute. We're delighted to invite contributions from anyone interested in enhancing or introducing new scripts to this repository. Your assistance is greatly appreciated, and **it's important to keep in mind that every contribution, regardless of size, is valued.** 4 | 5 | 6 | # Submitting Contributions👩‍💻👨‍💻 7 | Below you will find the process and workflow used to review and merge your changes. 8 | ## Step 1 : Find an issue 9 | - Check out the current listed issue or raise your own issue. 10 | - Once you're assigned a specific issue, you can start working on it. 11 | - Remember: Any changes to this repository has to be linked to is respective issue. 12 | 13 | ![Screenshot1](https://i.postimg.cc/Y9dqH6wC/Screenshot-from-2023-08-25-13-31-46-1.jpg) 14 | 15 | ## Step 2 : Fork the Project 16 | - Fork the repository to make a copy of it on your own github profile. Make sure to have `upstream` as main. 17 | ``` 18 | $ git clone https://github.com//PythonScriptsHub 19 | $ cd PythonScriptsHub 20 | $ git remote add upstream https://github.com/Swapnil-Singh-99/PythonScriptsHub 21 | ``` 22 | ![Screenshot2](https://i.postimg.cc/GpFht0vt/image.jpg) 23 | 24 | 25 | - If you have already forked the project, update your copy before working. 26 | ![Screenshot3](https://i.postimg.cc/cL4QQSsK/image-2.jpg) 27 | ## Step 3 : Branch 28 | Create a new branch. Use its name to identify the issue your addressing. 29 | ``` 30 | # It will create a new branch with name branch_name and switch to that branch 31 | $ git checkout -b branch_name 32 | ``` 33 | ## Step 4 : Work on the issue assigned 34 | - Work on the issue(s) assigned to you. 35 | - Add all the files/folders needed. 36 | - After you've made changes or made your contribution to the repository add changes to the branch you've just created: 37 | ``` 38 | # To add all new files to branch branch_name 39 | $ git add . 40 | ``` 41 | ## Step 5 : Commit 42 | - To commit give a message describing the changes made, for the convenience of reveiwer by: 43 | ``` 44 | # This message will appear with the changes you have made 45 | $ git commit -m "message" 46 | ``` 47 | ## Step 6 : Work Remotely 48 | - Now you are ready to push your work to the remote repository. 49 | - Once your work is ready and follows the [Contributing Guidelines](https://github.com/Swapnil-Singh-99/PythonScriptsHub/blob/main/CONTRIBUTING.md). 50 | ``` 51 | # To push your work to your remote repository 52 | $ git push -u origin branch_name 53 | ``` 54 | 55 | ## Step 7 : Pull Request 56 | - Go to your repository in browser and click on compare and pull requests. Then add a title and description to your pull request that explains your contribution or the changes you have made. 57 | 58 | - Great job! Your Pull Request has been sent and the moderators will review it before merging it to main branch. 🎉 59 | ![Screenshot4](https://i.postimg.cc/W3xgMF5S/image-4.jpg) 60 | 61 | ## Need more help?🤔 62 | You can refer to the following articles on basics of Git and Github and also contact the Project Mentors, in case you are stuck: 63 | - [Fork a repo](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) 64 | - [Creating an issue or pull request](https://help.github.com/en/desktop/contributing-to-projects/creating-an-issue-or-pull-request) 65 | - [How to create a pull request in GitHub](https://opensource.com/article/19/7/create-pull-request-github) 66 | - [Getting started with Git and GitHub](https://towardsdatascience.com/getting-started-with-git-and-github-6fcd0f2d4ac6 67 | 68 | 69 | 70 | ## Tip from us😇 71 | **Your Contributions Make a Difference!** 72 | 73 | Every line of code, every idea shared, and every issue reported contributes to the growth of our repository. Your efforts bring life to this open-source community. Remember, no contribution is too small – each one is a step towards making something amazing. So, let your creativity flow and your code shine. Together, let's build something incredible! 74 | -------------------------------------------------------------------------------- /Calculator/calculator_pyside6.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | import re 4 | from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, \ 5 | QPushButton, QLineEdit, QGridLayout, QSizePolicy, \ 6 | QMenuBar, QMenu, QMessageBox 7 | from PySide6.QtCore import Qt 8 | from PySide6.QtGui import QFont 9 | from PySide6.QtGui import QAction 10 | 11 | 12 | class Calculator(QMainWindow): 13 | def __init__(self): 14 | super().__init__() 15 | 16 | self.setWindowTitle("Calculator") 17 | self.setGeometry(100, 100, 300, 400) 18 | 19 | self.init_ui() 20 | self.answer_given = False 21 | 22 | def init_ui(self): 23 | central_widget = QWidget(self) 24 | self.setCentralWidget(central_widget) 25 | 26 | layout = QVBoxLayout() 27 | 28 | menu_bar = self.create_menu() 29 | layout.setMenuBar(menu_bar) 30 | 31 | self.result_display = QLineEdit() 32 | self.result_display.setReadOnly(True) 33 | self.result_display.setAlignment(Qt.AlignRight) 34 | self.result_display.setFixedHeight(50) 35 | 36 | display_font = QFont("Calculator", 24) 37 | self.result_display.setFont(display_font) 38 | 39 | layout.addWidget(self.result_display) 40 | 41 | button_layout = QGridLayout() 42 | button_layout.setSpacing(5) 43 | 44 | button_font = QFont("Arial", 14, QFont.Bold) 45 | button_style = ''' 46 | QPushButton { 47 | background-color: #424242; 48 | color: white; 49 | border-radius: 5px; 50 | } 51 | QPushButton:hover { 52 | background-color: #616161; 53 | } 54 | QPushButton:pressed { 55 | background-color: #757575; 56 | } 57 | ''' 58 | 59 | buttons = [ 60 | ('7', 0, 0), ('8', 0, 1), ('9', 0, 2), ('/', 0, 3), 61 | ('4', 1, 0), ('5', 1, 1), ('6', 1, 2), ('*', 1, 3), 62 | ('1', 2, 0), ('2', 2, 1), ('3', 2, 2), ('-', 2, 3), 63 | ('0', 3, 0), ('.', 3, 1), ('+', 3, 2), ('=', 3, 3), 64 | ('√', 4, 0), ('^', 4, 1), 65 | ('C', 4, 2), ('CE', 4, 3) 66 | ] 67 | 68 | for button_text, row, col in buttons: 69 | button = QPushButton(button_text) 70 | button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) 71 | button.clicked.connect(self.on_button_clicked) 72 | button.setFont(button_font) 73 | button.setStyleSheet(button_style) 74 | button_layout.addWidget(button, row, col) 75 | 76 | layout.addLayout(button_layout) 77 | central_widget.setLayout(layout) 78 | 79 | def create_menu(self): 80 | menu_bar = QMenuBar(self) 81 | 82 | file_menu = QMenu("File", self) 83 | exit_action = QAction("Exit", self) 84 | exit_action.triggered.connect(self.close) 85 | file_menu.addAction(exit_action) 86 | menu_bar.addMenu(file_menu) 87 | 88 | help_menu = QMenu("Help", self) 89 | about_action = QAction("About", self) 90 | about_action.triggered.connect(self.show_about_dialog) 91 | help_menu.addAction(about_action) 92 | menu_bar.addMenu(help_menu) 93 | 94 | return menu_bar 95 | 96 | def show_about_dialog(self): 97 | QMessageBox.about(self, "About Calculator", "A simple calculator built with PySide6.") 98 | 99 | def on_button_clicked(self): 100 | sender = self.sender() 101 | button_text = sender.text() 102 | 103 | if button_text == "=": 104 | try: 105 | result = eval(re.sub(r'√(\d+)', r'math.sqrt(\1)', str(self.result_display.text()))) 106 | if result == int(result): 107 | result = int(result) 108 | self.result_display.setText(str(result)) 109 | self.answer_given = True 110 | except Exception as e: 111 | QMessageBox.warning(sender, "Warning", str(e)) 112 | self.result_display.setText("") 113 | elif button_text in {'+', '-', '*', '/', '**', '√'}: 114 | if self.answer_given: 115 | self.answer_given = False 116 | self.result_display.setText(self.result_display.text() + button_text) 117 | elif button_text.isdigit() or button_text == ".": 118 | if not self.answer_given: 119 | self.result_display.setText(self.result_display.text() + button_text) 120 | elif button_text == "^": 121 | self.result_display.setText(self.result_display.text() + "**") 122 | elif button_text == "C": 123 | self.result_display.setText("") 124 | self.answer_given = False 125 | elif button_text == "CE": 126 | current_text = self.result_display.text() 127 | self.result_display.setText(current_text[:-1]) 128 | if self.answer_given: 129 | self.answer_given = False 130 | 131 | 132 | if __name__ == "__main__": 133 | app = QApplication(sys.argv) 134 | calculator = Calculator() 135 | calculator.show() 136 | sys.exit(app.exec()) -------------------------------------------------------------------------------- /Calculator/tkinter calculator.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import math 3 | from tkinter import * 4 | 5 | root = Tk() 6 | root.title("Calculator") 7 | 8 | display = Entry(root, font=10) 9 | display.grid(row=1, columnspan=6, sticky=W + E) 10 | 11 | 12 | # get the user input and place it in the textfield 13 | 14 | 15 | def clear() -> None: 16 | display.delete(0, END) 17 | 18 | 19 | def undo() -> None: 20 | entire_string = display.get() 21 | if entire_string: 22 | display.delete(display.index(END) - 1) 23 | else: 24 | clear() 25 | 26 | 27 | def get_operation(opr): 28 | display.insert(INSERT, opr) 29 | 30 | 31 | def factorial(x: int) -> int: 32 | return math.factorial(x) 33 | 34 | 35 | def calculate() -> None: 36 | try: 37 | result = eval(display.get()) 38 | except SyntaxError: 39 | result = "Error" 40 | clear() 41 | display.insert(0, result) 42 | 43 | 44 | # adding button to the calculator 45 | 46 | for j in range(1, 11): 47 | Button( 48 | root, text=str(n := j % 10), command=functools.partial(display.insert, index=INSERT, string=n), width=10 49 | ).grid(row=(j + 5) // 3, column=(j + 2) % 3) 50 | 51 | Button(root, text="AC", command=lambda: clear(), width=10).grid(row=5, column=1) 52 | Button(root, text="=", command=lambda: calculate(), width=10).grid(row=5, column=2) 53 | Button(root, text="->", command=lambda: undo(), width=10).grid(row=2, column=3) 54 | 55 | for j in zip( 56 | ('+', '-', '*', '/', '.', '%', '(', ')', 'exp', 'x!', '^2'), 57 | ('+', '-', '*', '/', '.', '%', '(', ')', '**', 'factorial(', '**2'), 58 | (3, 4, 5, 5, 3, 4, 2, 2, 3, 4, 5), 59 | (3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5), 60 | ): 61 | Button( 62 | root, text=j[0], command=functools.partial(display.insert, index=INSERT, string=j[1]), width=10 63 | ).grid(row=j[2], column=j[3]) 64 | 65 | root.mainloop() 66 | -------------------------------------------------------------------------------- /CalculatorGUI/main.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | root = Tk() 4 | root.geometry('540x600') 5 | 6 | label = Label(root, text="Calculator GUI") 7 | label.grid(row=0, column=0) 8 | 9 | integerValue = StringVar() 10 | integerValue.set("") # Initially the field is empty 11 | 12 | inputField = Entry(root, textvariable=integerValue, font="lucida 40 bold") 13 | inputField.grid(row=1, column=0) 14 | 15 | 16 | def get_data(e): 17 | global integerValue 18 | text = e.widget.cget("text") 19 | if text == "=": 20 | try: 21 | result = str(eval(integerValue.get())) 22 | integerValue.set(result) 23 | except ZeroDivisionError: 24 | integerValue.set("Division by Zero") 25 | except Exception as e: 26 | integerValue.set("Error") 27 | elif text == "C": 28 | integerValue.set("") 29 | elif text == "<": 30 | current_value = integerValue.get() 31 | if current_value: 32 | new_value = current_value[:-1] 33 | integerValue.set(new_value) 34 | else: 35 | integerValue.set(integerValue.get() + text) 36 | 37 | 38 | fr = Frame(root, bg='grey') 39 | 40 | btn = Button(fr, text="9", padx=20, pady=20, font="lucida 30 bold") 41 | btn.bind('', get_data) 42 | btn.grid(row=0, column=1) 43 | 44 | btn = Button(fr, text="8", padx=20, pady=20, font="lucida 30 bold") 45 | btn.bind('', get_data) 46 | btn.grid(row=0, column=2) 47 | 48 | btn = Button(fr, text="7", padx=20, pady=20, font="lucida 30 bold") 49 | btn.bind('', get_data) 50 | btn.grid(row=0, column=3) 51 | 52 | btn = Button(fr, text="6", padx=20, pady=20, font="lucida 30 bold") 53 | btn.bind('', get_data) 54 | btn.grid(row=1, column=1) 55 | 56 | btn = Button(fr, text="5", padx=20, pady=20, font="lucida 30 bold") 57 | btn.bind('', get_data) 58 | btn.grid(row=1, column=2) 59 | 60 | btn = Button(fr, text="4", padx=20, pady=20, font="lucida 30 bold") 61 | btn.bind('', get_data) 62 | btn.grid(row=1, column=3) 63 | 64 | btn = Button(fr, text="3", padx=20, pady=20, font="lucida 30 bold") 65 | btn.bind('', get_data) 66 | btn.grid(row=2, column=1) 67 | 68 | btn = Button(fr, text="2", padx=20, pady=20, font="lucida 30 bold") 69 | btn.bind('', get_data) 70 | btn.grid(row=2, column=2) 71 | 72 | btn = Button(fr, text="1", padx=20, pady=20, font="lucida 30 bold") 73 | btn.bind('', get_data) 74 | btn.grid(row=2, column=3) 75 | 76 | btn = Button(fr, text="0", padx=20, pady=20, font="lucida 30 bold") 77 | btn.bind('', get_data) 78 | btn.grid(row=3, column=1) 79 | 80 | btn = Button(fr, text="*", padx=20, pady=20, font="lucida 30 bold") 81 | btn.bind('', get_data) 82 | btn.grid(row=3, column=2) 83 | 84 | btn = Button(fr, text="=", padx=20, pady=20, font="lucida 30 bold") 85 | btn.bind('', get_data) 86 | btn.grid(row=3, column=3) 87 | 88 | btn = Button(fr, text="/", padx=20, pady=20, font="lucida 30 bold") 89 | btn.bind('', get_data) 90 | btn.grid(row=4, column=1) 91 | 92 | btn = Button(fr, text="+", padx=20, pady=20, font="lucida 30 bold") 93 | btn.bind('', get_data) 94 | btn.grid(row=4, column=2) 95 | 96 | btn = Button(fr, text="-", padx=20, pady=20, font="lucida 30 bold") 97 | btn.bind('', get_data) 98 | btn.grid(row=4, column=3) 99 | 100 | btn = Button(fr, text="C", padx=20, pady=20, font="lucida 30 bold") 101 | btn.bind('', get_data) 102 | btn.grid(row=5, column=1) 103 | 104 | btn = Button(fr, text="<", padx=20, pady=20, font="lucida 30 bold") 105 | btn.bind('', get_data) 106 | btn.grid(row=5, column=2) 107 | 108 | fr.grid() 109 | root.mainloop() 110 | -------------------------------------------------------------------------------- /Clock GUI/Clock.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import time 3 | 4 | def update_clock(): 5 | current_time = time.strftime("%H:%M:%S") 6 | clock_label.config(text=current_time) 7 | root.after(1000, update_clock) 8 | 9 | root = tk.Tk() 10 | root.title("Clock") 11 | 12 | clock_label = tk.Label(root, font=("Helvetica", 48)) 13 | clock_label.pack(padx=20, pady=20) 14 | 15 | update_clock() 16 | 17 | root.mainloop() 18 | -------------------------------------------------------------------------------- /Currency Converter/currency_converter.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from forex_python.converter import CurrencyRates 3 | 4 | def convert_currency(): 5 | amount = float(entry_amount.get()) 6 | from_currency = combo_from_currency.get() 7 | to_currency = combo_to_currency.get() 8 | 9 | currency_converter = CurrencyRates() 10 | converted_amount = currency_converter.convert(from_currency, to_currency, amount) 11 | 12 | result_label.config(text=f"Converted Amount: {converted_amount:.2f} {to_currency}") 13 | root = tk.Tk() 14 | root.title("Currency Converter") 15 | currencies = [ 16 | 'USD', # United States Dollar 17 | 'EUR', # Euro 18 | 'GBP', # British Pound Sterling 19 | 'JPY', # Japanese Yen 20 | 'AUD', # Australian Dollar 21 | 'CAD', # Canadian Dollar 22 | 'CHF', # Swiss Franc 23 | 'CNY', # Chinese Yuan 24 | 'INR', # Indian Rupee 25 | 'SGD', # Singapore Dollar 26 | 'MYR', # Malaysian Ringgit 27 | 'NZD', # New Zealand Dollar 28 | 'ZAR', # South African Rand 29 | 'BRL', # Brazilian Real 30 | 'RUB', # Russian Ruble 31 | 'TRY', # Turkish Lira 32 | 'AED', # United Arab Emirates Dirham 33 | 'SAR', # Saudi Riyal 34 | 'MXN', # Mexican Peso 35 | 'IDR', # Indonesian Rupiah 36 | ] 37 | label_amount = tk.Label(root, text="Enter Amount:") 38 | label_amount.grid(row=0, column=0, pady=10) 39 | 40 | entry_amount = tk.Entry(root) 41 | entry_amount.grid(row=0, column=1, padx=10, pady=10, columnspan=2) 42 | 43 | label_from_currency = tk.Label(root, text="From Currency:") 44 | label_from_currency.grid(row=1, column=0, pady=10) 45 | 46 | combo_from_currency = tk.StringVar() 47 | combo_from_currency.set(currencies[0]) 48 | from_currency_menu = tk.OptionMenu(root, combo_from_currency, *currencies) 49 | from_currency_menu.grid(row=1, column=1, padx=10) 50 | 51 | label_to_currency = tk.Label(root, text="To Currency:") 52 | label_to_currency.grid(row=1, column=2) 53 | 54 | combo_to_currency = tk.StringVar() 55 | combo_to_currency.set(currencies[1]) 56 | to_currency_menu = tk.OptionMenu(root, combo_to_currency, *currencies) 57 | to_currency_menu.grid(row=1, column=3, padx=10) 58 | 59 | convert_button = tk.Button(root, text="Convert", command=convert_currency) 60 | convert_button.grid(row=2, column=0, pady=10) 61 | 62 | result_label = tk.Label(root, text="", font=("Arial", 12, "bold")) 63 | result_label.grid(row=3, column=0, columnspan=4, padx=10) 64 | 65 | root.mainloop() 66 | -------------------------------------------------------------------------------- /Dice Rolling Simulator/assets/dice-six-faces-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Dice Rolling Simulator/assets/dice-six-faces-1.png -------------------------------------------------------------------------------- /Dice Rolling Simulator/assets/dice-six-faces-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Dice Rolling Simulator/assets/dice-six-faces-2.png -------------------------------------------------------------------------------- /Dice Rolling Simulator/assets/dice-six-faces-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Dice Rolling Simulator/assets/dice-six-faces-3.png -------------------------------------------------------------------------------- /Dice Rolling Simulator/assets/dice-six-faces-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Dice Rolling Simulator/assets/dice-six-faces-4.png -------------------------------------------------------------------------------- /Dice Rolling Simulator/assets/dice-six-faces-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Dice Rolling Simulator/assets/dice-six-faces-5.png -------------------------------------------------------------------------------- /Dice Rolling Simulator/assets/dice-six-faces-6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Dice Rolling Simulator/assets/dice-six-faces-6.png -------------------------------------------------------------------------------- /Dice Rolling Simulator/dice_rolling_sim.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import random 3 | from PIL import Image, ImageTk 4 | 5 | def roll_dice (): 6 | random_number = random.randint(1, 6) 7 | result.set(random_number) 8 | dice_image.config(image=dice_resized_images[random_number - 1]) 9 | 10 | def roll_dice_animation(frames_left=10): 11 | if frames_left > 0: 12 | dice_image.config(image=dice_resized_images[frames_left % 6]) 13 | root.after(200, roll_dice_animation, frames_left - 1) 14 | else: 15 | roll_dice() 16 | 17 | root = tk.Tk() 18 | root.title("Dice Rolling Simulator") 19 | 20 | frame = tk.Frame(root) 21 | frame.pack() 22 | dice_images = [Image.open(f"./assets/dice-six-faces-{i}.png") for i in range(1, 7)] 23 | desired_width = 100 24 | resized_images = [img.resize((desired_width, int(img.height * (desired_width / img.width))), Image.LANCZOS) for img in dice_images] 25 | dice_resized_images = [ImageTk.PhotoImage(img) for img in resized_images] 26 | 27 | roll_button = tk.Button(frame, text="Roll Dice",width=20, command=roll_dice_animation) 28 | roll_button.grid(row=0, column=0, pady=30, padx=30) 29 | result = tk.IntVar() 30 | dice_image = tk.Label(frame, image=dice_resized_images[0]) 31 | dice_image.grid(row=1) 32 | output = tk.Label(frame, textvariable=result, font=("Arial", 20, "bold"), pady=10) 33 | output.grid(row=2, column=0) 34 | root.mainloop() -------------------------------------------------------------------------------- /DigitalRecognition/main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2023/10/7 22:43 3 | # @Author : 之落花--falling_flowers 4 | # @File : main.py 5 | # @Software: PyCharm 6 | import io 7 | import tkinter as tk 8 | import numpy as np 9 | import torch 10 | from PIL import Image 11 | from torch import nn 12 | from torch.nn import functional as f 13 | from torchvision import transforms 14 | 15 | 16 | class App: 17 | def __init__(self): 18 | self.net = Net() 19 | self.net.load_state_dict(torch.load('net.pth')) 20 | self.resize = transforms.Resize([28, 28], antialias=True) 21 | self.line_id = None 22 | self.line_points = [] 23 | self.root = tk.Tk() 24 | self.root.title('Handwritten digit recognizer') 25 | self.root.resizable(width=False, height=False) 26 | self.canvas = tk.Canvas(height=368, width=368, relief='groove', bd=2) 27 | self.canvas.pack() 28 | self.text = tk.StringVar(self.root, 'number:') 29 | tk.Label(self.root, textvariable=self.text, font=('microsoft yahei', 15)).pack(side='left') 30 | tk.Button(self.root, text='clear', font=('microsoft yahei', 15), 31 | command=lambda: self.canvas.delete(tk.ALL)).pack(side='right') 32 | self.canvas.bind('', self.set_start) 33 | self.canvas.bind('', self.draw_line) 34 | self.canvas.bind('', self.end_line) 35 | self.root.mainloop() 36 | 37 | def draw_line(self, event): 38 | self.line_points.extend((event.x, event.y)) 39 | if self.line_id is not None: 40 | self.canvas.delete(self.line_id) 41 | self.line_id = self.canvas.create_line(self.line_points, width=30) 42 | 43 | def set_start(self, event): 44 | self.line_points.extend((event.x, event.y)) 45 | 46 | def end_line(self, _): 47 | self.line_points.clear() 48 | self.line_id = None 49 | img = np.array(Image.open(io.BytesIO(self.canvas.postscript(colormode='mono').encode('utf-8'))))[:, :, 0] 50 | a = self.net(self.resize(torch.tensor(img / -255 + 1)[None]).float()) 51 | self.text.set(f'number:{int(torch.argmax(a))}') 52 | 53 | 54 | class Net(nn.Module): 55 | def __init__(self): 56 | super(Net, self).__init__() 57 | self.conv1 = nn.Conv2d(1, 6, 3) 58 | self.conv2 = nn.Conv2d(6, 16, 4) 59 | self.fc1 = nn.Linear(16 * 5 * 5, 120) 60 | self.fc2 = nn.Linear(120, 84) 61 | self.fc3 = nn.Linear(84, 10) 62 | 63 | def forward(self, x): 64 | x = f.max_pool2d(f.relu(self.conv1(x)), 2) 65 | x = f.max_pool2d(f.relu(self.conv2(x)), 2) 66 | x = torch.flatten(x, 0) 67 | x = f.relu(self.fc1(x)) 68 | x = f.relu(self.fc2(x)) 69 | x = self.fc3(x) 70 | return x 71 | 72 | 73 | def main(): 74 | App() 75 | 76 | 77 | if __name__ == '__main__': 78 | main() 79 | -------------------------------------------------------------------------------- /DigitalRecognition/net.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/DigitalRecognition/net.pth -------------------------------------------------------------------------------- /Face Registration Recognition/face_reg_rec.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "vscode": { 8 | "languageId": "plaintext" 9 | } 10 | }, 11 | "outputs": [], 12 | "source": [ 13 | "pip install face_recognition opencv-python pandas numpy" 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "import cv2\n", 23 | "import face_recognition as fr\n", 24 | "import pandas as pd\n", 25 | "\n", 26 | "fd = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n", 27 | "\n", 28 | "# Reading data from csv file\n", 29 | "try:\n", 30 | " face_db = pd.read_csv(\"./face_database.csv\", index_col=0)\n", 31 | " final_data = {\"NAMES\": face_db[\"NAMES\"].values.tolist(), \"ENC\": face_db[\"ENC\"].values.tolist()}\n", 32 | "except Exception as e:\n", 33 | " print(e)\n", 34 | " print(\"Creating new database\")\n", 35 | " final_data = {\"NAMES\": [], \"ENC\": []}\n", 36 | "\n", 37 | "\n", 38 | "# Video read using web cam\n", 39 | "vid = cv2.VideoCapture(0)\n", 40 | "counter = 0\n", 41 | "captured = True\n", 42 | "cropped_face = None\n", 43 | "\n", 44 | "# main loop to read and show image until we break the loop\n", 45 | "while captured :\n", 46 | " flag, img = vid.read()\n", 47 | " cropped_face = img\n", 48 | "\n", 49 | " # if flag is true then only show image\n", 50 | " if flag:\n", 51 | " faces = fd.detectMultiScale(img, 1.3, 5)\n", 52 | " for x,y,w,h in faces:\n", 53 | " cropped_face = img[y:y+h, x:x+w].copy()\n", 54 | " \n", 55 | " # It will check if face is present in front of cam for 20 frames\n", 56 | " if len(faces) == 1:\n", 57 | " counter += 1\n", 58 | " if counter == 20:\n", 59 | " # It will ask for name and save the face encodings in csv file\n", 60 | " final_data[\"NAMES\"].append(input(\"Enter your name: \"))\n", 61 | " face_enc = fr.face_encodings(cropped_face)\n", 62 | " final_data[\"ENC\"].append(face_enc[0].tolist())\n", 63 | " db = pd.DataFrame(final_data)\n", 64 | " db.to_csv(\"./face_database.csv\")\n", 65 | " captured = False\n", 66 | " else:\n", 67 | " counter = 0\n", 68 | " \n", 69 | " cv2.imshow(\"webcam_image\",cropped_face)\n", 70 | " key = cv2.waitKey(1)\n", 71 | " if key == ord(\"q\"):\n", 72 | " break\n", 73 | " else:\n", 74 | " break\n", 75 | "vid.release()\n", 76 | "cv2.destroyAllWindows()" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "import cv2\n", 86 | "import numpy as np\n", 87 | "import face_recognition as fr\n", 88 | "import pandas as pd\n", 89 | "\n", 90 | "fd = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n", 91 | "\n", 92 | "# Reading data from csv file\n", 93 | "try:\n", 94 | " face_db = pd.read_csv(\"./face_database.csv\", index_col=0)\n", 95 | " final_data = {\"NAMES\": face_db[\"NAMES\"].values.tolist(), \"ENC\": face_db[\"ENC\"].values.tolist()}\n", 96 | "except Exception as e:\n", 97 | " print(e)\n", 98 | " final_data = {\"NAMES\": [], \"ENC\": []}\n", 99 | "\n", 100 | "# Video read using web cam\n", 101 | "vid = cv2.VideoCapture(0)\n", 102 | "captured = True\n", 103 | "cropped_face = None\n", 104 | "\n", 105 | "# main loop to read and show image until we break the loop\n", 106 | "while captured :\n", 107 | " flag, img = vid.read()\n", 108 | " cropped_face = img\n", 109 | "\n", 110 | " # if flag is true then only show image\n", 111 | " if flag:\n", 112 | " faces = fd.detectMultiScale(img, 1.3, 5)\n", 113 | " for x,y,w,h in faces:\n", 114 | " cropped_face = img[y:y+h, x:x+w].copy()\n", 115 | " \n", 116 | " # It will check if face is present in front of cam for 20 frames\n", 117 | " if len(faces) == 1:\n", 118 | " try:\n", 119 | " face_enc = fr.face_encodings(cropped_face)\n", 120 | " for fe in final_data[\"ENC\"]:\n", 121 | " if fr.compare_faces(np.array(eval(fe)), face_enc)[0]:\n", 122 | " cv2.putText(img, final_data[\"NAMES\"][final_data[\"ENC\"].index(fe)], (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0,255,0), 2)\n", 123 | " cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)\n", 124 | " else:\n", 125 | " cv2.putText(img, \"Unknown\", (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0,0,255), 2)\n", 126 | " cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)\n", 127 | " except Exception as e:\n", 128 | " print(e)\n", 129 | " else:\n", 130 | " print(\"Multiple faces detected\")\n", 131 | "\n", 132 | " cv2.imshow(\"webcam_image\", img)\n", 133 | " key = cv2.waitKey(1)\n", 134 | " if key == ord(\"q\"):\n", 135 | " break\n", 136 | " else:\n", 137 | " break\n", 138 | "vid.release()\n", 139 | "cv2.destroyAllWindows()" 140 | ] 141 | } 142 | ], 143 | "metadata": { 144 | "language_info": { 145 | "name": "python" 146 | } 147 | }, 148 | "nbformat": 4, 149 | "nbformat_minor": 2 150 | } 151 | -------------------------------------------------------------------------------- /Google_Logo/google_logo.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | # Get the instance of turtle 4 | t = turtle.Turtle() 5 | 6 | # Select color 7 | t.color('#4285F4', '#4285F4') # RGB value of color 8 | 9 | # Change the pen size 10 | t.pensize(5) 11 | 12 | # Change the drawing speed 13 | t.speed(3) 14 | 15 | # Function to draw the Google logo 16 | def draw_google_logo(): 17 | t.forward(120) 18 | t.right(90) 19 | t.circle(-150, 50) ## First circle for red color 20 | t.color('#0F9D58') 21 | t.circle(-150, 100) 22 | t.color('#F4B400') 23 | t.circle(-150, 60) 24 | t.color('#DB4437', '#DB4437') 25 | 26 | t.begin_fill() 27 | t.circle(-150, 100) 28 | t.right(90) 29 | t.forward(50) 30 | t.right(90) 31 | t.circle(100, 100) 32 | t.right(90) 33 | t.forward(50) 34 | t.end_fill() 35 | 36 | t.begin_fill() 37 | 38 | ## Second circle for yellow color 39 | 40 | t.color("#F4B400", "#F4B400") 41 | t.right(180) 42 | t.forward(50) 43 | t.right(90) 44 | 45 | t.circle(100, 60) 46 | t.right(90) 47 | t.forward(50) 48 | t.right(90) 49 | t.circle(-150, 60) 50 | t.end_fill() 51 | 52 | # Third circle of green color 53 | t.right(90) 54 | t.forward(50) 55 | t.right(90) 56 | t.circle(100, 60) 57 | t.color('#0F9D58', '#0F9D58') 58 | t.begin_fill() 59 | t.circle(100, 100) 60 | t.right(90) 61 | t.forward(50) 62 | t.right(90) 63 | t.circle(-150, 100) 64 | t.right(90) 65 | t.forward(50) 66 | t.end_fill() 67 | 68 | ## Draw last circle 69 | 70 | t.right(90) 71 | t.circle(100, 100) 72 | t.color('#4285F4', '#4285F4') 73 | t.begin_fill() 74 | t.circle(100, 25) 75 | t.left(115) 76 | t.forward(65) 77 | t.right(90) 78 | t.forward(42) 79 | t.right(90) 80 | t.forward(124) 81 | t.right(90) 82 | t.circle(-150, 50) 83 | t.right(90) 84 | t.forward(50) 85 | t.end_fill() 86 | 87 | 88 | # Function to write "Google" text below the logo 89 | def write_google_text(): 90 | t.penup() 91 | t.goto(-20, -220) # Adjust the position as needed 92 | t.color('black') # Text color 93 | t.write("Google", align="center", font=("Arial", 40, "bold")) 94 | 95 | 96 | # Draw the Google logo 97 | draw_google_logo() 98 | 99 | # Write "Google" text below the logo 100 | write_google_text() 101 | 102 | # Keep the window open 103 | turtle.done() 104 | -------------------------------------------------------------------------------- /Google_Logo/microsoft_logo.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | pen = turtle.Turtle() 4 | screen = turtle.Screen() 5 | 6 | pen.hideturtle() 7 | pen.penup() 8 | pen.goto(-154, 4) 9 | pen.pendown() 10 | pen.showturtle 11 | 12 | #orange box 13 | pen.color("#f25022") 14 | pen.begin_fill() 15 | pen.goto(-204, 4) 16 | pen.goto(-204, 50) 17 | pen.goto(-154, 50) 18 | pen.goto(-154, 4) 19 | pen.end_fill() 20 | 21 | #green box 22 | pen.color("#7fba00") 23 | pen.penup() 24 | pen.goto(-150, 4) 25 | pen.pendown() 26 | pen.begin_fill() 27 | pen.goto(-150, 50) 28 | pen.goto(-100, 50) 29 | pen.goto(-100, 4) 30 | pen.goto(-150, 4) 31 | pen.end_fill() 32 | 33 | #yellow box 34 | pen.color("#ffb900") 35 | pen.penup() 36 | pen.goto(-150, 0) 37 | pen.pendown() 38 | pen.begin_fill() 39 | pen.goto(-100, 0) 40 | pen.goto(-100, -50) 41 | pen.goto(-150, -50) 42 | pen.goto(-150, 0) 43 | pen.end_fill() 44 | 45 | #blue box 46 | pen.color("#00a4ef") 47 | pen.penup() 48 | pen.goto(-154, 0) 49 | pen.pendown() 50 | pen.begin_fill() 51 | pen.goto(-204, 0) 52 | pen.goto(-204, -50) 53 | pen.goto(-154, -50) 54 | pen.goto(-154, 0) 55 | pen.end_fill() 56 | 57 | pen.hideturtle() 58 | -------------------------------------------------------------------------------- /Guess_The_Number/guess_the_number.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import messagebox 3 | import random 4 | 5 | class NumberGuessingGame: 6 | def __init__(self, root): 7 | self.root = root 8 | self.root.title("Number Guessing Game") 9 | 10 | self.secret_number = random.randint(1, 100) 11 | self.attempts = 0 12 | 13 | self.root.geometry("300x200") # Set window dimensions 14 | 15 | self.label = tk.Label(root, text="Guess a number between 1 and 100:") 16 | self.label.pack(pady=10) 17 | 18 | self.entry = tk.Entry(root) 19 | self.entry.pack(pady=5) 20 | self.entry.bind("", self.check_guess_enter) # Bind Enter key to check_guess_enter method 21 | 22 | self.button = tk.Button(root, text="Submit Guess", command=self.check_guess) 23 | self.button.pack() 24 | 25 | def check_guess(self): 26 | self.attempt_logic() 27 | 28 | def check_guess_enter(self, event): 29 | self.attempt_logic() 30 | 31 | def attempt_logic(self): 32 | try: 33 | guess = int(self.entry.get()) 34 | self.attempts += 1 35 | 36 | if guess < self.secret_number: 37 | message = "Too low! Try again." 38 | elif guess > self.secret_number: 39 | message = "Too high! Try again." 40 | else: 41 | message = f"Congratulations! You guessed the number {self.secret_number} in {self.attempts} attempts." 42 | self.button.config(state=tk.DISABLED) # Disable the button after guessing correctly 43 | 44 | messagebox.showinfo("Result", message) 45 | except ValueError: 46 | messagebox.showerror("Error", "Please enter a valid number.") 47 | finally: 48 | self.entry.delete(0, tk.END) # Clear the entry field 49 | 50 | if __name__ == "__main__": 51 | root = tk.Tk() 52 | game = NumberGuessingGame(root) 53 | root.mainloop() -------------------------------------------------------------------------------- /Hand Recognition/hand-detection.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "pip install opencv-python cvzone" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 17, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import cv2\n", 19 | "from cvzone.HandTrackingModule import HandDetector\n", 20 | "\n", 21 | "# Initialize HandDetector from cvzone\n", 22 | "detector = HandDetector(detectionCon=0.8, maxHands=2)\n", 23 | "\n", 24 | "# Open the webcam\n", 25 | "cap = cv2.VideoCapture(0)\n", 26 | "\n", 27 | "while cap.isOpened():\n", 28 | " ret, frame = cap.read()\n", 29 | " \n", 30 | " # Flip the frame horizontally for a later selfie-view display\n", 31 | " frame = cv2.flip(frame, 1)\n", 32 | " \n", 33 | " # Detect hands using cvzone HandDetector\n", 34 | " hands, frame = detector.findHands(frame, draw=True, flipType=False)\n", 35 | "\n", 36 | " # Show the frame\n", 37 | " cv2.imshow('Hand Recognition', frame)\n", 38 | " \n", 39 | " # Break the loop when 'q' key is pressed\n", 40 | " if cv2.waitKey(1) & 0xFF == ord('q'):\n", 41 | " break\n", 42 | "\n", 43 | "# Release the webcam and close all windows\n", 44 | "cap.release()\n", 45 | "cv2.destroyAllWindows()\n" 46 | ] 47 | } 48 | ], 49 | "metadata": { 50 | "kernelspec": { 51 | "display_name": "Python 3", 52 | "language": "python", 53 | "name": "python3" 54 | }, 55 | "language_info": { 56 | "codemirror_mode": { 57 | "name": "ipython", 58 | "version": 3 59 | }, 60 | "file_extension": ".py", 61 | "mimetype": "text/x-python", 62 | "name": "python", 63 | "nbconvert_exporter": "python", 64 | "pygments_lexer": "ipython3", 65 | "version": "3.10.11" 66 | } 67 | }, 68 | "nbformat": 4, 69 | "nbformat_minor": 2 70 | } 71 | -------------------------------------------------------------------------------- /ImageToTextConverter/ImageToText.py: -------------------------------------------------------------------------------- 1 | !pip install pytesseract 2 | !sudo apt-get install tesseract-ocr 3 | !pip install opencv-python-headless 4 | from PIL import Image 5 | import pytesseract 6 | import cv2 7 | from google.colab import files 8 | 9 | def extract_text_from_image(image_path): 10 | # Load the image from the provided path 11 | image = cv2.imread(image_path) 12 | 13 | # Convert the image to grayscale 14 | gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 15 | 16 | # Apply thresholding to enhance text 17 | _, thresh = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) 18 | 19 | # Perform OCR on the preprocessed image 20 | text = pytesseract.image_to_string(thresh) 21 | 22 | return text 23 | 24 | # Function to upload an image file in Google Colab 25 | def upload_image(): 26 | uploaded = files.upload() 27 | for filename in uploaded.keys(): 28 | return filename 29 | 30 | # Ask the user whether to upload a file or provide a path 31 | choice = input("Do you want to upload a file? (yes/no): ").strip().lower() 32 | if choice == "yes": 33 | # Upload the image file 34 | image_filename = upload_image() 35 | if image_filename: 36 | # Extract text from the uploaded image 37 | extracted_text = extract_text_from_image(image_filename) 38 | print("Scanned Text:") 39 | print(extracted_text) 40 | else: 41 | # Provide the path to the image you want to scan 42 | image_path = "123.png" 43 | # Extract text from the image 44 | extracted_text = extract_text_from_image(image_path) 45 | print("Scanned Text:") 46 | print(extracted_text) 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Swapnil Singh 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LIve Weather Using Python/LiveWeather.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from plyer import notification 3 | 4 | # Replace 'YOUR_API_KEY' with your OpenWeatherMap API key 5 | api_key = '6f42afa4f1275a6802a554ad79114ccd' 6 | 7 | 8 | # Define the city and country code for the location you want to track 9 | city = 'New York' 10 | country_code = 'US' 11 | 12 | # Define the URL for the OpenWeatherMap API 13 | url = f'http://api.openweathermap.org/data/2.5/weather?q={city},{country_code}&appid={api_key}' 14 | 15 | # Function to get weather data and send a notification 16 | def get_weather_and_notify(): 17 | try: 18 | response = requests.get(url) 19 | data = response.json() 20 | 21 | if data['cod'] != 200: 22 | raise Exception(data['message']) 23 | 24 | weather_description = data['weather'][0]['description'] 25 | temperature = data['main']['temp'] 26 | 27 | notification_title = f'Weather in {city}' 28 | notification_message = f'{weather_description.capitalize()}. Temperature: {temperature}°C' 29 | 30 | notification.notify( 31 | title=notification_title, 32 | message=notification_message, 33 | app_name='Weather App', 34 | timeout=10 # Notification timeout in seconds 35 | ) 36 | 37 | except Exception as e: 38 | print(f"An error occurred: {e}") 39 | 40 | if __name__ == '__main__': 41 | get_weather_and_notify() 42 | -------------------------------------------------------------------------------- /Library Management System/library.py: -------------------------------------------------------------------------------- 1 | class Library: 2 | def __init__(self): 3 | self.books = [] 4 | self.borrowed_books = {} 5 | 6 | def add_book(self, book_title, author, pages, year, publisher, genre, language, copies): 7 | if book_title == "" or author == "" or pages == "" or year == "" or publisher == "" or genre == "" or language == "" or copies <= 0: 8 | print("Please fill out all the fields.") 9 | elif book_title not in self.books: 10 | book = { 11 | "title": book_title, 12 | "author": author, 13 | "pages": pages, 14 | "year": year, 15 | "publisher": publisher, 16 | "genre": genre, 17 | "language": language, 18 | "copies": copies 19 | } 20 | self.books.append(book) 21 | print(f'Book "{book_title}" by {author} added successfully.') 22 | else: 23 | print(f'Book "{book_title}" already exists in the library.') 24 | 25 | def display_books(self): 26 | if self.books == []: 27 | print("No books in the library.") 28 | else: 29 | print("Available Books:") 30 | for book in self.books: 31 | print(f'"{book["title"]}" by {book["author"]}') 32 | 33 | def book_info(self, book_title): 34 | book = None 35 | for b in self.books: 36 | if book_title == b["title"]: 37 | book = b 38 | if book: 39 | print(f'"{book["title"]}" by {book["author"]}') 40 | print(f'Pages: {book["pages"]}') 41 | print(f'Year: {book["year"]}') 42 | print(f'Publisher: {book["publisher"]}') 43 | print(f'Genre: {book["genre"]}') 44 | print(f'Language: {book["language"]}') 45 | print(f'Copies: {book["copies"]}') 46 | else: 47 | print(f'Book "{book_title}" does not exist in the library.') 48 | 49 | def borrow_book(self, book_title, student): 50 | if student.books == {} or book_title not in [book["title"] for book in student.books]: 51 | book = None 52 | for b in self.books: 53 | if book_title == b["title"]: 54 | book = b 55 | if book: 56 | book["copies"] -= 1 57 | if book_title not in self.borrowed_books: 58 | self.borrowed_books[book_title] = [student.name] 59 | else: 60 | self.borrowed_books[book_title].append(student.name) 61 | student.borrow_book(book_title, b["title"]) 62 | print(f'You have borrowed "{book_title}". Enjoy reading!') 63 | else: 64 | print(f'Sorry, "{book_title}" is not available in the library.') 65 | else: 66 | print(f'You have already borrowed "{book_title}".') 67 | 68 | 69 | 70 | def return_book(self, book_title, student): 71 | if book_title not in [book["title"] for book in student.books]: 72 | print(f'You have not borrowed "{book_title}".') 73 | else: 74 | book = None 75 | for b in self.books: 76 | if book_title == b["title"]: 77 | book = b 78 | if book: 79 | book["copies"] += 1 80 | self.borrowed_books[book_title].remove(student.name) 81 | student.return_book(book_title) 82 | print(f'Thank you for returning "{book_title}".') 83 | 84 | def borrowed_books_func(self): 85 | if self.borrowed_books == {}: 86 | print("No books borrowed.") 87 | else: 88 | print("Borrowed Books:") 89 | for book_title in self.borrowed_books: 90 | print(f'->"{book_title}" Borrowed by') 91 | for student in self.borrowed_books[book_title]: 92 | print(f' {student}') 93 | 94 | class Student: 95 | def __init__(self, name): 96 | self.name = name 97 | self.books = [] 98 | print(f"Welcome to the library, {self.name}!") 99 | 100 | def borrow_book(self, book_title, author): 101 | book = { 102 | "title": book_title, 103 | "author": author 104 | } 105 | self.books.append(book) 106 | 107 | def return_book(self, book_title): 108 | for book in self.books: 109 | if book_title == book["title"]: 110 | self.books.remove(book) 111 | 112 | def borrowed_books(self): 113 | if self.books == []: 114 | print("No books borrowed.") 115 | else: 116 | print("Borrowed Books:") 117 | for book in self.books: 118 | print(f'"{book["title"]}" by {book["author"]}') 119 | 120 | def main(): 121 | library = Library() 122 | student = Student(input("Enter your name: ")) 123 | 124 | while True: 125 | print("\nLibrary Management System Menu:") 126 | print("1. Add Book (Librarian Only)") 127 | print("2. Display Available Books") 128 | print("3. Display Book's Information") 129 | print("4. Borrow Book") 130 | print("5. Return Book") 131 | print("6. See Student's Borrowed Books") 132 | print("7. See Total Borrowed Books (Librarian Only)") 133 | print("8. Exit") 134 | 135 | choice = input("Enter your choice: ") 136 | 137 | if choice == "1": 138 | title = input("Enter book title: ").lower() 139 | author = input("Enter author name: ") 140 | pages = int(input("Enter number of pages: ")) 141 | year = int(input("Enter year published: ")) 142 | publisher = input("Enter publisher: ") 143 | genre = input("Enter genre: ") 144 | language = input("Enter language: ") 145 | copies = int(input("Enter number of copies: ")) 146 | library.add_book(title, author, pages, year, publisher, genre, language, copies) 147 | elif choice == "2": 148 | library.display_books() 149 | elif choice == "3": 150 | title = input("Enter book title: ").lower() 151 | library.book_info(title) 152 | elif choice == "4": 153 | title = input("Enter the title of the book you want to borrow: ").lower() 154 | library.borrow_book(title, student) 155 | elif choice == "5": 156 | title = input("Enter the title of the book you are returning: ").lower() 157 | library.return_book(title, student) 158 | elif choice == "6": 159 | student.borrowed_books() 160 | elif choice == "7": 161 | library.borrowed_books_func() 162 | elif choice == "8": 163 | print("Exiting the Library Management System. Goodbye!") 164 | break 165 | else: 166 | print("Invalid choice. Please try again.") 167 | 168 | if __name__ == "__main__": 169 | main() -------------------------------------------------------------------------------- /Meme Generator/input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Meme Generator/input.png -------------------------------------------------------------------------------- /Meme Generator/meme.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "pip install pillow" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 1, 15 | "metadata": {}, 16 | "outputs": [ 17 | { 18 | "name": "stdout", 19 | "output_type": "stream", 20 | "text": [ 21 | "Meme generated and saved as output.png\n" 22 | ] 23 | } 24 | ], 25 | "source": [ 26 | "from PIL import Image, ImageDraw, ImageFont\n", 27 | "\n", 28 | "def text_width(font, text):\n", 29 | " mask = font.getmask(text)\n", 30 | " return mask.getbbox()[2] - mask.getbbox()[0]\n", 31 | "\n", 32 | "def generate_meme(input_image_path, output_image_path, top_text, bottom_text, max_text_length=20, font_path='arial.ttf', min_font_size=10, max_font_size=100):\n", 33 | " try:\n", 34 | " # Open the input image\n", 35 | " img = Image.open(input_image_path)\n", 36 | " draw = ImageDraw.Draw(img)\n", 37 | " \n", 38 | " # Get image width and height\n", 39 | " width, height = img.size\n", 40 | " \n", 41 | " # Load font\n", 42 | " try:\n", 43 | " font_size = max_font_size\n", 44 | " font = ImageFont.truetype(font_path, font_size)\n", 45 | " except IOError:\n", 46 | " font = ImageFont.load_default()\n", 47 | "\n", 48 | " # Calculate top text size and position\n", 49 | " top_text_length = min(len(top_text), max_text_length)\n", 50 | " while text_width(font, top_text[:top_text_length]) > width:\n", 51 | " font_size -= 1\n", 52 | " font = ImageFont.truetype(font_path, font_size)\n", 53 | " x = (width - text_width(font, top_text[:top_text_length])) // 2\n", 54 | " y = 10\n", 55 | " \n", 56 | " # Add top text to the image\n", 57 | " draw.text((x, y), top_text[:top_text_length], font=font, fill='white')\n", 58 | " \n", 59 | " # Calculate bottom text size and position\n", 60 | " bottom_text_length = min(len(bottom_text), max_text_length)\n", 61 | " while text_width(font, bottom_text[:bottom_text_length]) > width:\n", 62 | " font_size -= 1\n", 63 | " font = ImageFont.truetype(font_path, font_size)\n", 64 | " x = (width - text_width(font, bottom_text[:bottom_text_length])) // 2\n", 65 | " text_bbox = draw.textbbox((x, y), bottom_text[:bottom_text_length], font=font)\n", 66 | " y = height - text_bbox[1] - 10\n", 67 | " \n", 68 | " # Add bottom text to the image\n", 69 | " draw.text((x, y), bottom_text[:bottom_text_length], font=font, fill='white')\n", 70 | " \n", 71 | " # Save the final meme\n", 72 | " img.save(output_image_path)\n", 73 | " print(f\"Meme generated and saved as {output_image_path}\")\n", 74 | " except Exception as e:\n", 75 | " print(f\"Error: {e}\")\n", 76 | "\n", 77 | "# Example usage\n", 78 | "input_image_path = 'input.png'\n", 79 | "output_image_path = 'output.png'\n", 80 | "top_text = 'My PC'\n", 81 | "bottom_text = 'After Starting Android Studio'\n", 82 | "generate_meme(input_image_path, output_image_path, top_text, bottom_text, max_font_size=70, max_text_length=50)\n" 83 | ] 84 | } 85 | ], 86 | "metadata": { 87 | "kernelspec": { 88 | "display_name": "Python 3", 89 | "language": "python", 90 | "name": "python3" 91 | }, 92 | "language_info": { 93 | "codemirror_mode": { 94 | "name": "ipython", 95 | "version": 3 96 | }, 97 | "file_extension": ".py", 98 | "mimetype": "text/x-python", 99 | "name": "python", 100 | "nbconvert_exporter": "python", 101 | "pygments_lexer": "ipython3", 102 | "version": "3.10.11" 103 | } 104 | }, 105 | "nbformat": 4, 106 | "nbformat_minor": 2 107 | } 108 | -------------------------------------------------------------------------------- /Meme Generator/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Meme Generator/output.png -------------------------------------------------------------------------------- /Merging or Spliting PDFs/merge-split-pdfs.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "pip install PyPDF2" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import PyPDF2\n", 19 | "\n", 20 | "def merge_pdfs(input_pdfs, output_pdf):\n", 21 | " merger = PyPDF2.PdfFileMerger()\n", 22 | "\n", 23 | " for pdf in input_pdfs:\n", 24 | " merger.append(pdf)\n", 25 | "\n", 26 | " merger.write(output_pdf)\n", 27 | " merger.close()\n", 28 | "\n", 29 | "def split_pdf(input_pdf):\n", 30 | " pdf_reader = PyPDF2.PdfFileReader(input_pdf)\n", 31 | "\n", 32 | " for page_num in range(pdf_reader.numPages):\n", 33 | " pdf_writer = PyPDF2.PdfFileWriter()\n", 34 | " pdf_writer.addPage(pdf_reader.getPage(page_num))\n", 35 | "\n", 36 | " output_pdf = f\"page_{page_num + 1}.pdf\"\n", 37 | " with open(output_pdf, \"wb\") as output_file:\n", 38 | " pdf_writer.write(output_file)\n", 39 | " print(f\"Page {page_num + 1} extracted and saved as {output_pdf}\")\n", 40 | "\n", 41 | "choice = int(input(\"What do you want to do?\\n1. Merge PDFs\\n2. Split PDF\\nEnter your choice (1 or 2): \"))\n", 42 | "\n", 43 | "if choice == 1:\n", 44 | " # Example usage for merging two PDF files\n", 45 | " input_pdfs = input(\"Enter the PDFs you want to merge separated by space: \").split()\n", 46 | " output_pdf = input(\"Enter the name of the merged PDF: \")\n", 47 | " merge_pdfs(input_pdfs, output_pdf)\n", 48 | " print(\"PDF files merged successfully.\")\n", 49 | "elif choice == 2:\n", 50 | " # Example usage for splitting a PDF file\n", 51 | " input_pdf = input(\"Enter the PDF you want to split: \")\n", 52 | " split_pdf(input_pdf)\n", 53 | "else:\n", 54 | " print(\"Invalid choice! Please try again.\")" 55 | ] 56 | } 57 | ], 58 | "metadata": { 59 | "kernelspec": { 60 | "display_name": "Python 3", 61 | "language": "python", 62 | "name": "python3" 63 | }, 64 | "language_info": { 65 | "codemirror_mode": { 66 | "name": "ipython", 67 | "version": 3 68 | }, 69 | "file_extension": ".py", 70 | "mimetype": "text/x-python", 71 | "name": "python", 72 | "nbconvert_exporter": "python", 73 | "pygments_lexer": "ipython3", 74 | "version": "3.10.11" 75 | } 76 | }, 77 | "nbformat": 4, 78 | "nbformat_minor": 2 79 | } 80 | -------------------------------------------------------------------------------- /Motivational Quotes Twitter Bot/main.py: -------------------------------------------------------------------------------- 1 | # Automate this scipt on Pythonanywhere for free to tweet automatically 2 | 3 | import tweepy 4 | import requests 5 | 6 | # Get these credentials for free from twitter developer's account 7 | api_key = "Your API KEY" 8 | api_secret = "Your API Secret" 9 | bearer_token = r"Your Bearer Token" 10 | access_token = "Your Access Token" 11 | access_token_secret = "Your Access Token Secret" 12 | 13 | client = tweepy.Client(bearer_token,api_key,api_secret,access_token,access_token_secret) 14 | auth = tweepy.OAuth1UserHandler(api_key,api_secret,access_token,access_token_secret) 15 | api = tweepy.API(auth) 16 | 17 | 18 | 19 | # Function to get a random quote from They Said So API 20 | def get_random_quote(): 21 | url = f'https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json&category=inspire' 22 | response = requests.get(url) 23 | data = response.json() 24 | return data["quoteText"] 25 | 26 | 27 | # This is to Tweet the quote 28 | client.create_tweet(text=f"{get_random_quote()} \n#Xmoon #Quotes #Happiness") -------------------------------------------------------------------------------- /Motivational Quotes Twitter Bot/readme: -------------------------------------------------------------------------------- 1 | Hey Everyone, 2 | 3 | This is a python script to make a Motivation Quotes Twitter Bot 4 | 5 | Steps: 6 | 7 | 1. Get yourself a free twitter api from developer's account 8 | 2. Put your credentials in field mentioned in the script. 9 | 3. Host this script on cloud for free with Pythonanywhere 10 | 4. Hurray, You are now automated 11 | 5. Made with Love by @Aryainguz -------------------------------------------------------------------------------- /Motivational Quotes Twitter Bot/requirements.txt: -------------------------------------------------------------------------------- 1 | tweepy==4.14.0 2 | python==3.9.13 3 | requests==2.28.1 -------------------------------------------------------------------------------- /Number system calculator/calculator.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import tkinter as tk\n", 10 | "from tkinter import ttk\n", 11 | "\n", 12 | "def convert_number():\n", 13 | " base = int(base_entry.get())\n", 14 | " input_number = input_entry.get()\n", 15 | "\n", 16 | " try:\n", 17 | " decimal_number = int(input_number, base)\n", 18 | " binary = bin(decimal_number)[2:]\n", 19 | " octal = oct(decimal_number)[2:]\n", 20 | " hexadecimal = hex(decimal_number)[2:]\n", 21 | "\n", 22 | " decimal_result.set(f\"Decimal: {decimal_number}\")\n", 23 | " binary_result.set(f\"Binary: {binary}\")\n", 24 | " octal_result.set(f\"Octal: {octal}\")\n", 25 | " hexadecimal_result.set(f\"Hexadecimal: {hexadecimal}\")\n", 26 | " except ValueError:\n", 27 | " decimal_result.set(\"Invalid input\")\n", 28 | " binary_result.set(\"Invalid input\")\n", 29 | " octal_result.set(\"Invalid input\")\n", 30 | " hexadecimal_result.set(\"Invalid input\")\n", 31 | "\n", 32 | "# Create a tkinter window\n", 33 | "root = tk.Tk()\n", 34 | "root.title(\"Number System Converter\")\n", 35 | "root.geometry(\"400x400\") # Set window size\n", 36 | "\n", 37 | "# Style configuration\n", 38 | "style = ttk.Style()\n", 39 | "style.configure(\"TLabel\", background=\"#3498db\", foreground=\"white\", font=(\"Arial\", 12))\n", 40 | "style.configure(\"TButton\", background=\"#2ecc71\", foreground=\"black\", font=(\"Arial\", 12))\n", 41 | "style.configure(\"TEntry\", font=(\"Arial\", 12))\n", 42 | "\n", 43 | "# Base input\n", 44 | "base_label = ttk.Label(root, text=\"Enter Base:\")\n", 45 | "base_label.pack(pady=10)\n", 46 | "base_entry = ttk.Entry(root, font=(\"Arial\", 12))\n", 47 | "base_entry.pack(pady=10)\n", 48 | "\n", 49 | "# Number input\n", 50 | "input_label = ttk.Label(root, text=\"Enter Number:\")\n", 51 | "input_label.pack()\n", 52 | "input_entry = ttk.Entry(root, font=(\"Arial\", 12))\n", 53 | "input_entry.pack(pady=10)\n", 54 | "\n", 55 | "# Convert button\n", 56 | "convert_button = ttk.Button(root, text=\"Convert\", command=convert_number)\n", 57 | "convert_button.pack(pady=20)\n", 58 | "\n", 59 | "# Result labels\n", 60 | "decimal_result = tk.StringVar()\n", 61 | "decimal_label = ttk.Label(root, textvariable=decimal_result)\n", 62 | "decimal_label.pack()\n", 63 | "\n", 64 | "binary_result = tk.StringVar()\n", 65 | "binary_label = ttk.Label(root, textvariable=binary_result)\n", 66 | "binary_label.pack()\n", 67 | "\n", 68 | "octal_result = tk.StringVar()\n", 69 | "octal_label = ttk.Label(root, textvariable=octal_result)\n", 70 | "octal_label.pack()\n", 71 | "\n", 72 | "hexadecimal_result = tk.StringVar()\n", 73 | "hexadecimal_label = ttk.Label(root, textvariable=hexadecimal_result)\n", 74 | "hexadecimal_label.pack()\n", 75 | "\n", 76 | "# Run the tkinter main loop\n", 77 | "root.mainloop()" 78 | ] 79 | } 80 | ], 81 | "metadata": { 82 | "kernelspec": { 83 | "display_name": "Python 3", 84 | "language": "python", 85 | "name": "python3" 86 | }, 87 | "language_info": { 88 | "codemirror_mode": { 89 | "name": "ipython", 90 | "version": 3 91 | }, 92 | "file_extension": ".py", 93 | "mimetype": "text/x-python", 94 | "name": "python", 95 | "nbconvert_exporter": "python", 96 | "pygments_lexer": "ipython3", 97 | "version": "3.8.10" 98 | } 99 | }, 100 | "nbformat": 4, 101 | "nbformat_minor": 2 102 | } 103 | -------------------------------------------------------------------------------- /Printing Excel sheet/Orders-With Nulls.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Printing Excel sheet/Orders-With Nulls.xlsx -------------------------------------------------------------------------------- /Printing Excel sheet/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | from openpyxl import load_workbook 3 | import win32print 4 | import win32ui 5 | 6 | def print_excel_sheet(excel_file_path): 7 | try: 8 | # Load the Excel workbook 9 | wb = load_workbook(filename=excel_file_path, read_only=True) 10 | 11 | # Get the first sheet (you can modify this to print a specific sheet) 12 | sheet = wb.active 13 | 14 | # Create a temporary text file to store the sheet content 15 | temp_txt_file = "temp_sheet.txt" 16 | with open(temp_txt_file, "w") as txt_file: 17 | for row in sheet.iter_rows(values_only=True): 18 | txt_file.write("\t".join(map(str, row)) + "\n") 19 | 20 | # Get the default printer 21 | printer_name = win32print.GetDefaultPrinter() 22 | 23 | # Initialize the printer and document properties 24 | printer_handle = win32print.OpenPrinter(printer_name) 25 | printer_info = win32print.GetPrinter(printer_handle, 2) 26 | hprinter = win32print.OpenPrinter(printer_name, {"DesiredAccess": win32print.PRINTER_ACCESS_USE}) 27 | 28 | # Print the text file to the printer 29 | printer_data = open(temp_txt_file, "rb").read() 30 | win32print.StartDocPrinter(hprinter, 1, ("Excel Sheet", None, "RAW")) 31 | win32print.StartPagePrinter(hprinter) 32 | win32print.WritePrinter(hprinter, printer_data) 33 | win32print.EndPagePrinter(hprinter) 34 | win32print.EndDocPrinter(hprinter) 35 | 36 | # Clean up temporary files 37 | os.remove(temp_txt_file) 38 | 39 | print("Excel sheet printed successfully.") 40 | except Exception as e: 41 | print(f"Error: {e}") 42 | 43 | if __name__ == "__main__": 44 | excel_file_path = "Printing Excel sheet\Orders-With Nulls.xlsx" # Replace with the path to your Excel file 45 | print_excel_sheet(excel_file_path) 46 | -------------------------------------------------------------------------------- /Printing Excel sheet/readme.md: -------------------------------------------------------------------------------- 1 | # Excel Sheet Printer 2 | 3 | ## Description 4 | 5 | The Excel Sheet Printer is a Python script that allows users to print Excel sheets in the command line. This script provides a simple and efficient way to view the contents of Excel files without the need for external applications. 6 | 7 | 8 | 9 | ## Installation 10 | 11 | 1. Clone the repository to your local machine: 12 | 13 | ```bash 14 | git clone https://github.com/your-username/excel-sheet-printer.git 15 | 16 | 17 | ## Usage 18 | 19 | To print an Excel sheet, run the following command in your terminal: 20 | 21 | python excel_printer.py path/to/excel_file.xlsx 22 | 23 | Replace path/to/excel_file.xlsx with the path to your Excel file. 24 | 25 | ## Features 26 | Print Excel sheets in the command line. 27 | Support for various Excel file formats (XLSX). 28 | Simple and user-friendly interface. 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | ![PythonScriptsHub](https://socialify.git.ci/Swapnil-Singh-99/PythonScriptsHub/image?description=1&descriptionEditable=Diverse%20collection%20of%20Python%20Scripts&font=Jost&name=1&owner=1&pattern=Plus&theme=Auto) 5 | 6 |
7 | 8 | ![Open Source Love](https://badges.frapsoft.com/os/v2/open-source.svg?v=103)   ![PRs Welcome](https://img.shields.io/badge/PRs-welcome-green.svg)   9 | LOC   10 | Stars Badge  Forks Badge   11 | ![GitHub contributors](https://img.shields.io/github/contributors/Swapnil-Singh-99/PythonScriptsHub?color=blue)   12 | ![GitHub last commit](https://img.shields.io/github/last-commit/Swapnil-Singh-99/PythonScriptsHub?color=red&style=plastic)   13 | ![Repo. Size](https://img.shields.io/github/repo-size/Swapnil-Singh-99/PythonScriptsHub?color=white)   14 |   15 |   16 |   17 |   18 |   19 | 20 |
21 |
22 | 23 | ## 📌 Opensource Programs 24 | 25 | ### This project is a part of following Open Source Programs 26 | 27 |

Logo

28 | 29 | ## 💻Table of Contents 30 | - **[How to Contribute?](#how-to-contribute)** 31 | - **[Project Admin](#project-admin)** 32 | - **[Our Valuable Contributors](#our-valuable-contributors)** 33 | 34 | ## How to Contribute? 35 | 36 | - Check it out [here](https://github.com/Swapnil-Singh-99/PythonScriptsHub/blob/main/CONTRIBUTING.md). 37 | - Enhance the clarity of your Pull Request by including relevant screenshots or screen captures. This helps everyone understand the visual impact of your proposed changes. 38 | 39 | Your contributions are highly appreciated! Let's collaborate to make PythonScriptsHub even better. 40 | 41 | Feel free to reach out if you have any questions or need assistance. 42 | 43 | ## Project Maintainers 44 | 45 | 46 | 47 | 49 | 51 | 52 |

Swapnil Singh

48 |

Yash Shukla

50 |
53 |
54 | 55 | ## Our Valuable Contributors 56 | 57 | 58 | 59 | 64 | 65 |
60 | 61 | 62 | 63 |
66 | 67 |

68 | 69 | --- 70 | 71 |
72 | If you find this project valuable or if you've learned something from it, give it a ⭐! 73 |

74 | 75 | 76 |
77 | -------------------------------------------------------------------------------- /Regular-Expressions/Regular-Expressions.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def validate_email(email): 4 | # Define the regular expression pattern for validating email addresses 5 | pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' 6 | 7 | # Use the re.match function to match the pattern against the email address 8 | if re.match(pattern, email): 9 | return True 10 | else: 11 | return False 12 | 13 | # Infinite loop to validate emails based on user input 14 | while True: 15 | user_input = input("Enter an email address (or type 'q' to quit): ") 16 | 17 | if user_input.lower() == 'q': 18 | break 19 | 20 | is_valid = validate_email(user_input) 21 | print(f"Is {user_input} a valid email address? {is_valid}") 22 | 23 | -------------------------------------------------------------------------------- /Resize_Image/input_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Resize_Image/input_image.png -------------------------------------------------------------------------------- /Resize_Image/output_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Resize_Image/output_image.png -------------------------------------------------------------------------------- /Resize_Image/resize_image.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | 4 | def resize_image(input_image, output_image, new_width, new_height): 5 | # Read the input image 6 | image = cv2.imread(input_image) 7 | 8 | # Resize the image 9 | resized_image = cv2.resize(image, (new_width, new_height)) 10 | 11 | # Save the resized image 12 | cv2.imwrite(output_image, resized_image) 13 | 14 | print("Image resized and saved successfully!") 15 | 16 | # Display the original image 17 | cv2.imshow('Original Image', image) 18 | cv2.waitKey(0) 19 | 20 | # Display the resized image 21 | resized_image = cv2.imread(output_image) 22 | cv2.imshow('Resized Image', resized_image) 23 | cv2.waitKey(0) 24 | cv2.destroyAllWindows() 25 | 26 | 27 | # Specify the input image path, output image path, and new dimensions 28 | input_image_path = 'input_image.png' 29 | output_image_path = 'output_image.png' 30 | new_width = 300 31 | new_height = 150 32 | 33 | # Resize the image 34 | resize_image(input_image_path, output_image_path, new_width, new_height) -------------------------------------------------------------------------------- /Resumenator/HomePage.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | #from streamlit_option_menu import option_menu 3 | from jinja2 import Environment, FileSystemLoader, select_autoescape 4 | from Resume import temp1 5 | from Portfolio import temp2 6 | import base64 # Import the base64 module 7 | if 'resume1' not in st.session_state: 8 | st.session_state['resume1']=True 9 | if 'temp1' not in st.session_state: 10 | st.session_state['temp1']=False 11 | if 'temp2' not in st.session_state: 12 | st.session_state['temp2']=False 13 | st.sidebar.header("Select your Templates") 14 | 15 | st.sidebar.image("Portfolio.png",caption="Portfolio",use_column_width=True) 16 | temp_button2 = st.sidebar.button("Portfolio 💼", key='btn2') 17 | 18 | 19 | st.write("\n\n") 20 | 21 | st.sidebar.image("Resume.jpeg",caption="Resume",use_column_width=True) 22 | temp_button1 = st.sidebar.button("Resume 📁",key="btn1") 23 | 24 | image_options = { 25 | "Template 1": "/Users/mitta/OneDrive/Pictures/Screenshots/template1.png", 26 | "Template 2": "/Users/mitta/OneDrive/Pictures/Screenshots/template1.png" 27 | } 28 | #st.sidebar.image("/Users/mitta/OneDrive/Pictures/Screenshots/template1.png",caption="Template 1",use_column_width=True) 29 | #st.sidebar.image("/Users/mitta/OneDrive/Pictures/Screenshots/template2.png",caption="Template 2",use_column_width=True) 30 | if temp_button1 and not st.session_state['temp1']: 31 | st.session_state['temp1']=True 32 | st.session_state['temp2']=False 33 | temp1() 34 | elif temp_button2 and not st.session_state['temp2']: 35 | st.session_state['temp2']=True 36 | st.session_state['temp1']=False 37 | temp2() 38 | elif st.session_state['temp1']: 39 | temp1() 40 | elif st.session_state['temp2']: 41 | temp2() 42 | -------------------------------------------------------------------------------- /Resumenator/Portfolio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Resumenator/Portfolio.png -------------------------------------------------------------------------------- /Resumenator/Portfolio.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from jinja2 import Environment, FileSystemLoader, select_autoescape 3 | import base64 4 | template_env = Environment( 5 | loader=FileSystemLoader("templates"), 6 | autoescape=select_autoescape(['html', 'xml']) 7 | ) 8 | def generate_resume(user_data): 9 | template = template_env.get_template("PortfolioTemplate.html") 10 | rendered_html = template.render(data=user_data) 11 | return rendered_html 12 | def save_to_html(html_content): 13 | with open("Portfolio.html", "w") as html_file: 14 | html_file.write(html_content) 15 | def temp2(): 16 | st.title("Portfolio Generator") 17 | user_data = { 18 | "Companies": [], 19 | "Skills": [], 20 | "Hobbies": [], 21 | "Education": [], 22 | "Projects":[], 23 | "Ach":[], 24 | "PL":[], 25 | "Tool":[] 26 | } 27 | st.subheader("Personal Information") 28 | cols1, cols2 = st.columns(2) 29 | user_data["Name"] = cols1.text_input("Name") 30 | user_data["Call"] = cols1.text_input("Call") 31 | user_data["Mail"] = cols1.text_input("Mail") 32 | user_data["Website"] = cols1.text_input("Website") 33 | user_data["Home"] = cols2.text_input("Home") 34 | user_data["TwitterID"] = cols2.text_input("Twitter ID") 35 | user_data["LinkedinID"] = cols2.text_input("Linkedin ID") 36 | user_data["GithubID"] = cols2.text_input("Github ID") 37 | user_data["Bio"] = st.text_area("Bio", height=200) # Increase the text area height 38 | num_companies = st.number_input("Number of Companies to Add", min_value=0, step=1) 39 | for i in range(num_companies): 40 | st.write(f"Company {i + 1}") 41 | cols = st.columns(4) # Divide row into 4 columns 42 | company_data = { 43 | "CompanyName": cols[0].text_input(f"Company Name", key=f"company_name_{i}"), 44 | "CompanyPeriod": cols[1].text_input(f"Company Period", key=f"company_period_{i}"), 45 | "CompanyRole": cols[2].text_input(f"Company Role", key=f"company_role_{i}"), 46 | "WorkDetails": cols[3].text_input(f"Work Details", key=f"work_details_{i}"), 47 | } 48 | user_data["Companies"].append(company_data) 49 | 50 | num_Education = st.number_input("Education Data", min_value=0, step=1) 51 | for i in range(num_Education): 52 | st.write(f"Education Institute {i + 1}") 53 | cols = st.columns(4) # Divide row into 4 columns 54 | Education_data = { 55 | "SchoolName": cols[0].text_input(f"School Name", key=f"SchoolName{i}"), 56 | "StudyPeriod": cols[1].text_input(f"Study period", key=f"StudyPeriod{i}"), 57 | "CourseName": cols[2].text_input(f"course Name", key=f"CourseName{i}"), 58 | "GPA": cols[3].text_input(f"GPA", key=f"GPA{i}"), 59 | } 60 | user_data["Education"].append(Education_data) 61 | 62 | num_Projects = st.number_input("Projects Data", min_value=0, step=1) 63 | for i in range(num_Projects): 64 | st.write(f"Project {i + 1}") 65 | cols = st.columns(2) # Divide row into 4 columns 66 | Projects_data = { 67 | "ProjectName": cols[0].text_input(f"Project Name", key=f"Project_Name{i}"), 68 | "Techstacks": cols[1].text_input(f"Techstacks", key=f"ProjectName{i}"), 69 | "PDescription": st.text_area(f"Project Description", height=200,key=f"PDescription{i}"), 70 | } 71 | user_data["Projects"].append(Projects_data) 72 | 73 | 74 | num_skills = st.number_input("Number of Skills to Add", min_value=0, step=1, value=0) 75 | for i in range(num_skills): 76 | user_data["Skills"].append(st.text_input(f"Skill {i + 1}")) 77 | num_hobbies = st.number_input("Number of Hobbies to Add", min_value=0, step=1, value=0) 78 | for i in range(num_hobbies): 79 | user_data["Hobbies"].append(st.text_input(f"Hobby {i + 1}")) 80 | num_Ach = st.number_input("Number of Achievements to Add", min_value=0, step=1, value=0) 81 | for i in range(num_Ach): 82 | user_data["Ach"].append(st.text_input(f"Achievement {i + 1}")) 83 | ProgrammingLangs = st.number_input("Number of Programming Languages to Add", min_value=0, step=1, value=0) 84 | for i in range(ProgrammingLangs): 85 | user_data["PL"].append(st.text_input(f"Programming Lang {i + 1}")) 86 | num_tools = st.number_input("Number of Tools to Add", min_value=0, step=1, value=0) 87 | for i in range(num_tools): 88 | user_data["Tool"].append(st.text_input(f"Tool {i + 1}")) 89 | uploaded_image = st.file_uploader("Upload Profile Image", type=["jpg", "jpeg", "png"]) 90 | if uploaded_image is not None: 91 | image_data = uploaded_image.read() 92 | encoded_image = base64.b64encode(image_data).decode("utf-8") 93 | user_data["ProfileImage"] = encoded_image 94 | if st.button("Generate Resume"): 95 | resume = generate_resume(user_data) 96 | save_to_html(resume) 97 | st.success("Portfolio generated successfully!") 98 | st.balloons() 99 | with open('Portfolio.html', 'rb') as f: 100 | st.download_button('Download resume', f, file_name='Portfolio.html') 101 | -------------------------------------------------------------------------------- /Resumenator/README.md: -------------------------------------------------------------------------------- 1 | # Resumenator 2 | Resumenator 3 | # try it here 4 | https://resumenator.streamlit.app/ 5 | -------------------------------------------------------------------------------- /Resumenator/Resume.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Resumenator/Resume.jpeg -------------------------------------------------------------------------------- /Resumenator/Resume.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from jinja2 import Environment, FileSystemLoader, select_autoescape 3 | # Load Jinja environment with the template folder 4 | def temp1() : 5 | template_env = Environment( 6 | loader=FileSystemLoader("templates"), 7 | autoescape=select_autoescape(['html', 'xml']) 8 | ) 9 | def generate_resume(user_data): 10 | template = template_env.get_template("ResumeTemplate.html") 11 | rendered_html = template.render(data=user_data) 12 | return rendered_html 13 | def save_to_html(html_content): 14 | with open("Resume.html", "w") as html_file: 15 | html_file.write(html_content) 16 | 17 | user_data1 = {'Inst':[],'Proj':[]} 18 | st.title("Resume Generator") 19 | # Input fields for user data 20 | name = st.text_input("Name") 21 | email = st.text_input("Email") 22 | phone = st.text_input("Phone") 23 | a=st.columns([1,2]) 24 | with a[0]: 25 | number_inputs = st.number_input('Number of Degrees',min_value=1, max_value=10) 26 | for i in range(number_inputs): 27 | st.write(f"Institute {i + 1}") 28 | cols = st.columns(4) # Divide row into 4 columns 29 | Inst_data = { 30 | "Institutename": cols[0].text_input(f"Institution Name", key=f"Institute_name{i}"), 31 | "Degreetype": cols[1].text_input(f"Degree type", key=f"Degree_type{i}"), 32 | "Degreeperiod": cols[2].text_input(f"Degree period", key=f"Degree_period{i}"), 33 | "cgpa": cols[3].text_input(f"Percentage / CGPA", key=f"cgpa_{i}"), 34 | } 35 | user_data1['Inst'].append(Inst_data) 36 | b = st.columns([1,2]) 37 | with b[0]: 38 | number_inputs1 = st.number_input('Number of Projects',min_value=1, max_value=10) 39 | for i in range(number_inputs1): 40 | st.write(f"Projects {i + 1}") 41 | cols = st.columns(3) # Divide row into 3 columns 42 | Project_data = { 43 | "ProjectName": cols[0].text_input(f"Project Name", key=f"project_name{i}"), 44 | "ProjectDesc": cols[1].text_input(f"Project Description", key=f"Project_desc{i}"), 45 | "ProjectStack": cols[2].text_input(f"Tech Stack used", key=f"tech_stacks{i}"), 46 | } 47 | user_data1['Proj'].append(Project_data) 48 | achivements = st.text_input('Achivements (seperate with , )') 49 | result_ach = achivements.split(',') 50 | prog_lan = st.text_input("Programming Languages you know (seperate with , )") 51 | result_pro = prog_lan.split(',') 52 | tools = st.text_input("Tools Used till now (seperate with , )") 53 | result_tools = tools.split(',') 54 | user_data = { 55 | "Name": name, 56 | "Email": email, 57 | "Phone": phone, 58 | "ProgLang": result_pro, 59 | "Tools": result_tools, 60 | "Achievement": result_ach, 61 | "GithubID": st.text_input("Github ID"), 62 | "LinkedinID": st.text_input("Linkedin ID"), 63 | "HackerRankID": st.text_input("HackerRank ID") 64 | } 65 | user_data.update(user_data1) 66 | if st.button("Generate Resume"): 67 | resume = generate_resume(user_data) 68 | save_to_html(resume) 69 | st.success("Resume generated successfully!") 70 | st.balloons() 71 | # Add a download button 72 | with open('Resume.html', 'rb') as f: 73 | st.download_button('Download resume', f, file_name='Resume.html') 74 | -------------------------------------------------------------------------------- /Resumenator/packages.txt: -------------------------------------------------------------------------------- 1 | wkhtmltopdf 2 | -------------------------------------------------------------------------------- /Resumenator/requirements.txt: -------------------------------------------------------------------------------- 1 | jinja2 2 | requests 3 | pdfkit 4 | streamlit 5 | -------------------------------------------------------------------------------- /Rock, Paper & Scissors/game.py: -------------------------------------------------------------------------------- 1 | # #program to make a game of rock, papers & scissors using python 2 | # import random 3 | 4 | # maxScore=int(input("Enter the Max Score: ")) 5 | # compScore=0 6 | # userScore=0 7 | 8 | # while maxScore: 9 | # user_input=input("Choose (rock (r), paper (p) or scissors (s): ") 10 | # options=["r","p","s"] 11 | # computer_input=random.choice(options) 12 | # print("Your Choice: ", user_input, "\nComputer's Choice: ", computer_input) 13 | 14 | # if (user_input==computer_input): 15 | # print("It's a TIE! Nobody gets a score!\n") 16 | # elif (user_input=="r"): 17 | # if (computer_input=="p"): 18 | # print("Computer WON! You Lose!\n") 19 | # compScore+=1 20 | # else: 21 | # print("You WON! Computer Lose!\n") 22 | # userScore+=1 23 | # elif (user_input=="p"): 24 | # if (computer_input=="s"): 25 | # print("Computer WON! You Lose!\n") 26 | # compScore+=1 27 | # else: 28 | # print("You WON! Computer Lose!\n") 29 | # userScore+=1 30 | # elif (user_input=="s"): 31 | # if (computer_input=="r"): 32 | # print("Computer WON! You Lose!\n") 33 | # compScore+=1 34 | # else: 35 | # print("You WON! Computer Lose!\n") 36 | # userScore+=1 37 | # print("User Score: ", userScore, "\nComputer Score: ", compScore) 38 | 39 | # if (userScore==maxScore): 40 | # print("User WON!") 41 | # elif (compScore==maxScore): 42 | # print("Computer WON!") 43 | # if (userScore==maxScore or compScore==maxScore): 44 | # break 45 | 46 | import random 47 | 48 | def get_user_choice(): 49 | while True: 50 | user_input = input("Choose (rock (r), paper (p), or scissors (s)): ").lower() 51 | if user_input in ['r', 'p', 's']: 52 | return user_input 53 | else: 54 | print("Invalid input. Please choose 'r', 'p', or 's'.") 55 | 56 | def determine_winner(user_choice, computer_choice): 57 | outcomes = {'r': 's', 's': 'p', 'p': 'r'} 58 | if user_choice == computer_choice: 59 | return "It's a tie!", None 60 | elif outcomes[user_choice] == computer_choice: 61 | return "You win!", 'user' 62 | else: 63 | return "Computer wins!", 'computer' 64 | 65 | def play_game(): 66 | max_score = int(input("Enter the Max Score: ")) 67 | comp_score = 0 68 | user_score = 0 69 | 70 | while True: 71 | user_input = get_user_choice() 72 | options = ['r', 'p', 's'] 73 | computer_input = random.choice(options) 74 | 75 | print("Your Choice:", user_input) 76 | print("Computer's Choice:", computer_input) 77 | 78 | result, winner = determine_winner(user_input, computer_input) 79 | print(result) 80 | 81 | if winner == 'user': 82 | user_score += 1 83 | elif winner == 'computer': 84 | comp_score += 1 85 | 86 | print("User Score:", user_score) 87 | print("Computer Score:", comp_score) 88 | 89 | if user_score == max_score: 90 | print("User WON!") 91 | break 92 | elif comp_score == max_score: 93 | print("Computer WON!") 94 | break 95 | 96 | play_again = input("Do you want to play again? (yes/no): ").lower() 97 | return play_again == 'yes' 98 | 99 | while True: 100 | if not play_game(): 101 | print("Thanks for playing! Goodbye.") 102 | break 103 | -------------------------------------------------------------------------------- /SCRIPTS.md: -------------------------------------------------------------------------------- 1 |

🚀 Python Scripts Available 🚀

2 | 3 | | SL No\. | 🚀 Script Name | 👨🏻‍💻 Script Function | 🔗 Link | 👩🏻‍💻 Contributed By | 4 | |--------- |-------------------------|----------------------------------------------------------------------------------|------------|--------------------| 5 | |1.|Google Logo|Make a google logo using python turtle module|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Google_Logo)|[Swapnil-Singh-99](https://github.com/Swapnil-Singh-99)| 6 | |2.|Image Resize|A program to resize an image file|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Resize_Image)|[Swapnil-Singh-99](https://github.com/Swapnil-Singh-99)| 7 | |3.|Send Mail|A program to send mail using python|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Send_Mail)|[Swapnil-Singh-99](https://github.com/Swapnil-Singh-99)| 8 | |4.|OS Tasks|A program to shutdown, logoff, restart and many more laptop/computer|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Shutdown)|[Swapnil-Singh-99](https://github.com/Swapnil-Singh-99)| 9 | |5.|Website Blocker|A program to block websites on your laptop/computer for a time interval|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Website_Blocker)|[Swapnil-Singh-99](https://github.com/Swapnil-Singh-99)| 10 | |6.|Clock GUI|A simple digital clock Gui using Tkinter|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Clock%20GUI)|[Abhinavcode13](https://github.com/Abhinavcode13)| 11 | |7.|Task Schedule(ToDo)|A Task Schedule GUI|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Task%20schedule)|[Transyltooniaa](https://github.com/Transyltooniaa)| 12 | |8.|Temperature Converter GUI|A tkinter interface to convert temperature from *C to F or vice-versa|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Temperature%20Converter)|[aryanas159](https://github.com/aryanas159)| 13 | |9.|Hangman Game|Terminal Hangman Game|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/hangman)|[Transyltooniaa](https://github.com/Transyltooniaa)| 14 | |10.|Reverse a number|A python script to print the reverse of a number|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/reverse-number-script)|[Parvezkhan0](https://github.com/Parvezkhan0)| 15 | |11.|Desktop Task Notifier|A python script that will notify user after a specific time for a task|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/desktop-notifier-task)|[Parvez Khan](https://github.com/Parvezkhan0)| 16 | |12.|Password Strength Checker|This python script will tell whether the password is weak or strong|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/passwordChecker)|[Transyltooniaa](https://github.com/Transyltooniaa)| 17 | |13.|Dice Roll Simulator|Simple dice roll animation|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Dice%20Rolling%20Simulator)|[Aryan Singh](https://github.com/aryanas159)| 18 | |14.|Currency Convertor|A simple currency convertor GUI|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Currency%20Converter)|[Aryan Singh](https://github.com/aryanas159)| 19 | |15.|BMI Calculator|Calculates the Body Mass Index based on the given inputs|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/BMI%20Calculator)|[Ayan Joshi](https://github.com/ayan-joshi)| 20 | |16.|Email Validator|Validates the inputed Email using Regular expressions|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/Regular-Expressions)|[Parvez Khan](https://github.com/Parvezkhan0)| 21 | |17.|Fibonacci Series|Generates fibonacci series based on number of expressions required|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/fibonacci-generation)|[Parvez Khan](https://github.com/Parvezkhan0)| 22 | |18.|Calculator GUI|GUI Calculator app made using Tkinter|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/CalculatorGUI)|[Vidip Ghosh](https://github.com/Vidip-Ghosh)| 23 | |19.|Timer|Timer GUI|[Link](https://github.com/Swapnil-Singh-99/PythonScriptsHub/tree/main/timer)|[Transyltooniaa](https://github.com/Transyltooniaa)| 24 | -------------------------------------------------------------------------------- /Send_Mail/send_mail.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | 3 | try: 4 | server = smtplib.SMTP("smtp.gmail.com", 587) 5 | server.ehlo() 6 | server.starttls() 7 | print("SERVER CONNECTED") 8 | except: 9 | print("Could Not connect to Gmail") 10 | 11 | user = input("Enter User id\n") 12 | Pass_w = input("\nEnter your Password\n") 13 | reciever_id = input("\nEnter reciever id\n") 14 | msg = input("\nEnter message\n") 15 | try: 16 | print("User Logged in") 17 | except: 18 | print("Allow Less secure apps in GOOGLE ACCOUNT SETTINGS to use SMTP services") 19 | server.quit() 20 | exit() 21 | 22 | server.sendmail(user, reciever_id, msg) 23 | print("MAIL sent") 24 | 25 | print("Closing Connection") 26 | server.quit() 27 | print("Server closed") 28 | -------------------------------------------------------------------------------- /Shutdown/shutdown.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | print("1. Shutdown") 4 | print("2. Reboot") 5 | print("3. Lock") 6 | print("4. Sign Out") 7 | user_input = int(input("Please provide your input [1/2/3/4]: ")) 8 | 9 | 10 | def shutdown(): 11 | os.system("shutdown /s /t 1") 12 | 13 | def reboot(): 14 | os.system("shutdown /r /t 1") 15 | 16 | def logoff(): 17 | os.system("shutdown /l") 18 | 19 | def lockpc(): 20 | os.system(r'"C:\Windows\System32\rundll32.exe user32.dll,LockWorkStation"') 21 | 22 | if user_input == 1: 23 | shutdown() 24 | elif user_input == 2: 25 | reboot() 26 | elif user_input == 3: 27 | lockpc() 28 | elif user_input == 4: 29 | logoff() 30 | else: 31 | exit() -------------------------------------------------------------------------------- /Speech Recognition/speech.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 as px 2 | import speech_recognition as sr 3 | 4 | rec = sr.Recognizer() 5 | engine = px.init() 6 | engine.setProperty('rate', 150) 7 | engine.setProperty('volume', 0.9) 8 | voices = engine.getProperty('voices') 9 | engine.setProperty('voice', voices[1].id) 10 | 11 | def speak(text): 12 | engine.say(text) 13 | engine.runAndWait() 14 | 15 | def takeCommand(): 16 | try: 17 | with sr.Microphone() as source: 18 | print('Listening...') 19 | voice = rec.listen(source, phrase_time_limit=2) 20 | command = rec.recognize_google(voice) 21 | command = command.lower() 22 | return command 23 | except: 24 | pass 25 | 26 | def main(): 27 | speak('Listening...') 28 | while True: 29 | command = takeCommand() 30 | if command is not None: 31 | speak('You might have said ' + command) 32 | print('You might have said ' + command) 33 | else: 34 | speak('Please say something.') 35 | 36 | main() -------------------------------------------------------------------------------- /Talking Bot/about.md: -------------------------------------------------------------------------------- 1 | # Adrien 1.0 2 | - Adrien is a chatbot who takes response in text and responds in voice. 3 | - it can convert text to speech 4 | -------------------------------------------------------------------------------- /Talking Bot/main.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 2 | engine = pyttsx3.init() 3 | 4 | call=input() 5 | if call.lower()=="hi" or call.lower()=="hello" or call.lower()=="hey": 6 | engine.say("Hola") 7 | engine.runAndWait() 8 | engine.say("What's your name my lady?") 9 | engine.runAndWait() 10 | print("What's your name? ") 11 | usernm=input() 12 | print("Hello "+usernm) 13 | engine.say("Hello "+usernm) 14 | engine.runAndWait() 15 | engine.say("what are you doing?"+usernm) 16 | engine.runAndWait() 17 | -------------------------------------------------------------------------------- /Task schedule/main.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import messagebox, ttk 3 | from tkcalendar import DateEntry 4 | import sqlite3 5 | from datetime import datetime 6 | 7 | class Task: 8 | def __init__(self, name, priority, due_date): 9 | self.name = name 10 | self.priority = priority 11 | self.due_date = due_date 12 | 13 | class TaskManagerApp: 14 | def __init__(self, root): 15 | self.root = root 16 | self.root.title("Task Manager") 17 | 18 | self.tasks = [] 19 | 20 | self.task_name_var = tk.StringVar() 21 | self.priority_var = tk.StringVar() 22 | self.due_date_var = tk.StringVar() 23 | 24 | self.create_widgets() 25 | 26 | # Create a database connection and a cursor 27 | self.conn = sqlite3.connect("tasks.db") 28 | self.cursor = self.conn.cursor() 29 | 30 | # Create the tasks table if it doesn't exist 31 | self.cursor.execute(''' 32 | CREATE TABLE IF NOT EXISTS tasks ( 33 | id INTEGER PRIMARY KEY AUTOINCREMENT, 34 | name TEXT, 35 | priority TEXT, 36 | due_date DATE 37 | ) 38 | ''') 39 | 40 | # Retrieve tasks from the database 41 | self.retrieve_tasks_from_db() 42 | 43 | def create_widgets(self): 44 | # Task Name Label and Entry 45 | tk.Label(self.root, text="Task Name:").grid(row=0, column=0, sticky="w") 46 | task_name_entry = tk.Entry(self.root, textvariable=self.task_name_var) 47 | task_name_entry.grid(row=0, column=1, padx=10, pady=5) 48 | 49 | # Priority Label and Dropdown 50 | tk.Label(self.root, text="Priority:").grid(row=1, column=0, sticky="w") 51 | priority_values = ["Low", "Medium", "High"] 52 | priority_dropdown = ttk.Combobox(self.root, textvariable=self.priority_var, values=priority_values) 53 | priority_dropdown.grid(row=1, column=1, padx=10, pady=5) 54 | 55 | # Due Date Label and Calendar 56 | tk.Label(self.root, text="Due Date:").grid(row=2, column=0, sticky="w") 57 | 58 | # Initialize the calendar widget and store it as an instance variable 59 | self.due_date_calendar = DateEntry(self.root, textvariable=self.due_date_var, date_pattern="yyyy-mm-dd") 60 | self.due_date_calendar.grid(row=2, column=1, padx=10, pady=5) 61 | 62 | # Add Task Button 63 | add_task_button = tk.Button(self.root, text="Add Task", command=self.add_task) 64 | add_task_button.grid(row=3, column=0, columnspan=2, padx=10, pady=5) 65 | 66 | # Task List Treeview 67 | self.task_list_treeview = ttk.Treeview(self.root, columns=("Priority", "Due Date")) 68 | self.task_list_treeview.grid(row=4, column=0, columnspan=2, padx=10, pady=5) 69 | self.task_list_treeview.heading("#0", text="Task Name") 70 | self.task_list_treeview.heading("Priority", text="Priority") 71 | self.task_list_treeview.heading("Due Date", text="Due Date") 72 | 73 | # Delete Task Button 74 | delete_task_button = tk.Button(self.root, text="Delete Task", command=self.delete_task) 75 | delete_task_button.grid(row=5, column=0, padx=10, pady=5, sticky="w") 76 | 77 | # Clear Task Button 78 | clear_task_button = tk.Button(self.root, text="Clear Task", command=self.clear_task) 79 | clear_task_button.grid(row=5, column=1, padx=10, pady=5, sticky="e") 80 | 81 | def add_task(self): 82 | name = self.task_name_var.get() 83 | priority = self.priority_var.get() 84 | due_date = self.due_date_var.get() 85 | 86 | if name and priority and due_date: 87 | task = Task(name, priority, due_date) 88 | self.tasks.append(task) 89 | 90 | self.task_list_treeview.insert("", tk.END, text=task.name, values=(task.priority, task.due_date)) 91 | 92 | self.task_name_var.set("") 93 | self.priority_var.set("") 94 | self.due_date_var.set("") 95 | 96 | # Insert the task into the database 97 | self.cursor.execute("INSERT INTO tasks (name, priority, due_date) VALUES (?, ?, ?)", 98 | (task.name, task.priority, task.due_date)) 99 | self.conn.commit() 100 | 101 | # Reinitialize the calendar widget to fix the display issue 102 | self.due_date_calendar.destroy() 103 | self.due_date_calendar = DateEntry(self.root, textvariable=self.due_date_var, date_pattern="yyyy-mm-dd") 104 | self.due_date_calendar.grid(row=2, column=1, padx=10, pady=5) 105 | else: 106 | messagebox.showerror("Error", "Please fill in all fields.") 107 | 108 | def delete_task(self): 109 | selected_item = self.task_list_treeview.selection() 110 | if selected_item: 111 | task_name = self.task_list_treeview.item(selected_item)["text"] 112 | for task in self.tasks: 113 | if task.name == task_name: 114 | self.tasks.remove(task) 115 | self.task_list_treeview.delete(selected_item) 116 | 117 | # Delete the task from the database 118 | self.cursor.execute("DELETE FROM tasks WHERE name=?", (task.name,)) 119 | self.conn.commit() 120 | break 121 | 122 | def clear_task(self): 123 | self.task_name_var.set("") 124 | self.priority_var.set("") 125 | self.due_date_var.set("") 126 | 127 | def retrieve_tasks_from_db(self): 128 | self.cursor.execute("SELECT name, priority, due_date FROM tasks") 129 | rows = self.cursor.fetchall() 130 | for row in rows: 131 | name, priority, due_date = row 132 | task = Task(name, priority, due_date) 133 | self.tasks.append(task) 134 | self.task_list_treeview.insert("", tk.END, text=task.name, values=(task.priority, task.due_date)) 135 | 136 | if __name__ == "__main__": 137 | root = tk.Tk() 138 | app = TaskManagerApp(root) 139 | root.mainloop() 140 | -------------------------------------------------------------------------------- /Task schedule/tasks.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/Task schedule/tasks.db -------------------------------------------------------------------------------- /Temperature Converter/temperature_converter.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | 3 | def convert_temperature(): 4 | try: 5 | temperature = float(entry.get()) 6 | if var.get() == 1: # Fahrenheit to Celsius 7 | result.set((temperature - 32) * 5/9) 8 | elif var.get() == 2: # Celsius to Fahrenheit 9 | result.set((temperature * 9/5) + 32) 10 | except ValueError: 11 | result.set("Invalid input") 12 | 13 | def on_validate_input(P): 14 | if P == "" or P.isdigit() or P[0] == "-": 15 | return True 16 | else: 17 | return False 18 | 19 | 20 | root = tk.Tk() 21 | root.title("Temperature Converter") 22 | 23 | var = tk.IntVar() 24 | 25 | frame = tk.Frame(root) 26 | frame.pack(pady=20) 27 | 28 | label = tk.Label(frame, text="Enter Temperature:") 29 | label.grid(row=0, column=0) 30 | 31 | validate_input = root.register(on_validate_input) 32 | entry = tk.Entry(frame, validate="key", validatecommand=(validate_input, "%P")) 33 | entry.grid(row=0, column=1) 34 | 35 | 36 | radio_fahrenheit = tk.Radiobutton(frame, text="Fahrenheit to Celsius", variable=var, value=1) 37 | radio_fahrenheit.grid(row=1, column=0, padx=10) 38 | 39 | radio_celsius = tk.Radiobutton(frame, text="Celsius to Fahrenheit", variable=var, value=2) 40 | radio_celsius.grid(row=1, column=1, padx=10) 41 | 42 | convert_button = tk.Button(frame, text="Convert", command=convert_temperature) 43 | convert_button.grid(row=2, columnspan=2, pady=10) 44 | 45 | result = tk.StringVar() 46 | result.set("") 47 | output_label = tk.Label(frame, textvariable=result) 48 | output_label.grid(row=3, columnspan=2) 49 | 50 | root.mainloop() 51 | -------------------------------------------------------------------------------- /Text Counter/text_counter.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def read_text_from_file(file_path): 4 | try: 5 | with open(file_path, 'r') as file: 6 | text = file.read() 7 | 8 | file.close() 9 | return text 10 | except FileNotFoundError: 11 | print("File not found. Please provide a valid file path.") 12 | return None 13 | 14 | 15 | def count_words(text): 16 | words = text.split() 17 | return len(words) 18 | 19 | 20 | def count_sentences(text): 21 | sentences = re.split(r'[.!?\n]', text) # Split's the sentences by . or ! or ? or \n 22 | 23 | sentences = [sentence for sentence in sentences if sentence.strip()] 24 | return len(sentences) 25 | 26 | 27 | def count_paragraphs(text): 28 | paragraphs = re.split(r'\n{2,}', text) 29 | # Assuming that paras are seperated by more than 1 \n (new line) 30 | 31 | paragraphs = [paragraph for paragraph in paragraphs if paragraph.strip()] 32 | return len(paragraphs) 33 | 34 | 35 | if __name__ == "__main__": 36 | 37 | file_path = input("Enter the file path: ") 38 | 39 | text = read_text_from_file(file_path) 40 | if text: 41 | word_count = count_words(text) 42 | sentence_count = count_sentences(text) 43 | paragraph_count = count_paragraphs(text) 44 | 45 | print("Word count:", word_count) 46 | print("Sentence count:", sentence_count) 47 | print("Paragraph count:", paragraph_count) 48 | -------------------------------------------------------------------------------- /Text based adventure game/game.py: -------------------------------------------------------------------------------- 1 | def introduction(): 2 | print("Welcome to the Text Adventure Game!") 3 | print("You find yourself in a mysterious forest. You have to make decisions to find your way out.") 4 | print("Let the adventure begin!\n") 5 | 6 | 7 | def make_choice(choices): 8 | print("Available Choices:") 9 | for index, choice in enumerate(choices, start=1): 10 | print(f"{index}. {choice}") 11 | 12 | while True: 13 | try: 14 | choice = int(input("Enter the number of your choice: ")) 15 | if 1 <= choice <= len(choices): 16 | return choice 17 | else: 18 | print("Invalid choice. Please try again.") 19 | except ValueError: 20 | print("Invalid input. Please enter a number.") 21 | 22 | 23 | def forest(): 24 | print("\nYou are in a dense forest. You can hear mysterious sounds all around you.") 25 | choices = ["Go deeper into the forest", "Try to climb a tree", "Go back"] 26 | choice = make_choice(choices) 27 | 28 | if choice == 1: 29 | print("\nYou venture deeper into the forest and get lost.") 30 | print("Game Over! You are lost in the forest.") 31 | elif choice == 2: 32 | print("\nYou climb a tree and spot a river in the distance.") 33 | river() 34 | else: 35 | print("\nYou decide to go back and find a different path.") 36 | start() 37 | 38 | 39 | def river(): 40 | print("\nYou reach the riverbank. The river is fast-flowing and looks dangerous.") 41 | choices = ["Swim across the river", "Look for a bridge", "Go back to the forest"] 42 | choice = make_choice(choices) 43 | 44 | if choice == 1: 45 | print("\nYou attempt to swim across the river but get swept away by the current.") 46 | print("Game Over! You got drowned in the river.") 47 | elif choice == 2: 48 | print("\nYou find a sturdy bridge and safely cross the river.") 49 | treasure() 50 | else: 51 | print("\nYou decide to go back to the forest and explore other options.") 52 | forest() 53 | 54 | 55 | def treasure(): 56 | print("\nCongratulations! You have successfully crossed the river.") 57 | print("You discover a hidden treasure chest!") 58 | print("You have won the game! Well done, adventurer!") 59 | 60 | 61 | def start(): 62 | introduction() 63 | forest() 64 | 65 | 66 | if __name__ == "_main_": 67 | start() -------------------------------------------------------------------------------- /Text to ASCII/ascii-art.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "pip install pyfiglet" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import pyfiglet\n", 19 | "\n", 20 | "def text_to_ascii_art(text):\n", 21 | " ascii_art = pyfiglet.figlet_format(text)\n", 22 | " return ascii_art\n", 23 | "\n", 24 | "def main():\n", 25 | " user_text = input(\"Enter the text you want to convert into ASCII art: \")\n", 26 | " ascii_art = text_to_ascii_art(user_text)\n", 27 | " print(ascii_art)\n", 28 | "\n", 29 | "if __name__ == \"__main__\":\n", 30 | " main()\n" 31 | ] 32 | } 33 | ], 34 | "metadata": { 35 | "kernelspec": { 36 | "display_name": "Python 3", 37 | "language": "python", 38 | "name": "python3" 39 | }, 40 | "language_info": { 41 | "codemirror_mode": { 42 | "name": "ipython", 43 | "version": 3 44 | }, 45 | "file_extension": ".py", 46 | "mimetype": "text/x-python", 47 | "name": "python", 48 | "nbconvert_exporter": "python", 49 | "pygments_lexer": "ipython3", 50 | "version": "3.10.11" 51 | } 52 | }, 53 | "nbformat": 4, 54 | "nbformat_minor": 2 55 | } 56 | -------------------------------------------------------------------------------- /Tic Tac Toe/Readme.md: -------------------------------------------------------------------------------- 1 | # Tic-Tac-Toe Command-Line Game 2 | 3 | This is a simple two-player command-line implementation of the classic game Tic-Tac-Toe (also known as Noughts and Crosses). Players take turns to make their moves, and the game continues until there's a winner or a draw. 4 | 5 | ## How to Play 6 | 7 | 1. Open your terminal or command prompt. 8 | 9 | 2. Navigate to the directory where you have the Python script for the game. 10 | 11 | 3. Run the script using Python: 12 | 13 | 4. The game will start, and you will see an empty Tic-Tac-Toe board: 14 | 15 | | | 16 | | | 17 | | | 18 | 19 | 20 | 5. Players take turns to make their moves. When prompted, enter the row (0, 1, or 2) and column (0, 1, or 2) where you want to place your symbol (X or O). For example, if you want to place your symbol in the top-right corner, you would enter "0" for the row and "2" for the column. 21 | 22 | 6. The game will display the updated board after each move. 23 | 24 | 7. The first player to get three of their symbols in a row (horizontally, vertically, or diagonally) wins the game. 25 | 26 | 8. If all cells on the board are filled, and there is no winner, the game ends in a draw. 27 | 28 | 9. To restart the game, simply run the script again. 29 | 30 | ## Enjoy the Game! 31 | 32 | Have fun playing this command-line Tic-Tac-Toe game! Challenge your friends and family to see who can become the ultimate Tic-Tac-Toe champion. 33 | 34 | Feel free to modify and improve the game as you like. Happy gaming! 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Tic Tac Toe/tic_tac_toe.py: -------------------------------------------------------------------------------- 1 | def print_board(board): 2 | for row in board: 3 | print(" | ".join(row)) 4 | print("-" * 9) 5 | 6 | def check_winner(board, player): 7 | for row in board: 8 | if all(cell == player for cell in row): 9 | return True 10 | 11 | for col in range(3): 12 | if all(board[row][col] == player for row in range(3)): 13 | return True 14 | 15 | if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)): 16 | return True 17 | 18 | return False 19 | 20 | def is_board_full(board): 21 | return all(cell != " " for row in board for cell in row) 22 | 23 | def main(): 24 | board = [[" " for _ in range(3)] for _ in range(3)] 25 | current_player = "X" 26 | 27 | print("Welcome to Tic-Tac-Toe!") 28 | print_board(board) 29 | 30 | while True: 31 | row = int(input(f"Player {current_player}, choose row (0, 1, or 2): ")) 32 | col = int(input(f"Player {current_player}, choose column (0, 1, or 2): ")) 33 | 34 | if board[row][col] == " ": 35 | board[row][col] = current_player 36 | else: 37 | print("That cell is already occupied. Try again.") 38 | continue 39 | 40 | print_board(board) 41 | 42 | if check_winner(board, current_player): 43 | print(f"Player {current_player} wins! Congratulations!") 44 | break 45 | elif is_board_full(board): 46 | print("It's a draw!") 47 | break 48 | 49 | current_player = "O" if current_player == "X" else "X" 50 | 51 | if __name__ == "__main__": 52 | main() 53 | -------------------------------------------------------------------------------- /Todo-list-GUI-app/app.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Akash Chaudhary 3 | GitHub Handle: akashchaudhary-git 4 | 5 | This script allows users to add tasks, view tasks, and delete tasks from the list. 6 | """ 7 | 8 | import tkinter as tk 9 | 10 | def add_task(): 11 | task = entry.get() 12 | if task: 13 | listbox.insert(tk.END, task) 14 | entry.delete(0, tk.END) 15 | 16 | def delete_task(): 17 | selected_task_index = listbox.curselection() 18 | if selected_task_index: 19 | listbox.delete(selected_task_index) 20 | 21 | # Create the main application window 22 | root = tk.Tk() 23 | root.title("To-Do List") 24 | 25 | # Create and configure the listbox 26 | listbox = tk.Listbox(root, width=50) 27 | listbox.pack(pady=10) 28 | 29 | # Create and configure the entry for adding new tasks 30 | entry = tk.Entry(root, width=40) 31 | entry.pack(pady=10) 32 | 33 | # Create and configure the buttons 34 | add_button = tk.Button(root, text="Add Task", command=add_task) 35 | add_button.pack(pady=5) 36 | 37 | delete_button = tk.Button(root, text="Delete Task", command=delete_task) 38 | delete_button.pack(pady=5) 39 | 40 | # Run the main event loop 41 | root.mainloop() 42 | -------------------------------------------------------------------------------- /Translator/Listen.py: -------------------------------------------------------------------------------- 1 | import speech_recognition as sr 2 | from googletrans import Translator 3 | 4 | #listen function 5 | def Listen(): 6 | r = sr.Recognizer() 7 | 8 | with sr.Microphone() as source: 9 | print("Listening...") 10 | r.pause_threshold = 1 11 | audio = r.listen(source,0,6) #listening 12 | 13 | try: 14 | print("Recognizing...") 15 | query = r.recognize_google(audio,language="hi") 16 | 17 | except: 18 | return "" 19 | 20 | query = str(query).lower() 21 | return query 22 | #translate function 23 | def TranslationHintoEng(text): 24 | line = str(text) 25 | translate = Translator() 26 | results = translate.translate(line,str = 'en') 27 | data = results.text 28 | print(f"You: {data}") 29 | return data 30 | #connect 31 | def Microcnnect(): 32 | query = Listen() 33 | data = TranslationHintoEng(query) 34 | return data 35 | Microcnnect() -------------------------------------------------------------------------------- /Translator/translator.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Readme" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "This script can convert text in about 114 languages but can speak the translated text in few languages which includes English, French, Hindi, Spanish, Mandarin, Portuguese" 15 | ] 16 | }, 17 | { 18 | "cell_type": "markdown", 19 | "metadata": {}, 20 | "source": [ 21 | "# Code" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "pip install SpeechRecognition googletrans==4.0.0-rc1 gtts" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "# Languages supported by Google Translate\n", 40 | "\n", 41 | "SPECIAL_CASES = {\n", 42 | " 'ee': 'et',\n", 43 | "}\n", 44 | "\n", 45 | "LANGUAGES = {\n", 46 | " 'af': 'afrikaans',\n", 47 | " 'sq': 'albanian',\n", 48 | " 'am': 'amharic',\n", 49 | " 'ar': 'arabic',\n", 50 | " 'hy': 'armenian',\n", 51 | " 'az': 'azerbaijani',\n", 52 | " 'eu': 'basque',\n", 53 | " 'be': 'belarusian',\n", 54 | " 'bn': 'bengali',\n", 55 | " 'bs': 'bosnian',\n", 56 | " 'bg': 'bulgarian',\n", 57 | " 'ca': 'catalan',\n", 58 | " 'ceb': 'cebuano',\n", 59 | " 'ny': 'chichewa',\n", 60 | " 'zh-cn': 'chinese (simplified)',\n", 61 | " 'zh-tw': 'chinese (traditional)',\n", 62 | " 'co': 'corsican',\n", 63 | " 'hr': 'croatian',\n", 64 | " 'cs': 'czech',\n", 65 | " 'da': 'danish',\n", 66 | " 'nl': 'dutch',\n", 67 | " 'en': 'english',\n", 68 | " 'eo': 'esperanto',\n", 69 | " 'et': 'estonian',\n", 70 | " 'tl': 'filipino',\n", 71 | " 'fi': 'finnish',\n", 72 | " 'fr': 'french',\n", 73 | " 'fy': 'frisian',\n", 74 | " 'gl': 'galician',\n", 75 | " 'ka': 'georgian',\n", 76 | " 'de': 'german',\n", 77 | " 'el': 'greek',\n", 78 | " 'gu': 'gujarati',\n", 79 | " 'ht': 'haitian creole',\n", 80 | " 'ha': 'hausa',\n", 81 | " 'haw': 'hawaiian',\n", 82 | " 'iw': 'hebrew',\n", 83 | " 'he': 'hebrew',\n", 84 | " 'hi': 'hindi',\n", 85 | " 'hmn': 'hmong',\n", 86 | " 'hu': 'hungarian',\n", 87 | " 'is': 'icelandic',\n", 88 | " 'ig': 'igbo',\n", 89 | " 'id': 'indonesian',\n", 90 | " 'ga': 'irish',\n", 91 | " 'it': 'italian',\n", 92 | " 'ja': 'japanese',\n", 93 | " 'jw': 'javanese',\n", 94 | " 'kn': 'kannada',\n", 95 | " 'kk': 'kazakh',\n", 96 | " 'km': 'khmer',\n", 97 | " 'ko': 'korean',\n", 98 | " 'ku': 'kurdish (kurmanji)',\n", 99 | " 'ky': 'kyrgyz',\n", 100 | " 'lo': 'lao',\n", 101 | " 'la': 'latin',\n", 102 | " 'lv': 'latvian',\n", 103 | " 'lt': 'lithuanian',\n", 104 | " 'lb': 'luxembourgish',\n", 105 | " 'mk': 'macedonian',\n", 106 | " 'mg': 'malagasy',\n", 107 | " 'ms': 'malay',\n", 108 | " 'ml': 'malayalam',\n", 109 | " 'mt': 'maltese',\n", 110 | " 'mi': 'maori',\n", 111 | " 'mr': 'marathi',\n", 112 | " 'mn': 'mongolian',\n", 113 | " 'my': 'myanmar (burmese)',\n", 114 | " 'ne': 'nepali',\n", 115 | " 'no': 'norwegian',\n", 116 | " 'or': 'odia',\n", 117 | " 'ps': 'pashto',\n", 118 | " 'fa': 'persian',\n", 119 | " 'pl': 'polish',\n", 120 | " 'pt': 'portuguese',\n", 121 | " 'pa': 'punjabi',\n", 122 | " 'ro': 'romanian',\n", 123 | " 'ru': 'russian',\n", 124 | " 'sm': 'samoan',\n", 125 | " 'gd': 'scots gaelic',\n", 126 | " 'sr': 'serbian',\n", 127 | " 'st': 'sesotho',\n", 128 | " 'sn': 'shona',\n", 129 | " 'sd': 'sindhi',\n", 130 | " 'si': 'sinhala',\n", 131 | " 'sk': 'slovak',\n", 132 | " 'sl': 'slovenian',\n", 133 | " 'so': 'somali',\n", 134 | " 'es': 'spanish',\n", 135 | " 'su': 'sundanese',\n", 136 | " 'sw': 'swahili',\n", 137 | " 'sv': 'swedish',\n", 138 | " 'tg': 'tajik',\n", 139 | " 'ta': 'tamil',\n", 140 | " 'te': 'telugu',\n", 141 | " 'th': 'thai',\n", 142 | " 'tr': 'turkish',\n", 143 | " 'uk': 'ukrainian',\n", 144 | " 'ur': 'urdu',\n", 145 | " 'ug': 'uyghur',\n", 146 | " 'uz': 'uzbek',\n", 147 | " 'vi': 'vietnamese',\n", 148 | " 'cy': 'welsh',\n", 149 | " 'xh': 'xhosa',\n", 150 | " 'yi': 'yiddish',\n", 151 | " 'yo': 'yoruba',\n", 152 | " 'zu': 'zulu'\n", 153 | "}" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "import speech_recognition as sr\n", 163 | "from googletrans import Translator\n", 164 | "from gtts import gTTS\n", 165 | "import os\n", 166 | "\n", 167 | "def listen_to_user():\n", 168 | " recognizer = sr.Recognizer()\n", 169 | "\n", 170 | " with sr.Microphone() as source:\n", 171 | " print(\"Please speak something...\")\n", 172 | " audio_data = recognizer.listen(source, timeout=5)\n", 173 | "\n", 174 | " try:\n", 175 | " print(\"Recognizing...\")\n", 176 | " user_input = recognizer.recognize_google(audio_data)\n", 177 | " print(\"You said:\", user_input)\n", 178 | " return user_input\n", 179 | " except sr.UnknownValueError:\n", 180 | " print(\"Sorry, I could not understand what you said.\")\n", 181 | " return None\n", 182 | " except sr.RequestError as e:\n", 183 | " print(\"Could not request results; {0}\".format(e))\n", 184 | " return None\n", 185 | "\n", 186 | "def translate_text(text, target_language):\n", 187 | " translator = Translator()\n", 188 | " translated_text = translator.translate(text, dest=target_language)\n", 189 | " return translated_text.text\n", 190 | "\n", 191 | "def speak_text(text, language):\n", 192 | " tts = gTTS(text=text, lang=language, slow=False)\n", 193 | " tts.save(\"translated_output.mp3\")\n", 194 | " os.system(\"translated_output.mp3\") # For Linux users, use os.system(\"mpg321 translated_output.mp3\"). For Windows, use os.system(\"translated_output.mp3\")\n", 195 | "\n", 196 | "def main():\n", 197 | " target_language = input(\"Enter the target language (e.g., 'fr' for French, 'es' for Spanish) (You can find the language code in the above code cell): \").lower()\n", 198 | " user_input = listen_to_user()\n", 199 | "\n", 200 | " if user_input:\n", 201 | " translated_text = translate_text(user_input, target_language)\n", 202 | " print(\"Translated text:\", translated_text)\n", 203 | " speak_text(translated_text, target_language)\n", 204 | "\n", 205 | "if __name__ == \"__main__\":\n", 206 | " main()\n" 207 | ] 208 | } 209 | ], 210 | "metadata": { 211 | "kernelspec": { 212 | "display_name": "Python 3", 213 | "language": "python", 214 | "name": "python3" 215 | }, 216 | "language_info": { 217 | "codemirror_mode": { 218 | "name": "ipython", 219 | "version": 3 220 | }, 221 | "file_extension": ".py", 222 | "mimetype": "text/x-python", 223 | "name": "python", 224 | "nbconvert_exporter": "python", 225 | "pygments_lexer": "ipython3", 226 | "version": "3.10.11" 227 | } 228 | }, 229 | "nbformat": 4, 230 | "nbformat_minor": 2 231 | } 232 | -------------------------------------------------------------------------------- /TurtleAnimations/CirclePattern.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | wn=turtle.Screen() 4 | turtle.bgcolor('white') 5 | turtle.color('red') 6 | turtle.shape('turtle') 7 | t5=turtle.Turtle() 8 | move=1 9 | 10 | ############################### 11 | t5.speed("fastest") 12 | for i in range(10): 13 | for i in range(4): 14 | t5.pu() 15 | t5.goto(500,200) 16 | t5.pd() 17 | t5.color('orange') 18 | t5.pensize(3) 19 | t5.circle(50,steps=4) 20 | t5.right(100) 21 | 22 | t5.speed("fastest") 23 | for i in range(6): 24 | for i in range(4): 25 | t5.pu() 26 | t5.goto(0,0) 27 | t5.pd() 28 | t5.color('red') 29 | t5.pensize(3) 30 | t5.circle(100,steps=6) 31 | t5.right(100) 32 | 33 | turtle.done() -------------------------------------------------------------------------------- /TurtleAnimations/DigitalClock.py: -------------------------------------------------------------------------------- 1 | import time 2 | import datetime as dt 3 | import turtle 4 | 5 | # create a turtle to display time 6 | t = turtle.Turtle() 7 | 8 | # create a turtle to create rectangle box 9 | t1 = turtle.Turtle() 10 | 11 | # create screen 12 | s = turtle.Screen() 13 | 14 | # set background color of the screen 15 | s.bgcolor("white") 16 | 17 | # obtain current hour, minute and second 18 | # from the system 19 | sec = dt.datetime.now().second 20 | min = dt.datetime.now().minute 21 | hr = dt.datetime.now().hour 22 | 23 | t1.pensize(3) 24 | t1.color('black') 25 | t1.penup() 26 | 27 | # set the position of turtle8 28 | t1.goto(-80, 0) 29 | t.goto(-60, 10) 30 | t1.pendown() 31 | t.pendown() 32 | 33 | # create rectangular box 34 | for i in range(2): 35 | t1.forward(200) 36 | t1.left(90) 37 | t1.forward(70) 38 | t1.left(90) 39 | 40 | # hide the turtle 41 | t1.hideturtle() 42 | 43 | while True: 44 | t.hideturtle() 45 | t.clear() 46 | # display the time 47 | t.write(str(hr).zfill(2) 48 | + ":"+str(min).zfill(2)+":" 49 | + str(sec).zfill(2), 50 | font=("Arial Narrow", 35, "bold")) 51 | time.sleep(1) 52 | sec += 1 53 | 54 | if sec == 60: 55 | sec = 0 56 | min += 1 57 | 58 | if min == 60: 59 | min = 0 60 | hr += 1 61 | 62 | if hr == 13: 63 | hr = 1 -------------------------------------------------------------------------------- /TurtleAnimations/IndianFlag.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | # Set up the turtle 4 | turtle.speed(30) 5 | turtle.bgcolor("white") 6 | turtle.title("Indian Flag") 7 | 8 | # Function to draw a rectangle 9 | def draw_rectangle(width, height, color): 10 | turtle.begin_fill() 11 | turtle.fillcolor(color) 12 | for _ in range(2): 13 | turtle.forward(width) 14 | turtle.right(90) 15 | turtle.forward(height) 16 | turtle.right(90) 17 | turtle.end_fill() 18 | 19 | 20 | # Draw the flag components 21 | def draw_indian_flag(): 22 | width = 900 23 | height = 600 24 | middle_rect_height = height / 3 25 | ashoka_chakra_diameter = middle_rect_height 26 | content_1 = -height / 2 + 650 # Position to write content 27 | content_2 = -height / 2 - 50 28 | 29 | # Draw saffron rectangle 30 | turtle.penup() 31 | turtle.goto(-width / 2, height / 2) 32 | turtle.pendown() 33 | draw_rectangle(width, middle_rect_height, "#FF9933") 34 | 35 | # Draw white rectangle 36 | turtle.penup() 37 | turtle.goto(-width / 2, middle_rect_height / 2) 38 | turtle.pendown() 39 | draw_rectangle(width, middle_rect_height, "white") 40 | 41 | # Draw green rectangle 42 | turtle.penup() 43 | turtle.goto(-width / 2, -middle_rect_height/2) 44 | turtle.pendown() 45 | draw_rectangle(width, middle_rect_height, "#138808") 46 | 47 | # Draw Ashoka Chakra 48 | turtle.pensize(5) 49 | turtle.penup() 50 | turtle.goto(0, -middle_rect_height/2) 51 | turtle.pendown() 52 | turtle.color("blue") 53 | turtle.circle(ashoka_chakra_diameter / 2) 54 | for _ in range(24): 55 | turtle.penup() 56 | turtle.goto(0, 0) 57 | turtle.pendown() 58 | turtle.forward(ashoka_chakra_diameter / 2) 59 | turtle.backward(ashoka_chakra_diameter / 20) 60 | turtle.penup() 61 | turtle.goto(0, 0) 62 | turtle.pendown() 63 | turtle.left(360 / 24) 64 | 65 | # Write content under the Chakra 66 | turtle.penup() 67 | turtle.goto(0, content_1) 68 | turtle.pendown() 69 | turtle.color("black") 70 | turtle.write("Happy 77th Independence Day", align="center", font=("Arial",45, "bold")) 71 | turtle.penup() 72 | turtle.goto(0, content_2) 73 | turtle.pendown() 74 | turtle.color("black") 75 | turtle.write("From Code to Canvas: Python Animation Magic - by pytech.academy ", align="center", font=("Arial", 20, "bold")) 76 | 77 | # Draw the Indian flag 78 | draw_indian_flag() 79 | 80 | # Hide the turtle 81 | turtle.hideturtle() 82 | 83 | # Keep the window open until it's closed by the user 84 | turtle.done() -------------------------------------------------------------------------------- /URL Shortner/url-shortner.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "pip install requests" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [ 17 | { 18 | "name": "stdout", 19 | "output_type": "stream", 20 | "text": [ 21 | "Shortened URL: https://bit.ly/3MeqmMR\n" 22 | ] 23 | } 24 | ], 25 | "source": [ 26 | "import requests\n", 27 | "\n", 28 | "# Your Bitly API credentials (replace with your own)\n", 29 | "BITLY_API_KEY = '*******************************'\n", 30 | "\n", 31 | "def shorten_url(long_url):\n", 32 | " try:\n", 33 | " # Bitly API endpoint for shortening a URL\n", 34 | " api_url = 'https://api-ssl.bitly.com/v4/shorten'\n", 35 | " headers = {\n", 36 | " 'Authorization': f'Bearer {BITLY_API_KEY}',\n", 37 | " 'Content-Type': 'application/json',\n", 38 | " }\n", 39 | " payload = {\n", 40 | " 'long_url': long_url,\n", 41 | " }\n", 42 | " \n", 43 | " response = requests.post(api_url, headers=headers, json=payload)\n", 44 | " response_data = response.json()\n", 45 | " \n", 46 | " if 'link' in response_data:\n", 47 | " return response_data['link']\n", 48 | " else:\n", 49 | " return \"URL shortening failed.\"\n", 50 | " except Exception as e:\n", 51 | " return f\"An error occurred: {str(e)}\"\n", 52 | "\n", 53 | "if __name__ == \"__main__\":\n", 54 | " url_to_shorten = input(\"Enter the URL you want to shorten: \")\n", 55 | " shortened_url = shorten_url(url_to_shorten)\n", 56 | " \n", 57 | " if shortened_url:\n", 58 | " print(\"Shortened URL:\", shortened_url)\n" 59 | ] 60 | } 61 | ], 62 | "metadata": { 63 | "kernelspec": { 64 | "display_name": "Python 3", 65 | "language": "python", 66 | "name": "python3" 67 | }, 68 | "language_info": { 69 | "codemirror_mode": { 70 | "name": "ipython", 71 | "version": 3 72 | }, 73 | "file_extension": ".py", 74 | "mimetype": "text/x-python", 75 | "name": "python", 76 | "nbconvert_exporter": "python", 77 | "pygments_lexer": "ipython3", 78 | "version": "3.10.11" 79 | } 80 | }, 81 | "nbformat": 4, 82 | "nbformat_minor": 2 83 | } 84 | -------------------------------------------------------------------------------- /URL-Validator/url_validator.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlparse 2 | import requests 3 | 4 | def url_validator(x): 5 | try: 6 | result = urlparse(x) 7 | return all([result.scheme and result.netloc]) 8 | except: 9 | return False 10 | 11 | def url_functional(url): 12 | try: 13 | response = requests.head(url) 14 | if response.status_code < 400: 15 | return True 16 | 17 | except: 18 | return False 19 | 20 | 21 | if __name__ == "__main__": 22 | url = input("Please enter the URL to verify: ") 23 | if url_validator(url): 24 | print("URL Format is Valid") 25 | if url_functional(url): 26 | print("URL is Functional") 27 | else: 28 | print("URL is not functional") 29 | else: 30 | print("URL format is Invalid") 31 | -------------------------------------------------------------------------------- /Voice to text/Readme.md: -------------------------------------------------------------------------------- 1 | # Voice to Text Converter 2 | 3 | This Python script allows you to convert audio files (in WAV or MP3 format) into text using speech recognition. You can also have the converted text spoken aloud. 4 | 5 | ## Features 6 | 7 | - Convert audio files to text. 8 | - Listen to the converted text using text-to-speech (TTS). 9 | 10 | ## Prerequisites 11 | 12 | Before running the script, you need to install the required Python packages. You can install them using `pip`: 13 | 14 | ```bash 15 | pip install pyttsx3 speech_recognition 16 | -------------------------------------------------------------------------------- /Voice to text/voice_to_text.py: -------------------------------------------------------------------------------- 1 | import os 2 | import tkinter as tk 3 | from tkinter import filedialog, messagebox 4 | import pyttsx3 5 | import speech_recognition as sr 6 | 7 | # Function to convert voice to text 8 | def convert_voice_to_text(audio_file_path): 9 | recognizer = sr.Recognizer() 10 | with sr.AudioFile(audio_file_path) as source: 11 | try: 12 | audio = recognizer.record(source) 13 | return recognizer.recognize_google(audio) 14 | except sr.UnknownValueError: 15 | return "Couldn't understand the audio." 16 | except sr.RequestError: 17 | return "Couldn't request results; check your network connection." 18 | 19 | # Function to process voice note 20 | def process_voice_note(): 21 | if not os.path.exists("voice_notes"): 22 | os.makedirs("voice_notes") 23 | 24 | audio_file_path = filedialog.askopenfilename(filetypes=[("Audio Files", "*.wav;*.mp3")]) 25 | 26 | if not os.path.isfile(audio_file_path): 27 | messagebox.showerror("Error", "File not found. Please provide a valid file path.") 28 | return 29 | 30 | text = convert_voice_to_text(audio_file_path) 31 | 32 | text_output.config(state=tk.NORMAL) 33 | text_output.delete(1.0, tk.END) 34 | text_output.insert(tk.END, text) 35 | text_output.config(state=tk.DISABLED) 36 | 37 | # Function to speak text 38 | def speak_text(): 39 | text = text_output.get(1.0, tk.END) 40 | engine = pyttsx3.init() 41 | engine.say(text) 42 | engine.runAndWait() 43 | 44 | # Create the main window 45 | root = tk.Tk() 46 | root.title("Voice to Text Converter") 47 | root.geometry("400x300") 48 | 49 | # Load a custom font (replace with your font file) 50 | custom_font = ("Helvetica", 14) 51 | 52 | # Create GUI elements with improved design 53 | title_label = tk.Label(root, text="Voice to Text Converter", font=("Helvetica", 20), padx=10, pady=10) 54 | process_button = tk.Button(root, text="Process Voice Note", command=process_voice_note, font=custom_font, bg="green", fg="white") 55 | speak_button = tk.Button(root, text="Speak Text", command=speak_text, font=custom_font, bg="blue", fg="white") 56 | text_output = tk.Text(root, wrap=tk.WORD, state=tk.DISABLED, font=custom_font, bg="lightgray", padx=10, pady=10) 57 | 58 | # Place GUI elements using grid layout 59 | title_label.grid(row=0, column=0, columnspan=2) 60 | process_button.grid(row=1, column=0, padx=10, pady=10) 61 | speak_button.grid(row=1, column=1, padx=10, pady=10) 62 | text_output.grid(row=2, column=0, columnspan=2, padx=10, pady=10) 63 | 64 | # Start the GUI main loop 65 | root.mainloop() 66 | -------------------------------------------------------------------------------- /Wallpaper/wallpaper_changer.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import time 4 | import random 5 | import requests 6 | 7 | 8 | ACCESS_KEY = 'dV0tx-EbdJDZPxSbTob2cyIlzYj5aVEbs4fA4yFVHgs' 9 | QUERY = 'nature' 10 | 11 | IMAGE_DIR = 'wallpapers' 12 | 13 | def download_random_image(): 14 | url = f'https://api.unsplash.com/photos/random?client_id={ACCESS_KEY}&query={QUERY}' 15 | response = requests.get(url) 16 | if response.status_code == 200: 17 | image_data = response.json() 18 | image_url = image_data['urls']['full'] 19 | image_filename = os.path.join(IMAGE_DIR, f'wallpaper_{time.time()}.jpg') 20 | with open(image_filename, 'wb') as image_file: 21 | image_file.write(requests.get(image_url).content) 22 | return image_filename 23 | 24 | def set_wallpaper(image_path): 25 | import ctypes 26 | SPI_SETDESKWALLPAPER = 20 27 | ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, image_path, 3) 28 | 29 | os.makedirs(IMAGE_DIR, exist_ok=True) 30 | 31 | 32 | interval_minutes = 10 33 | interval_seconds = interval_minutes * 60 34 | 35 | while True: 36 | try: 37 | image_path = download_random_image() 38 | set_wallpaper(image_path) 39 | print(f'Wallpaper changed to {image_path}') 40 | time.sleep(interval_seconds) 41 | except Exception as e: 42 | print(f'An error occurred: {str(e)}') 43 | continue 44 | # run the script by pip install requests pywin32 -------------------------------------------------------------------------------- /Weather app/Readme.md: -------------------------------------------------------------------------------- 1 | # Command-Line Weather App 2 | 3 | This is a simple command-line weather app built in Python. It allows you to fetch and display weather information for a specific city using the OpenWeatherMap API. 4 | 5 | ## Features 6 | 7 | - Get weather data including description, temperature, humidity, and wind speed for a given city. 8 | - The app uses metric units by default, but you can easily switch to imperial units for temperature (°F). 9 | 10 | ## Prerequisites 11 | 12 | Before using this app, you need to sign up for a free API key from OpenWeatherMap. You can obtain your API key here: [OpenWeatherMap API](https://openweathermap.org/api). 13 | 14 | ## Example 15 | 16 | Enter city name: New York 17 | Weather in New York: 18 | Description: Clear sky 19 | Temperature: 20.85°C 20 | Humidity: 68% 21 | Wind Speed: 2.68 m/s 22 | -------------------------------------------------------------------------------- /Weather app/main.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | def get_weather(api_key, city): 5 | base_url = "http://api.openweathermap.org/data/2.5/weather" 6 | params = { 7 | "q": city, 8 | "appid": api_key, 9 | "units": "metric" # You can change this to "imperial" for Fahrenheit 10 | } 11 | 12 | response = requests.get(base_url, params=params) 13 | 14 | if response.status_code == 200: 15 | data = response.json() 16 | return data 17 | else: 18 | return None 19 | 20 | def main(): 21 | api_key = "49762d02afb569bad642ebb28c4a4d31" # Replace with your OpenWeatherMap API key 22 | city = input("Enter city name: ") 23 | 24 | weather_data = get_weather(api_key, city) 25 | 26 | if weather_data: 27 | print(f"Weather in {city}:") 28 | print(f"Description: {weather_data['weather'][0]['description']}") 29 | print(f"Temperature: {weather_data['main']['temp']}°C") 30 | print(f"Humidity: {weather_data['main']['humidity']}%") 31 | print(f"Wind Speed: {weather_data['wind']['speed']} m/s") 32 | else: 33 | print("Weather data not found. Please check the city name or try again later.") 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /Weather/weather.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "pip install requests pillow tk" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 3, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import requests\n", 19 | "from PIL import Image, ImageTk\n", 20 | "import tkinter as tk\n", 21 | "from tkinter import messagebox\n", 22 | "\n", 23 | "API_KEY = 'YOUR_API_KEY'\n", 24 | "\n", 25 | "def get_weather(city):\n", 26 | " url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}'\n", 27 | " response = requests.get(url)\n", 28 | " data = response.json()\n", 29 | " return data\n", 30 | "\n", 31 | "def show_weather():\n", 32 | " city = city_entry.get()\n", 33 | " try:\n", 34 | " weather_data = get_weather(city)\n", 35 | " temperature = weather_data['main']['temp'] - 273.15 # Convert temperature from Kelvin to Celsius\n", 36 | " description = weather_data['weather'][0]['description'].capitalize()\n", 37 | " icon_code = weather_data['weather'][0]['icon']\n", 38 | "\n", 39 | " weather_icon_url = f\"http://openweathermap.org/img/w/{icon_code}.png\"\n", 40 | " icon_response = requests.get(weather_icon_url, stream=True)\n", 41 | " icon_image = Image.open(icon_response.raw).resize((150, 150))\n", 42 | " icon_photo = ImageTk.PhotoImage(icon_image)\n", 43 | "\n", 44 | " icon_label.config(image=icon_photo)\n", 45 | " icon_label.image = icon_photo\n", 46 | " result_label.config(text=f'Temperature: {temperature:.2f}°C\\nDescription: {description}', font=(\"Helvetica\", 16))\n", 47 | " except Exception as e:\n", 48 | " messagebox.showerror('Error', f'Could not fetch weather data for {city}.')\n", 49 | "\n", 50 | "# GUI Setup\n", 51 | "root = tk.Tk()\n", 52 | "root.title(\"Weather App\")\n", 53 | "root.geometry(\"500x500\") # Set window size\n", 54 | "\n", 55 | "root.configure(bg=\"#3498db\") # Set background color\n", 56 | "\n", 57 | "city_label = tk.Label(root, text=\"Enter city:\", bg=\"#3498db\", fg=\"white\", font=(\"Helvetica\", 18))\n", 58 | "city_label.pack(pady=20)\n", 59 | "\n", 60 | "city_entry = tk.Entry(root, font=(\"Helvetica\", 16))\n", 61 | "city_entry.pack(pady=10)\n", 62 | "\n", 63 | "show_weather_button = tk.Button(root, text=\"Show Weather\", command=show_weather, font=(\"Helvetica\", 16))\n", 64 | "show_weather_button.pack(pady=20)\n", 65 | "\n", 66 | "icon_label = tk.Label(root, bg=\"#3498db\")\n", 67 | "icon_label.pack()\n", 68 | "\n", 69 | "result_label = tk.Label(root, text=\"\", bg=\"#3498db\", fg=\"white\", font=(\"Helvetica\", 16))\n", 70 | "result_label.pack(pady=20)\n", 71 | "\n", 72 | "root.mainloop()" 73 | ] 74 | } 75 | ], 76 | "metadata": { 77 | "kernelspec": { 78 | "display_name": "Python 3", 79 | "language": "python", 80 | "name": "python3" 81 | }, 82 | "language_info": { 83 | "codemirror_mode": { 84 | "name": "ipython", 85 | "version": 3 86 | }, 87 | "file_extension": ".py", 88 | "mimetype": "text/x-python", 89 | "name": "python", 90 | "nbconvert_exporter": "python", 91 | "pygments_lexer": "ipython3", 92 | "version": "3.8.10" 93 | } 94 | }, 95 | "nbformat": 4, 96 | "nbformat_minor": 2 97 | } 98 | -------------------------------------------------------------------------------- /Website_Blocker/website_blocker.py: -------------------------------------------------------------------------------- 1 | import time 2 | from datetime import datetime as dt 3 | 4 | # Windows host file path 5 | hostsPath = r"C:\Windows\System32\drivers\etc\hosts" 6 | redirect = "127.0.0.1" 7 | 8 | # Add the website you want to block, in this list 9 | websites = [ 10 | "www.amazon.in", "www.youtube.com", "youtube.com", "www.facebook.com", 11 | "facebook.com" 12 | ] 13 | while True: 14 | # Duration during which, website blocker will work 15 | if dt(dt.now().year, 16 | dt.now().month, 17 | dt.now().day, 9) < dt.now() < dt(dt.now().year, 18 | dt.now().month, 19 | dt.now().day, 18): 20 | print("Access denied to Website") 21 | with open(hostsPath, 'r+') as file: 22 | content = file.read() 23 | for site in websites: 24 | if site in content: 25 | pass 26 | else: 27 | file.write(redirect + " " + site + "\n") 28 | else: 29 | with open(hostsPath, 'r+') as file: 30 | content = file.readlines() 31 | file.seek(0) 32 | for line in content: 33 | if not any(site in line for site in websites): 34 | file.write(line) 35 | file.truncate() 36 | print("Allowed access!") 37 | time.sleep(5) -------------------------------------------------------------------------------- /Xlsx-Writer/README.md: -------------------------------------------------------------------------------- 1 | # Py-Xlsx ?? 2 | 3 | A Python script which allows you to create Excel spreadsheets with custom headers and data entry. It provides a simple way to organize and store data efficiently. 4 | 5 | ### Features 6 | 7 | - Define custom headers for your Excel spreadsheet. 8 | - Enter data interactively for each header. 9 | - Save the generated spreadsheet with a custom filename. 10 | 11 | ### Prerequisites 12 | 13 | Before you begin, ensure you have met the following requirements: 14 | 15 | - Python 3.11.5 16 | - openpyxl library 17 | 18 | ### How to Use 19 | 20 | 1. Clone this repository to your local machine. 21 | 2. Run the script in your Python environment. 22 | 3. Follow the prompts to enter header names, data, and specify the output filename. 23 | 4. The script will create an Excel file with your data. 24 | 25 | ### Usage 26 | 27 | ```bash 28 | pip install openpyxl 29 | ``` 30 | then 31 | ```bash 32 | python3 main.py 33 | ``` 34 | 35 | ### License 36 | 37 | This project is licensed under the [MIT LICENSE](LICENSE). 38 | 39 | ### Author 40 | 41 | [![Mohamed Rizad](https://github.com/riz4d.png?size=100)](https://github.com/riz4d) | 42 | ----| 43 | [Mohamed Rizad](https://t.me/riz4d) | 44 | Author, Base, Bug Fixes | 45 | -------------------------------------------------------------------------------- /Xlsx-Writer/main.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 ©Mohamed Rizad 2 | # 250923 @riz4d 3 | import openpyxl 4 | from modules.font import Font 5 | from modules.align import Alignment 6 | 7 | headers = [] 8 | output_file_id = input("Enter Output Filename : ") 9 | num_of_heads = int(input("Enter How many heads are you using ? ")) 10 | for i in range(num_of_heads): 11 | i+=1 12 | head_id=input(f"Enter Head {i} Name : ") 13 | headers.append(head_id) 14 | 15 | 16 | workbook = openpyxl.Workbook() 17 | sheet = workbook.active 18 | 19 | for col_num, header in enumerate(headers, 1): 20 | cell = sheet.cell(row=1, column=col_num) 21 | cell.value = header 22 | cell.font = Font(bold=True) 23 | 24 | for col_num in range(1, num_of_heads + 1): 25 | cell = sheet.cell(row=1, column=col_num) 26 | cell.alignment = Alignment(horizontal='center') 27 | lettr = ord('a') 28 | def enter_data(chacode,datalst): 29 | letterr = ord('a') 30 | next_row = sheet.max_row + 1 31 | for i in range(len(datalst)): 32 | charcode = chr(letterr).upper() 33 | sheet[f'{charcode}{next_row}'] = datalst[i] 34 | letterr+=1 35 | def datadbm(*data): 36 | charcode = chr(data[0]).upper() 37 | datadb = data[1] 38 | enter_data(charcode,datadb) 39 | print(datadb) 40 | 41 | i=0 42 | # 250923 @riz4d 43 | while True: 44 | i+=1 45 | dataset = [] 46 | for i in range(len(headers)): 47 | dat = input(f"Enter {headers[i]} : ") 48 | dataset.append(dat) 49 | datadbm(lettr,dataset) 50 | lettr+=1 51 | workbook.save(f'{output_file_id}.xlsx') 52 | -------------------------------------------------------------------------------- /Xlsx-Writer/modules/align.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2010-2023 openpyxl 2 | # 250923 @riz4d 3 | from openpyxl.compat import safe_string 4 | 5 | from openpyxl.descriptors import Bool, MinMax, Min, Alias, NoneSet 6 | from openpyxl.descriptors.serialisable import Serialisable 7 | 8 | 9 | horizontal_alignments = ( 10 | "general", "left", "center", "right", "fill", "justify", "centerContinuous", 11 | "distributed", ) 12 | vertical_aligments = ( 13 | "top", "center", "bottom", "justify", "distributed", 14 | ) 15 | 16 | class Alignment(Serialisable): 17 | """Alignment options for use in styles.""" 18 | 19 | tagname = "alignment" 20 | 21 | __fields__ = ('horizontal', 22 | 'vertical', 23 | 'textRotation', 24 | 'wrapText', 25 | 'shrinkToFit', 26 | 'indent', 27 | 'relativeIndent', 28 | 'justifyLastLine', 29 | 'readingOrder', 30 | ) 31 | horizontal = NoneSet(values=horizontal_alignments) 32 | vertical = NoneSet(values=vertical_aligments) 33 | textRotation = NoneSet(values=range(181)) 34 | textRotation.values.add(255) 35 | text_rotation = Alias('textRotation') 36 | wrapText = Bool(allow_none=True) 37 | wrap_text = Alias('wrapText') 38 | shrinkToFit = Bool(allow_none=True) 39 | shrink_to_fit = Alias('shrinkToFit') 40 | indent = MinMax(min=0, max=255) 41 | relativeIndent = MinMax(min=-255, max=255) 42 | justifyLastLine = Bool(allow_none=True) 43 | readingOrder = Min(min=0) 44 | 45 | def __init__(self, horizontal=None, vertical=None, 46 | textRotation=0, wrapText=None, shrinkToFit=None, indent=0, relativeIndent=0, 47 | justifyLastLine=None, readingOrder=0, text_rotation=None, 48 | wrap_text=None, shrink_to_fit=None, mergeCell=None): 49 | self.horizontal = horizontal 50 | self.vertical = vertical 51 | self.indent = indent 52 | self.relativeIndent = relativeIndent 53 | self.justifyLastLine = justifyLastLine 54 | self.readingOrder = readingOrder 55 | if text_rotation is not None: 56 | textRotation = text_rotation 57 | if textRotation is not None: 58 | self.textRotation = int(textRotation) 59 | if wrap_text is not None: 60 | wrapText = wrap_text 61 | self.wrapText = wrapText 62 | if shrink_to_fit is not None: 63 | shrinkToFit = shrink_to_fit 64 | self.shrinkToFit = shrinkToFit 65 | # mergeCell is vestigial 66 | 67 | 68 | def __iter__(self): 69 | for attr in self.__attrs__: 70 | value = getattr(self, attr) 71 | if value is not None and value != 0: 72 | yield attr, safe_string(value) 73 | -------------------------------------------------------------------------------- /Xlsx-Writer/modules/font.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2010-2023 openpyxl 2 | # 250923 @riz4d 3 | 4 | from openpyxl.descriptors import ( 5 | Alias, 6 | Sequence, 7 | Integer 8 | ) 9 | from openpyxl.descriptors.serialisable import Serialisable 10 | 11 | from openpyxl.descriptors.nested import ( 12 | NestedValue, 13 | NestedBool, 14 | NestedNoneSet, 15 | NestedMinMax, 16 | NestedString, 17 | NestedInteger, 18 | NestedFloat, 19 | ) 20 | from .colors import ColorDescriptor, Color, BLACK 21 | 22 | from openpyxl.compat import safe_string 23 | from openpyxl.xml.functions import Element, SubElement 24 | from openpyxl.xml.constants import SHEET_MAIN_NS 25 | 26 | 27 | def _no_value(tagname, value, namespace=None): 28 | if value: 29 | return Element(tagname, val=safe_string(value)) 30 | 31 | 32 | class Font(Serialisable): 33 | """Font options used in styles.""" 34 | 35 | UNDERLINE_DOUBLE = 'double' 36 | UNDERLINE_DOUBLE_ACCOUNTING = 'doubleAccounting' 37 | UNDERLINE_SINGLE = 'single' 38 | UNDERLINE_SINGLE_ACCOUNTING = 'singleAccounting' 39 | 40 | name = NestedString(allow_none=True) 41 | charset = NestedInteger(allow_none=True) 42 | family = NestedMinMax(min=0, max=14, allow_none=True) 43 | sz = NestedFloat(allow_none=True) 44 | size = Alias("sz") 45 | b = NestedBool(to_tree=_no_value) 46 | bold = Alias("b") 47 | i = NestedBool(to_tree=_no_value) 48 | italic = Alias("i") 49 | strike = NestedBool(allow_none=True) 50 | strikethrough = Alias("strike") 51 | outline = NestedBool(allow_none=True) 52 | shadow = NestedBool(allow_none=True) 53 | condense = NestedBool(allow_none=True) 54 | extend = NestedBool(allow_none=True) 55 | u = NestedNoneSet(values=('single', 'double', 'singleAccounting', 56 | 'doubleAccounting')) 57 | underline = Alias("u") 58 | vertAlign = NestedNoneSet(values=('superscript', 'subscript', 'baseline')) 59 | color = ColorDescriptor(allow_none=True) 60 | scheme = NestedNoneSet(values=("major", "minor")) 61 | 62 | tagname = "font" 63 | 64 | __elements__ = ('name', 'charset', 'family', 'b', 'i', 'strike', 'outline', 65 | 'shadow', 'condense', 'color', 'extend', 'sz', 'u', 'vertAlign', 66 | 'scheme') 67 | 68 | 69 | def __init__(self, name=None, sz=None, b=None, i=None, charset=None, 70 | u=None, strike=None, color=None, scheme=None, family=None, size=None, 71 | bold=None, italic=None, strikethrough=None, underline=None, 72 | vertAlign=None, outline=None, shadow=None, condense=None, 73 | extend=None): 74 | self.name = name 75 | self.family = family 76 | if size is not None: 77 | sz = size 78 | self.sz = sz 79 | if bold is not None: 80 | b = bold 81 | self.b = b 82 | if italic is not None: 83 | i = italic 84 | self.i = i 85 | if underline is not None: 86 | u = underline 87 | self.u = u 88 | if strikethrough is not None: 89 | strike = strikethrough 90 | self.strike = strike 91 | self.color = color 92 | self.vertAlign = vertAlign 93 | self.charset = charset 94 | self.outline = outline 95 | self.shadow = shadow 96 | self.condense = condense 97 | self.extend = extend 98 | self.scheme = scheme 99 | 100 | 101 | @classmethod 102 | def from_tree(cls, node): 103 | """ 104 | Set default value for underline if child element is present 105 | """ 106 | underline = node.find("{%s}u" % SHEET_MAIN_NS) 107 | if underline is not None and underline.get('val') is None: 108 | underline.set("val", "single") 109 | return super(Font, cls).from_tree(node) 110 | 111 | 112 | DEFAULT_FONT = Font(name="Calibri", sz=11, family=2, b=False, i=False, 113 | color=Color(theme=1), scheme="minor") 114 | -------------------------------------------------------------------------------- /anagram.py: -------------------------------------------------------------------------------- 1 | def anagrams(word): 2 | if len(word)<2: 3 | yield word 4 | else: 5 | for i,letter in enumerate(word): 6 | if not letter in word[:i]: 7 | for j in anagrams(word[:i]+word[i+1:]): 8 | yield j+letter 9 | if __name__=="__main__": 10 | for i in anagrams("acbcddd"): 11 | print (i) -------------------------------------------------------------------------------- /concurrent-file-processing/README.md: -------------------------------------------------------------------------------- 1 | # Concurrent File Processor 2 | 3 | This Python program reads a large file and processes its content concurrently using threads. Each line is passed to worker threads for processing. 4 | 5 | ## Usage 6 | 7 | 1. Place the large file you want to process in the same directory as this script. 8 | 9 | 2. Open a terminal and navigate to the directory containing the script and the large file. 10 | 11 | 3. Run the script using Python: 12 | 13 | ```bash 14 | python concurrent_processor.py 15 | -------------------------------------------------------------------------------- /concurrent-file-processing/concurrent-file-processing.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | def process_line(line): 4 | result = line.upper() 5 | return result 6 | 7 | def process_file(filename, start, end): 8 | with open(filename, 'r') as file: 9 | for i, line in enumerate(file): 10 | if start <= i < end: 11 | result = process_line(line.strip()) 12 | print(result) 13 | 14 | def main(filename, num_threads): 15 | with open(filename, 'r') as file: 16 | total_lines = sum(1 for _ in file) 17 | 18 | lines_per_thread = total_lines // num_threads 19 | 20 | threads = [] 21 | for i in range(num_threads): 22 | start = i * lines_per_thread 23 | end = (i + 1) * lines_per_thread if i != num_threads - 1 else total_lines 24 | thread = threading.Thread(target=process_file, args=(filename, start, end)) 25 | threads.append(thread) 26 | thread.start() 27 | 28 | for thread in threads: 29 | thread.join() 30 | 31 | if __name__ == "__main__": 32 | filename = "large_file.txt" 33 | num_threads = 4 34 | 35 | main(filename, num_threads) 36 | -------------------------------------------------------------------------------- /concurrent-file-processing/large_file.txt: -------------------------------------------------------------------------------- 1 | Line 1 2 | Line 2 3 | Line 3 4 | Line 4 5 | Line 5 6 | Line 6 7 | Line 7 8 | Line 8 9 | Line 9 10 | Line 10 11 | -------------------------------------------------------------------------------- /desktop-notifier-task/desktop-notifier-task.py: -------------------------------------------------------------------------------- 1 | from plyer import notification 2 | import time 3 | 4 | def desktop_notifier(title, message, timeout): 5 | notification.notify( 6 | title = title, 7 | message = message, 8 | app_name = 'Task Notifier', 9 | timeout = timeout, # Added timeout parameter 10 | ) 11 | 12 | if __name__ == "__main__": 13 | task_title = "Complete Task" 14 | task_message = "Don't forget to complete the specific task!" 15 | notification_timeout = 10 # Set the notification timeout in seconds 16 | 17 | desktop_notifier(task_title, task_message, notification_timeout) 18 | -------------------------------------------------------------------------------- /fibonacci-generation/fibonacci-generation.py: -------------------------------------------------------------------------------- 1 | def fibonacci_iterative(n): 2 | if n <= 1: 3 | return n 4 | 5 | fib = [0, 1] 6 | for i in range(2, n+1): 7 | fib.append(fib[i-1] + fib[i-2]) 8 | 9 | return fib[n] 10 | -------------------------------------------------------------------------------- /hangman/__pycache__/words.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/hangman/__pycache__/words.cpython-310.pyc -------------------------------------------------------------------------------- /hangman/hangman_cli.py: -------------------------------------------------------------------------------- 1 | import random 2 | from words import word_list 3 | 4 | # Hangman Game 5 | def display_hangman(tries): 6 | stages = [ 7 | """ 8 | -------- 9 | | | 10 | | O 11 | | \\|/ 12 | | | 13 | | / \\ 14 | - 15 | """, 16 | 17 | """ 18 | -------- 19 | | | 20 | | O 21 | | \\|/ 22 | | | 23 | | / 24 | - 25 | """, 26 | 27 | """ 28 | -------- 29 | | | 30 | | O 31 | | \\|/ 32 | | | 33 | | 34 | - 35 | """, 36 | 37 | """ 38 | -------- 39 | | | 40 | | O 41 | | \\| 42 | | | 43 | | 44 | - 45 | """, 46 | 47 | """ 48 | -------- 49 | | | 50 | | O 51 | | | 52 | | | 53 | | 54 | - 55 | """, 56 | 57 | """ 58 | -------- 59 | | | 60 | | O 61 | | 62 | | 63 | | 64 | - 65 | """, 66 | 67 | """ 68 | -------- 69 | | | 70 | | 71 | | 72 | | 73 | | 74 | - 75 | """ 76 | ] 77 | return stages[tries] 78 | 79 | # Function to get a random word from the list of words 80 | def get_word(): 81 | word = random.choice(word_list) 82 | return word.upper() 83 | 84 | # Function to play the game 85 | def play(word): 86 | 87 | word_completion = "_" * len(word) 88 | guessed = False 89 | guessed_letters = [] 90 | guessed_words = [] 91 | tries = 6 92 | 93 | print("Hangman Game Begins !!!") 94 | print(display_hangman(tries)) 95 | print(word_completion) 96 | print("\n") 97 | 98 | 99 | while (not guessed and tries > 0): 100 | 101 | guess = input("Please guess a letter or word: ").upper() 102 | 103 | 104 | if len(guess) == 1 and guess.isalpha(): 105 | 106 | if guess in guessed_letters: 107 | print("You already guessed the letter", guess) 108 | 109 | elif guess not in word: 110 | print(guess, "is not in the word.") 111 | tries -= 1 112 | guessed_letters.append(guess) 113 | 114 | 115 | else: 116 | print("Good job,", guess, "is in the word!") 117 | 118 | guessed_letters.append(guess) 119 | 120 | word_as_list = list(word_completion) 121 | 122 | indices = [i for i, letter in enumerate(word) if letter == guess] 123 | 124 | for index in indices: 125 | word_as_list[index] = guess 126 | 127 | word_completion = "".join(word_as_list) 128 | 129 | if "_" not in word_completion: 130 | guessed = True 131 | 132 | elif len(guess) == len(word) and guess.isalpha(): 133 | 134 | if guess in guessed_words: 135 | print("You already guessed the word", guess) 136 | 137 | elif guess != word: 138 | print(guess, "is not the word.") 139 | tries -= 1 140 | guessed_words.append(guess) 141 | 142 | else: 143 | guessed = True 144 | word_completion = word 145 | 146 | else: 147 | print("Not a valid guess.") 148 | 149 | print(display_hangman(tries)) 150 | print(word_completion) 151 | print("\n") 152 | 153 | if guessed: 154 | print("Congrats, you guessed the word! You win!") 155 | else: 156 | print("Sorry, you ran out of tries. The word was " + word + ". Maybe next time!") 157 | 158 | 159 | 160 | 161 | 162 | def main(): 163 | word = get_word() 164 | play(word) 165 | while input("Play Again? (Y/N) ").upper() == "Y": 166 | word = get_word() 167 | play(word) 168 | 169 | 170 | if __name__ == "__main__": 171 | main() -------------------------------------------------------------------------------- /hangman/words.py: -------------------------------------------------------------------------------- 1 | word_list = [ 2 | "apple", "banana", "cat", "dog", "elephant", "fish", "grape", "hat", "ice cream", "jacket", 3 | "kite", "lion", "monkey", "noodle", "orange", "penguin", "queen", "rabbit", "snake", "tiger", 4 | "umbrella", "violin", "watermelon", "xylophone", "yogurt", "zebra", "airplane", "basketball", "car", "duck", 5 | "eagle", "frog", "guitar", "hamburger", "ice", "jellyfish", "kangaroo", "lemon", "mango", "ninja", 6 | "octopus", "parrot", "quokka", "raccoon", "strawberry", "toucan", "unicorn", "volcano", "whale", "xylophone", 7 | "yacht", "zeppelin", "ant", "bear", "camel", "dolphin", "elephant", "flamingo", "giraffe", "hedgehog", 8 | "iguana", "jaguar", "koala", "lemur", "meerkat", "narwhal", "octopus", "panda", "quokka", "rhinoceros", 9 | "sloth", "toucan", "urutu", "vampire", "walrus", "x-ray fish", "yak", "zebra", "apple", "banana", 10 | "carrot", "date", "eggplant", "fig", "grape", "honeydew", "kiwi", "lemon", "mango", "nectarine", 11 | "orange", "peach", "quince", "raspberry", "strawberry", "tomato", "watermelon", "avocado", "broccoli", "cabbage", 12 | "cucumber", "egg", "lettuce", "onion", "pepper", "spinach", "zucchini", "blueberry", "cherry", "coconut", 13 | "dragonfruit", "elderberry", "fennel", "grapefruit", "honey", "jackfruit", "kiwifruit", "lime", "mulberry", "nutmeg", 14 | "olive", "papaya", "quinoa", "radish", "starfruit", "tangerine", "uva", "vanilla", "watercress", "xigua", 15 | "yam", "zucchini", "almond", "blackberry", "cantaloupe", "date", "elderberry", "fig", "grape", "honeydew", 16 | "ice cream", "jicama", "kale", "leek", "mango", "nectarine", "olive", "pepper", "quince", "rhubarb", 17 | "spinach", "tangerine", "umeboshi", "vanilla", "watermelon", "xigua", "yogurt", "zucchini", "avocado", "blueberry", 18 | "cantaloupe", "date", "elderberry", "fig", "grape", "honeydew", "ice cream", "jicama", "kale", "leek", 19 | "mango", "nectarine", "olive", "pepper", "quince", "rhubarb", "spinach", "tangerine", "umeboshi", "vanilla", 20 | "watermelon", "xigua", "yogurt", "zucchini", "avocado", "blueberry", "cantaloupe", "date", "elderberry", "fig", 21 | "grape", "honeydew", "ice cream", "jicama", "kale", "leek", "mango", "nectarine", "olive", "pepper", "quince", 22 | "rhubarb", "spinach", "tangerine", "umeboshi", "vanilla", "watermelon", "xigua", "yogurt", "zucchini", 23 | ] 24 | 25 | 26 | -------------------------------------------------------------------------------- /image-gallery/image.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "pip install tk pillow" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 5, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "import os\n", 19 | "from tkinter import *\n", 20 | "from PIL import Image, ImageTk\n", 21 | "from tkinter import filedialog\n", 22 | "\n", 23 | "def load_images(directory):\n", 24 | " image_files = [file for file in os.listdir(directory) if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]\n", 25 | " images = []\n", 26 | " for file in image_files:\n", 27 | " image_path = os.path.join(directory, file)\n", 28 | " original_image = Image.open(image_path)\n", 29 | " # Resize the image to fit the window\n", 30 | " resized_image = original_image.resize((700, 700))\n", 31 | " image = ImageTk.PhotoImage(resized_image)\n", 32 | " images.append(image)\n", 33 | " return images\n", 34 | "\n", 35 | "def forward(img_no):\n", 36 | " global label\n", 37 | " global button_forward\n", 38 | " global button_back\n", 39 | " global button_exit\n", 40 | " label.grid_forget()\n", 41 | " label = Label(image=image_list[img_no-1])\n", 42 | " label.grid(row=1, column=0, columnspan=3)\n", 43 | " button_back = Button(root, text=\"Back\", command=lambda: back(img_no-1), state=ACTIVE if img_no > 1 else DISABLED)\n", 44 | " button_forward = Button(root, text=\"Forward\", command=lambda: forward(img_no+1), state=ACTIVE if img_no < len(image_list) else DISABLED)\n", 45 | " button_back.grid(row=5, column=0)\n", 46 | " button_exit.grid(row=5, column=1)\n", 47 | " button_forward.grid(row=5, column=2)\n", 48 | "\n", 49 | "def back(img_no):\n", 50 | " global label\n", 51 | " global button_forward\n", 52 | " global button_back\n", 53 | " global button_exit\n", 54 | " label.grid_forget()\n", 55 | " label = Label(image=image_list[img_no-1])\n", 56 | " label.grid(row=1, column=0, columnspan=3)\n", 57 | " button_back = Button(root, text=\"Back\", command=lambda: back(img_no-1), state=ACTIVE if img_no > 1 else DISABLED)\n", 58 | " button_forward = Button(root, text=\"Forward\", command=lambda: forward(img_no+1), state=ACTIVE if img_no < len(image_list) else DISABLED)\n", 59 | " button_back.grid(row=5, column=0)\n", 60 | " button_exit.grid(row=5, column=1)\n", 61 | " button_forward.grid(row=5, column=2)\n", 62 | "\n", 63 | "def exit_viewer():\n", 64 | " root.destroy()\n", 65 | "\n", 66 | "root = Tk()\n", 67 | "root.title(\"Image Viewer\")\n", 68 | "root.geometry(\"700x750\")\n", 69 | "\n", 70 | "# Ask user for the image directory\n", 71 | "image_directory = filedialog.askdirectory()\n", 72 | "\n", 73 | "image_list = load_images(image_directory)\n", 74 | "label = Label(image=image_list[0])\n", 75 | "label.grid(row=1, column=0, columnspan=3)\n", 76 | "\n", 77 | "button_back = Button(root, text=\"Back\", command=lambda: back(0), state=DISABLED)\n", 78 | "button_exit = Button(root, text=\"Exit\", command=lambda: exit_viewer())\n", 79 | "button_forward = Button(root, text=\"Forward\", command=lambda: forward(1), state=ACTIVE if len(image_list) > 1 else DISABLED)\n", 80 | "\n", 81 | "button_back.grid(row=5, column=0)\n", 82 | "button_exit.grid(row=5, column=1)\n", 83 | "button_forward.grid(row=5, column=2)\n", 84 | "\n", 85 | "root.mainloop()\n" 86 | ] 87 | } 88 | ], 89 | "metadata": { 90 | "kernelspec": { 91 | "display_name": "Python 3", 92 | "language": "python", 93 | "name": "python3" 94 | }, 95 | "language_info": { 96 | "codemirror_mode": { 97 | "name": "ipython", 98 | "version": 3 99 | }, 100 | "file_extension": ".py", 101 | "mimetype": "text/x-python", 102 | "name": "python", 103 | "nbconvert_exporter": "python", 104 | "pygments_lexer": "ipython3", 105 | "version": "3.10.11" 106 | } 107 | }, 108 | "nbformat": 4, 109 | "nbformat_minor": 2 110 | } 111 | -------------------------------------------------------------------------------- /matrix-multiplication-parallel/matrix-multiplication-parallel.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import time 3 | from multiprocessing import Pool, cpu_count 4 | 5 | # Sequential matrix multiplication 6 | def sequential_matrix_multiplication(A, B): 7 | return np.dot(A, B) 8 | 9 | # Parallel matrix multiplication using multiprocessing.Pool 10 | def parallel_matrix_multiplication(args): 11 | A, B = args 12 | return np.dot(A, B) 13 | 14 | if __name__ == '__main__': 15 | # Generate random large matrices (you can replace these with your own matrices) 16 | size = 1000 # Adjust the size as needed 17 | A = np.random.rand(size, size) 18 | B = np.random.rand(size, size) 19 | 20 | # Sequential multiplication 21 | start_time = time.time() 22 | result_seq = sequential_matrix_multiplication(A, B) 23 | seq_time = time.time() - start_time 24 | 25 | # Parallel multiplication 26 | num_processes = cpu_count() # Number of available CPU cores 27 | pool = Pool(processes=num_processes) 28 | args_list = [(A, B)] * num_processes # Splitting the task for parallel processing 29 | start_time = time.time() 30 | results_parallel = pool.map(parallel_matrix_multiplication, args_list) 31 | pool.close() 32 | pool.join() 33 | result_parallel = sum(results_parallel) 34 | parallel_time = time.time() - start_time 35 | 36 | # Compare results 37 | assert np.allclose(result_seq, result_parallel) 38 | 39 | print(f"Sequential Multiplication Time: {seq_time} seconds") 40 | print(f"Parallel Multiplication Time: {parallel_time} seconds") 41 | -------------------------------------------------------------------------------- /parallel_processing_example/parallel_processing_example.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | 3 | # Define the function to process a chunk of data 4 | def process_chunk(chunk, result_queue): 5 | result = sum(x**2 for x in chunk) 6 | result_queue.put(result) 7 | 8 | # Define the main function 9 | def main(): 10 | # Generate a large dataset 11 | data = list(range(1, 100001)) # Example dataset of numbers from 1 to 100,000 12 | 13 | # Split the data into chunks (adjust chunk size as needed) 14 | chunk_size = len(data) // multiprocessing.cpu_count() 15 | chunks = [data[i:i+chunk_size] for i in range(0, len(data), chunk_size)] 16 | 17 | # Create a queue to store results 18 | result_queue = multiprocessing.Queue() 19 | 20 | # Create and start processes 21 | processes = [] 22 | for chunk in chunks: 23 | p = multiprocessing.Process(target=process_chunk, args=(chunk, result_queue)) 24 | processes.append(p) 25 | p.start() 26 | 27 | # Wait for all processes to finish 28 | for p in processes: 29 | p.join() 30 | 31 | # Aggregate results 32 | total_result = 0 33 | while not result_queue.empty(): 34 | total_result += result_queue.get() 35 | 36 | print(f'The sum of squares is: {total_result}') 37 | 38 | if __name__ == '__main__': 39 | main() 40 | -------------------------------------------------------------------------------- /passwordChecker/banned_passwords.txt: -------------------------------------------------------------------------------- 1 | P@ssw0rd 2 | Admin123 3 | Qwerty123 4 | Password123 5 | abc123 6 | 123456 7 | password 8 | 12345678 9 | qwerty 10 | 12345 11 | 123456789 12 | P@55w0rd 13 | Welcome1 14 | 11111 15 | abc123 16 | Football1 17 | Monkey1 18 | liverpool1 19 | princess1 20 | iloveyou 21 | adobe123 22 | photoshop 23 | p@ssw0rd1 24 | welcome123 25 | login 26 | princess 27 | master 28 | 123456789 29 | qwertyuiop 30 | solo 31 | passw0rd 32 | cookie 33 | starwars 34 | trustno1 35 | dragon 36 | pass1234 37 | baseball1 38 | letmein1 39 | master1 40 | monkey12 41 | mustang 42 | access14 43 | batman1 44 | passw0rd1 45 | genesis 46 | 654321 47 | superman1 48 | guitar1 49 | marina 50 | charlie1 51 | michelle1 52 | corvette 53 | Bigdog1 54 | cookie1 55 | natasha1 56 | rockstar 57 | freedom1 58 | muffin1 59 | fantasy1 60 | daniel1 61 | pepper1 62 | blowfish 63 | mercedes1 64 | success1 65 | butthead1 66 | pepper01 67 | 21122112 68 | aaron431 69 | 01012011 70 | manutd 71 | ginger01 72 | redsox1 73 | winter1 74 | tigger1 75 | Samantha1 76 | slayer1 77 | charmed1 78 | 007700 79 | 789456123 80 | password01 81 | thomas1 82 | cocacola1 83 | jp1989 84 | qazwsx1 85 | 7777777 86 | freddy 87 | nirvana1 88 | myspace1 89 | 123gas321 90 | passw0rd01 91 | sparky1 92 | bowling1 93 | minnie 94 | mickeymouse 95 | alabama1 96 | reallyme 97 | trustno1 98 | 69696969 99 | cooldude1 100 | red123 101 | dirtyharry 102 | harley1 103 | fuckyou1 104 | Internet1 105 | booboo1 106 | sample1 107 | 123abc 108 | blowjob 109 | lovers1 110 | 0987654321 111 | q1w2e3r4 112 | defender 113 | green1 114 | 98765432 115 | maverick1 116 | tintin 117 | poopoo1 118 | aaaaa1 119 | asdfghjkl 120 | bubbles1 121 | testing123 122 | darkness 123 | frankie 124 | scoobydoo 125 | passwords 126 | maximus 127 | malibu 128 | raphael 129 | drowssap1 130 | windows1 131 | paris1 132 | check123 133 | 321654987 134 | members 135 | aaaaaa1 136 | blasters 137 | bonded007 138 | williams 139 | titanic1 140 | master12 141 | cheyenne 142 | telecom 143 | lemons 144 | killer123 145 | marathon 146 | hhhhhh1 147 | eastern 148 | francis 149 | asdzxc 150 | homerun 151 | peewee 152 | junior1 153 | green123 154 | babygirl1 155 | spongebob1 156 | magicman 157 | isabel 158 | isabella 159 | angel123 160 | star1234 161 | james1 162 | apple123 163 | ncc1701e 164 | slapdragon 165 | butterfly1 166 | start123 167 | qwerasdf 168 | hannah1 169 | pass123 170 | pretty 171 | rolling 172 | rocknroll 173 | wizard1 174 | nathan1 175 | metallic@ 176 | 246810 177 | spitfire 178 | smashing 179 | bagpipes 180 | sandman1 181 | naughty 182 | nudes 183 | inspector 184 | kingkong 185 | gizmodo1 186 | FTPaccess21 187 | secret123 188 | brittany1 189 | 456258 190 | stargate 191 | fighter 192 | orange1 193 | passion1 194 | hottie1 195 | homepage 196 | angel12 197 | danger 198 | workerbee 199 | viper1 200 | magical 201 | dogface208 202 | jellybean 203 | poolshark 204 | 135790 205 | sexsex1 206 | bigrob 207 | charles1 208 | bookworm1 209 | tabasco 210 | eljefe 211 | remington1 212 | mypass1 213 | 7894561 214 | power123 215 | teens1 216 | secret12 217 | tinman 218 | trinity1 219 | cookie123 220 | perfect1 221 | service123 222 | star69 223 | slaves2B 224 | images1 225 | winston1 226 | solomon1 227 | kingpin 228 | holidays 229 | enternow 230 | alphas1 231 | spiderman1 232 | smooth1 233 | passthison 234 | private12 235 | crochet1 236 | appleseed 237 | snowdog 238 | tigger12 239 | momoney1 240 | fastcars1 241 | periodblood 242 | 007007 243 | cupojoe 244 | marshall1 245 | fireball1 246 | mymelody1 247 | summer12 -------------------------------------------------------------------------------- /passwordChecker/main.py: -------------------------------------------------------------------------------- 1 | from zxcvbn import zxcvbn 2 | 3 | import random 4 | import array 5 | 6 | 7 | #generating a strong password 8 | MAX_LEN = 12 9 | 10 | DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 11 | LOCASE_CHARACTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 12 | 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 13 | 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 14 | 'z'] 15 | 16 | UPCASE_CHARACTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 17 | 'I', 'J', 'K', 'M', 'N', 'O', 'P', 'Q', 18 | 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 19 | 'Z'] 20 | 21 | SYMBOLS = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', 22 | '*', '(', ')', '<'] 23 | 24 | # combines all the character arrays above to form one array 25 | COMBINED_LIST = DIGITS + UPCASE_CHARACTERS + LOCASE_CHARACTERS + SYMBOLS 26 | 27 | # randomly select at least one character from each character set above 28 | rand_digit = random.choice(DIGITS) 29 | rand_upper = random.choice(UPCASE_CHARACTERS) 30 | rand_lower = random.choice(LOCASE_CHARACTERS) 31 | rand_symbol = random.choice(SYMBOLS) 32 | 33 | 34 | temp_pass = rand_digit + rand_upper + rand_lower + rand_symbol 35 | 36 | for x in range(MAX_LEN - 4): 37 | temp_pass = temp_pass + random.choice(COMBINED_LIST) 38 | 39 | temp_pass_list = array.array('u', temp_pass) 40 | random.shuffle(temp_pass_list) 41 | 42 | 43 | password_g = "" 44 | for x in temp_pass_list: 45 | password_g= password_g + x 46 | 47 | 48 | # rating the password 49 | class Wordlist: 50 | _cache = {} 51 | 52 | def __init__(self, file_path): 53 | self.file_path = file_path 54 | self.words = self.load_wordlist() 55 | 56 | def load_wordlist(self): 57 | if self.file_path in self._cache: 58 | return self._cache[self.file_path] 59 | 60 | try: 61 | with open(self.file_path, 'r') as file: 62 | wordlist = [line.strip() for line in file] 63 | self._cache[self.file_path] = wordlist 64 | return wordlist 65 | except FileNotFoundError as e: 66 | raise FileNotFoundError(f"Error: File '{self.file_path}' not found.") from e 67 | except Exception as e: 68 | raise RuntimeError( 69 | f"Error loading wordlist from '{self.file_path}': {str(e)}" 70 | ) from e 71 | 72 | def is_word_in_list(self, word): 73 | return word in self.words 74 | 75 | 76 | class StrengthResult: 77 | def __init__(self, strength: str, score: int, message: str): 78 | self.strength = strength 79 | self.score = score 80 | self.message = message 81 | 82 | 83 | class PasswordStrength: 84 | def __init__(self, weak_wordlist_path: str = None, banned_wordlist_path: str = None): 85 | self.weak_wordlist = Wordlist(weak_wordlist_path) if weak_wordlist_path else None 86 | self.banned_wordlist = Wordlist(banned_wordlist_path) if banned_wordlist_path else None 87 | self.MIN_PASSWORD_LENGTH = 12 88 | 89 | def check_password_strength(self, password: str) -> StrengthResult: 90 | """ 91 | Check the strength of a password. 92 | 93 | Args: 94 | password: The password to check. 95 | 96 | Returns: 97 | A StrengthResult object containing the password strength, score, and a message. 98 | """ 99 | if len(password) < self.MIN_PASSWORD_LENGTH: 100 | return StrengthResult("\nToo short", 0, "Password should be at least 12 characters long.") 101 | 102 | if self.weak_wordlist and self.weak_wordlist.is_word_in_list(password): 103 | return StrengthResult("\nWeak", 0, "Password is commonly used and easily guessable.") 104 | 105 | password_strength = zxcvbn(password) 106 | score = password_strength["score"] 107 | 108 | if score >= 3: 109 | return StrengthResult("Strong", score, f"Password meets all the requirements. Score: {score}/4") 110 | suggestions = password_strength["feedback"]["suggestions"] 111 | return StrengthResult("Weak", score, f"Password is weak. Suggestions: {', '.join(suggestions)}") 112 | 113 | if __name__ == '__main__': 114 | while True: 115 | try: 116 | num_passwords = int(input("\nEnter the number of passwords to test (enter 0 to exit): ")) 117 | except ValueError: 118 | print("Error: Invalid input. Please enter a valid number.") 119 | continue 120 | 121 | if num_passwords == 0: 122 | print("Exiting the tool.") 123 | break 124 | 125 | try: 126 | weak_wordlist_path = input("\nEnter the path to the weak wordlist file (leave blank for default): ") 127 | banned_wordlist_path = input("Enter the path to the banned wordlist file (leave blank for default): ") 128 | 129 | password_strength_checker = PasswordStrength(weak_wordlist_path, banned_wordlist_path) 130 | except Exception as e: 131 | print(f"Error initializing PasswordStrength: {str(e)}") 132 | continue 133 | 134 | for _ in range(num_passwords): 135 | password = input("\nEnter a password: ") 136 | result = password_strength_checker.check_password_strength(password) 137 | print(f"{result.strength}: {result.message}") 138 | 139 | if result.strength == "Weak": 140 | print("Suggested strong password:", password_g) 141 | 142 | print("Thank you for using the Password Strength Checker.\n") -------------------------------------------------------------------------------- /passwordChecker/weak_passwords.txt: -------------------------------------------------------------------------------- 1 | 123456 2 | password 3 | 12345678 4 | qwerty 5 | 12345 6 | 123456789 7 | 1234567 8 | 111111 9 | 1234569 10 | iloveyou 11 | adobe123 12 | 123123 13 | admin 14 | 1234567890 15 | letmein 16 | photoshop 17 | 1234 18 | monkey 19 | shadow 20 | sunshine 21 | 1234567 22 | password1 23 | princess 24 | azerty 25 | trustno1 26 | 000000 27 | 1234556 28 | dragon 29 | baseball 30 | football 31 | welcome 32 | jesus 33 | password12 34 | 654321 35 | qwertyuiop 36 | solo 37 | cookie 38 | starwars 39 | passw0rd 40 | michael 41 | pokemon 42 | ninja 43 | zaq12wsx 44 | metallica 45 | charlie 46 | superman 47 | batman 48 | naruto 49 | access 50 | anthony 51 | pepper 52 | daniel 53 | 12345678910 54 | iloveyou! 55 | freedom 56 | whatever 57 | scooter 58 | purple 59 | orange 60 | snoopy 61 | lovely 62 | marina 63 | success 64 | blue 65 | magic 66 | winner 67 | peanut 68 | fantasia 69 | edward 70 | 8888888 71 | 01234 72 | pepper01 73 | aaron431 74 | password01 75 | thomas 76 | cocacola 77 | qazwsx 78 | 7777777 79 | myspace1 80 | password1 81 | computer 82 | michelle 83 | corvette 84 | Hello123 85 | youtube 86 | secret 87 | abcd1234 88 | summer 89 | internet 90 | asshole 91 | ginger 92 | princess1 93 | george 94 | cookie1 95 | cheese 96 | mickey 97 | tigger 98 | robert 99 | soccer 100 | boomer 101 | nfvgbh 102 | compaq 103 | gateway 104 | asa123 105 | batman1 106 | nanook 107 | slipknot 108 | frodo 109 | 0987654321 110 | q1w2e3r4 111 | peaches 112 | badboy 113 | power 114 | samantha 115 | misty 116 | jasmine 117 | mercedes 118 | steven 119 | dallas 120 | jessica 121 | guitar 122 | chelsea 123 | dexter 124 | amber 125 | danielle 126 | blink182 127 | mike 128 | toyota 129 | blowme 130 | asdfghjkl 131 | samsung 132 | dolphins 133 | elephant 134 | marlboro 135 | aaaaa1 136 | monica 137 | jimmy 138 | birdie 139 | crystal 140 | maverick 141 | catdog 142 | banana 143 | pookie 144 | kitty 145 | superfly 146 | amanda 147 | muffin 148 | redsox 149 | winter 150 | barbie 151 | william 152 | jonathan 153 | ginger01 154 | taylor 155 | pokemon1 156 | titanic 157 | angels 158 | jordan23 159 | michell1 160 | 4815162342 161 | drowssap 162 | samson 163 | jackson 164 | anime 165 | 123qwe 166 | fucking 167 | dakota 168 | fender1 169 | ncc1701d 170 | slayer 171 | cloud 172 | porn 173 | softball 174 | camaro 175 | mattie 176 | morgan 177 | harley 178 | ranger1 179 | 987654321 180 | phoenix 181 | jennifer 182 | ireland 183 | hockey 184 | corolla 185 | simpsons 186 | monster 187 | dave 188 | victoria 189 | red123 190 | 11111111111 191 | gunner 192 | helpme 193 | asswordp 194 | hottie 195 | money 196 | 123abc 197 | lovers 198 | 098765 199 | green 200 | 98765432 201 | maverick1 202 | braves 203 | welcome1 204 | 4444444 205 | liverpool 206 | poopoo 207 | shitty 208 | asdfgh 209 | happy123 210 | creative 211 | drowssap123 212 | admin123 213 | drive 214 | banana1 215 | testing 216 | legend 217 | jason1 218 | melissa 219 | brooklyn 220 | therock 221 | princessa 222 | coffee 223 | booboo 224 | kitten 225 | satan666 226 | mitchell 227 | lucky 228 | wildcard 229 | fucker 230 | dilbert1 231 | island 232 | butthead 233 | isabelle 234 | winnie 235 | casper 236 | richard 237 | bitches 238 | magnum 239 | chance 240 | bubbles 241 | testing12 242 | sexy 243 | maxwell 244 | killer 245 | maria123 246 | school 247 | pepper123 248 | xbox360 249 | galore 250 | maggie123 251 | sexsex 252 | bigdog 253 | beautiful 254 | minniemouse 255 | family 256 | hottie1 257 | trebor 258 | secret1 259 | penguin 260 | merlin 261 | veronica 262 | yankees1 263 | 987654321a 264 | matthew1 265 | ashley 266 | hello123 267 | elizabet 268 | school123 269 | captain 270 | shadow1 271 | master1 272 | 123456a 273 | qwertyu 274 | charlie1 275 | loveme 276 | football1 277 | loveyou 278 | 696969696 279 | explorer1 280 | christin 281 | q1w2e3 282 | sweet 283 | pokemon123 284 | qwerty123 285 | cocacola1 286 | compaq123 287 | tennis 288 | 9876543210 289 | midnight 290 | martin 291 | mickeymouse 292 | nintendo 293 | babygirl 294 | asd123 295 | college 296 | party 297 | love123 298 | lovely1 299 | 789456 300 | xxxxxx 301 | serenity 302 | passw0rd 303 | 0000d -------------------------------------------------------------------------------- /reverse-number-script/reverse_a_number.py: -------------------------------------------------------------------------------- 1 | def reverse_number(num): 2 | reversed_num = 0 3 | while num > 0: 4 | reversed_num = reversed_num * 10 + num % 10 5 | num = num // 10 6 | return reversed_num 7 | 8 | # Test the function 9 | input_num = int(input("Enter a number: ")) 10 | reversed_num = reverse_number(input_num) 11 | print(f"The reversed number is: {reversed_num}") 12 | -------------------------------------------------------------------------------- /snake-game/food.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | import random 3 | 4 | 5 | class Food(Turtle): 6 | def __init__(self): 7 | super().__init__() 8 | self.shape("circle") 9 | self.pu() 10 | self.shapesize(stretch_len=0.5, stretch_wid=0.5) 11 | self.color("orange") 12 | self.speed("fastest") 13 | self.refresh() 14 | 15 | def refresh(self): 16 | self.goto(random.randint(-280, 280), random.randint(-280, 280)) 17 | -------------------------------------------------------------------------------- /snake-game/main.py: -------------------------------------------------------------------------------- 1 | from turtle import Screen 2 | from snake import Snake 3 | import time 4 | from food import Food 5 | from scoreboard import ScoreBoard 6 | 7 | screen = Screen() 8 | screen.bgcolor("black") 9 | screen.setup(height=600, width=600) 10 | screen.title("My Snake Game") 11 | screen.tracer(0) 12 | 13 | snake = Snake() 14 | food = Food() 15 | scoreboard = ScoreBoard() 16 | 17 | screen.listen() 18 | screen.onkey(snake.up, "Up") 19 | screen.onkey(snake.down, "Down") 20 | screen.onkey(snake.left, "Left") 21 | screen.onkey(snake.right, "Right") 22 | 23 | has_ended = False 24 | while not has_ended: 25 | screen.update() 26 | time.sleep(0.1) 27 | 28 | snake.move() 29 | 30 | # Detect collision with food 31 | if snake.head.distance(food) < 15: 32 | food.refresh() 33 | snake.grow() 34 | scoreboard.add_score() 35 | 36 | # Detect collision with wall 37 | if snake.head.xcor() > 290 or snake.head.xcor() < -290 or snake.head.ycor() > 290 or snake.head.ycor() < -290: 38 | scoreboard.reset() 39 | snake.reset() 40 | 41 | # Detect collision with itself 42 | for tim in snake.tims[1:]: 43 | if snake.head.distance(tim) < 10: 44 | scoreboard.reset() 45 | snake.reset() 46 | 47 | screen.exitonclick() 48 | -------------------------------------------------------------------------------- /snake-game/scoreboard.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | import os 3 | 4 | ALIGNMENT = "center" 5 | FONT = ("Courier", 18, "normal") 6 | cwd = os.getcwd() 7 | 8 | class ScoreBoard(Turtle): 9 | def __init__(self): 10 | super().__init__() 11 | try: 12 | with open("./PythonScriptsHub/snake-game/data.txt", mode="r") as f: 13 | self.high_score = f.read() 14 | except FileNotFoundError: 15 | self.high_score = 0 16 | # print(os.path.join(cwd, "snake-game", "data.txt").replace("\\", "/")) 17 | self.score = 0 18 | self.color("white") 19 | self.pu() 20 | self.ht() 21 | self.goto(0, 270) 22 | self.update() 23 | 24 | def update(self): 25 | self.clear() 26 | self.write(f"Score: {self.score} High Score: {self.high_score}", align=ALIGNMENT, font=FONT) 27 | 28 | def add_score(self): 29 | self.score += 1 30 | self.update() 31 | 32 | def reset(self): 33 | if self.score > int(self.high_score): 34 | self.high_score = self.score 35 | with open("./PythonScriptsHub/snake-game/data.txt", mode="w") as f: 36 | f.write(str(self.high_score)) 37 | self.score = 0 38 | self.update() 39 | -------------------------------------------------------------------------------- /snake-game/snake.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | 3 | TIMS = [] 4 | MOVE_DISTANCE = 20 5 | RIGHT = 0 6 | UP = 90 7 | LEFT = 180 8 | DOWN = 270 9 | 10 | 11 | class Snake: 12 | def __init__(self): 13 | self.tims = TIMS 14 | self.create_snake() 15 | self.head = self.tims[0] 16 | 17 | def grow(self): 18 | self.tims.append(Turtle(shape="square")) 19 | self.tims[-1].pu() 20 | self.tims[-1].color("white") 21 | self.tims[-1].width(20) 22 | self.tims[-1].goto(self.tims[-2].xcor(), self.tims[-2].ycor()) 23 | 24 | def create_snake(self): 25 | for n in range(3): 26 | self.tims.append(Turtle(shape="square")) 27 | self.tims[n].pu() 28 | self.tims[n].color("white") 29 | self.tims[n].width(20) 30 | self.tims[n].goto(-n * 20, 0) 31 | 32 | def reset(self): 33 | for n in self.tims: 34 | n.goto(1000, 1000) 35 | TIMS.clear() 36 | self.tims = TIMS 37 | self.create_snake() 38 | self.head = self.tims[0] 39 | 40 | def move(self): 41 | for n in range(len(self.tims) - 1, 0, -1): 42 | self.tims[n].goto(self.tims[n - 1].xcor(), self.tims[n - 1].ycor()) 43 | self.head.forward(MOVE_DISTANCE) 44 | 45 | def up(self): 46 | if self.head.heading() != DOWN: 47 | self.head.setheading(UP) 48 | 49 | def down(self): 50 | if self.head.heading() != UP: 51 | self.head.setheading(DOWN) 52 | 53 | def left(self): 54 | if self.head.heading() != RIGHT: 55 | self.head.setheading(LEFT) 56 | 57 | def right(self): 58 | if self.head.heading() != LEFT: 59 | self.head.setheading(RIGHT) 60 | -------------------------------------------------------------------------------- /sort-algorithm-comparison/comparision.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | 4 | # Generate a random list of numbers 5 | arr = [random.randint(0, 10000) for _ in range(1000)] 6 | 7 | # Measure the execution time for Radix Sort 8 | start_time = time.time() 9 | radix_sort(arr.copy()) 10 | radix_sort_time = time.time() - start_time 11 | 12 | # Measure the execution time for Quicksort 13 | start_time = time.time() 14 | quicksort(arr.copy()) 15 | quicksort_time = time.time() - start_time 16 | 17 | print(f"Radix Sort Time: {radix_sort_time} seconds") 18 | print(f"Quicksort Time: {quicksort_time} seconds") 19 | -------------------------------------------------------------------------------- /sort-algorithm-comparison/quick-sort.py: -------------------------------------------------------------------------------- 1 | def quicksort(arr): 2 | if len(arr) <= 1: 3 | return arr 4 | pivot = arr[len(arr)//2] 5 | left = [x for x in arr if x < pivot] 6 | middle = [x for x in arr if x == pivot] 7 | right = [x for x in arr if x > pivot] 8 | return quicksort(left) + middle + quicksort(right) 9 | -------------------------------------------------------------------------------- /sort-algorithm-comparison/radix-sort.py: -------------------------------------------------------------------------------- 1 | def radix_sort(arr): 2 | # Find the maximum number to determine the number of digits 3 | max_num = max(arr) 4 | num_digits = len(str(max_num)) 5 | 6 | # Perform counting sort for each digit, starting from the least significant digit 7 | for i in range(num_digits): 8 | counting_sort(arr, i) 9 | 10 | def counting_sort(arr, digit): 11 | n = len(arr) 12 | output = [0] * n 13 | count = [0] * 10 14 | 15 | # Count the occurrences of each digit 16 | for i in range(n): 17 | index = arr[i] // 10**digit 18 | count[index % 10] += 1 19 | 20 | # Calculate cumulative count 21 | for i in range(1, 10): 22 | count[i] += count[i - 1] 23 | 24 | # Build the output array 25 | for i in range(n - 1, -1, -1): 26 | index = arr[i] // 10**digit 27 | output[count[index % 10] - 1] = arr[i] 28 | count[index % 10] -= 1 29 | 30 | # Copy the output array back to the original array 31 | for i in range(n): 32 | arr[i] = output[i] 33 | -------------------------------------------------------------------------------- /spark-data-transformation/spark-data-transformation.py: -------------------------------------------------------------------------------- 1 | from pyspark.sql import SparkSession 2 | from pyspark.sql.functions import col, expr 3 | 4 | # Initialize SparkSession 5 | spark = SparkSession.builder \ 6 | .appName("Complex Data Transformation") \ 7 | .getOrCreate() 8 | 9 | # Read CSV file (assuming the file has columns 'col1', 'col2', 'col3') 10 | input_path = "input.csv" 11 | df = spark.read.csv(input_path, header=True, inferSchema=True) 12 | 13 | # Perform Complex Transformation 14 | df_transformed = df \ 15 | .withColumn("new_col", col("col1") * 2) \ 16 | .withColumn("new_col2", expr("col2 + 10")) \ 17 | .filter(col("col3") > 5) 18 | 19 | # Write the result to a new CSV file 20 | output_path = "output.csv" 21 | df_transformed.write.csv(output_path, header=True, mode="overwrite") 22 | 23 | # Stop SparkSession 24 | spark.stop() 25 | -------------------------------------------------------------------------------- /sudoku-solver/__pycache__/generate_board.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/sudoku-solver/__pycache__/generate_board.cpython-310.pyc -------------------------------------------------------------------------------- /sudoku-solver/__pycache__/sudoku_lp.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/sudoku-solver/__pycache__/sudoku_lp.cpython-310.pyc -------------------------------------------------------------------------------- /sudoku-solver/example.py: -------------------------------------------------------------------------------- 1 | from sudoku_lp import SudokuSolver 2 | from generate_board import SudokuBoardGenerator 3 | 4 | 5 | 6 | # Example usage: 7 | generator = SudokuBoardGenerator() 8 | generator.fill_board() 9 | generator.remove_numbers(40) # Adjust the number as needed 10 | 11 | # Get the generated Sudoku puzzle as a matrix 12 | sudoku_puzzle = generator.get_board() 13 | 14 | # Print the puzzle 15 | for row in sudoku_puzzle: 16 | print(" ".join(str(num) if num != 0 else '0' for num in row)) 17 | 18 | # Solve the puzzle using your solver 19 | solver = SudokuSolver(sudoku_puzzle) 20 | if solver.solve(): 21 | print("\nSolved Sudoku:") 22 | solver.print_board() 23 | else: 24 | print("No solution exists") 25 | -------------------------------------------------------------------------------- /sudoku-solver/generate_board.py: -------------------------------------------------------------------------------- 1 | import random 2 | from sudoku_lp import SudokuSolver 3 | 4 | class SudokuBoardGenerator: 5 | def __init__(self): 6 | self.board = [[0] * 9 for _ in range(9)] 7 | self.solver = SudokuSolver(self.board) 8 | 9 | def fill_board(self): 10 | for i in range(0, 9, 3): 11 | nums = random.sample(range(1, 10), 9) 12 | k = 0 13 | for j in range(i, i + 3): 14 | self.board[j][i:i + 3] = nums[k:k + 3] 15 | k += 3 16 | self.solver.solve() 17 | 18 | def remove_numbers(self, count): 19 | for _ in range(count): 20 | row, col = random.randint(0, 8), random.randint(0, 8) 21 | while self.board[row][col] == 0: 22 | row, col = random.randint(0, 8), random.randint(0, 8) 23 | self.board[row][col] = 0 24 | 25 | def get_board(self): 26 | return [row[:] for row in self.board] 27 | 28 | 29 | -------------------------------------------------------------------------------- /sudoku-solver/main.py: -------------------------------------------------------------------------------- 1 | 2 | from generate_board import SudokuBoardGenerator 3 | from sudoku_lp import SudokuSolver 4 | def get_user_board(): 5 | print("Enter your Sudoku board as a 9x9 matrix. Use 0 for empty cells.") 6 | user_board = [] 7 | for _ in range(9): 8 | while True: 9 | try: 10 | row = list(map(int, input().split())) 11 | if len(row) != 9 or any(cell < 0 or cell > 9 for cell in row): 12 | raise ValueError 13 | user_board.append(row) 14 | break 15 | except ValueError: 16 | print("Invalid input. Please enter 9 numbers (0-9) separated by spaces.") 17 | return user_board 18 | 19 | def main(): 20 | print("Welcome to the Sudoku Solver!") 21 | input("Press any key to generate a random Sudoku board or type 'input' to enter your own board: ") 22 | 23 | if input().strip().lower() == 'input': 24 | sudoku_board = get_user_board() 25 | else: 26 | generator = SudokuBoardGenerator() 27 | generator.fill_board() 28 | generator.remove_numbers(40) # Adjust the number as needed 29 | sudoku_board = generator.get_board() 30 | 31 | print("\nSudoku Board:") 32 | for row in sudoku_board: 33 | print(" ".join(str(num) if num != 0 else '.' for num in row)) 34 | 35 | solver = SudokuSolver(sudoku_board) 36 | if solver.solve(): 37 | print("\nSolved Sudoku:") 38 | solver.print_board() 39 | else: 40 | print("No solution exists") 41 | 42 | if __name__ == "__main__": 43 | main() -------------------------------------------------------------------------------- /sudoku-solver/sudoku_lp.py: -------------------------------------------------------------------------------- 1 | class SudokuSolver: 2 | def __init__(self, board): 3 | self.board = board 4 | 5 | def print_board(self): 6 | for row in self.board: 7 | print(" ".join(str(num) if num != 0 else '.' for num in row)) 8 | 9 | def is_valid(self, row, col, num): 10 | # Check if the number is in the current row or column 11 | for i in range(9): 12 | if self.board[row][i] == num or self.board[i][col] == num: 13 | return False 14 | 15 | # Check if the number is in the current 3x3 grid 16 | start_row, start_col = 3 * (row // 3), 3 * (col // 3) 17 | for i in range(3): 18 | for j in range(3): 19 | if self.board[start_row + i][start_col + j] == num: 20 | return False 21 | 22 | return True 23 | 24 | def solve(self): 25 | for row in range(9): 26 | for col in range(9): 27 | if self.board[row][col] == 0: 28 | for num in range(1, 10): 29 | if self.is_valid(row, col, num): 30 | self.board[row][col] = num 31 | if self.solve(): 32 | return True 33 | self.board[row][col] = 0 34 | return False 35 | return True 36 | 37 | -------------------------------------------------------------------------------- /timer/main.py: -------------------------------------------------------------------------------- 1 | import time 2 | from tkinter import * 3 | from tkinter import messagebox 4 | 5 | # creating Tk window 6 | root = Tk() 7 | 8 | 9 | root.geometry("300x250") 10 | 11 | 12 | root.title("Time Counter") 13 | 14 | # Declaration of variables 15 | hour = StringVar() 16 | minute = StringVar() 17 | second = StringVar() 18 | 19 | # setting the default value as 0 20 | hour.set(" 00") 21 | minute.set(" 00") 22 | second.set(" 00") 23 | 24 | # Labels for hours, minutes, and seconds 25 | hour_label = Label(root, text="Hours", font=("Arial", 12)) 26 | hour_label.place(x=87, y=55) 27 | minute_label = Label(root, text="Minutes", font=("Arial", 12)) 28 | minute_label.place(x=141, y=55) 29 | second_label = Label(root, text="Seconds", font=("Arial", 12)) 30 | second_label.place(x=200, y=55) 31 | 32 | # Use of Entry class to take input from the user 33 | hourEntry = Entry(root, width=3, font=("Arial", 18, ""), textvariable=hour) 34 | hourEntry.place(x=83, y=20) 35 | 36 | minuteEntry = Entry(root, width=3, font=("Arial", 18, ""), textvariable=minute) 37 | minuteEntry.place(x=143, y=20) 38 | 39 | secondEntry = Entry(root, width=3, font=("Arial", 18, ""), textvariable=second) 40 | secondEntry.place(x=203, y=20) 41 | 42 | 43 | def submit(): 44 | try: 45 | 46 | temp = int(hour.get()) * 3600 + int(minute.get()) * 60 + int(second.get()) 47 | except ValueError: 48 | messagebox.showerror("Input Error", "Please input valid numbers") 49 | return 50 | 51 | while temp >= 0: 52 | 53 | mins, secs = divmod(temp, 60) 54 | 55 | hours = 0 56 | if mins > 60: 57 | 58 | hours, mins = divmod(mins, 60) 59 | 60 | 61 | hour.set(" {:02d}".format(hours)) 62 | minute.set(" {:02d}".format(mins)) 63 | second.set(" {:02d}".format(secs)) 64 | 65 | 66 | root.update() 67 | time.sleep(1) 68 | 69 | # when temp value = 0; then a messagebox pop's up 70 | # with a message:"Time's up" 71 | if temp == 0: 72 | messagebox.showinfo("Time Countdown", "Time's up") 73 | 74 | 75 | temp -= 1 76 | 77 | 78 | # button widget 79 | btn = Button(root, text='Start Countdown', bd='5', command=submit) 80 | btn.place(x=90, y=120) 81 | 82 | 83 | root.mainloop() -------------------------------------------------------------------------------- /weatherAppCLI/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hereisSwapnil/PythonScriptsHub/5c32dda520efa2a5f5aa82eabd6fffa1644b2e5a/weatherAppCLI/.DS_Store -------------------------------------------------------------------------------- /weatherAppCLI/README.md: -------------------------------------------------------------------------------- 1 | # Description 2 | This is a weather CLI app where real time weather information is showed. To use the app, you have to input the name of the city you want the information of, and it will generate the real time data using the OpenWeatherAPI. 3 | 4 | # Build 5 | ``` 6 | pip install -r requirements.txt 7 | ``` 8 | 9 | or 10 | 11 | ``` 12 | pip3 install -r requirements.txt 13 | ``` 14 | 15 | Then run, 16 | ``` 17 | python3 weatherAppCLI 18 | ``` 19 | 20 | -------------------------------------------------------------------------------- /weatherAppCLI/requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.8.4 2 | aiosignal==1.3.1 3 | async-timeout==4.0.3 4 | asyncio==3.4.3 5 | attrs==23.1.0 6 | charset-normalizer==3.3.0 7 | frozenlist==1.4.0 8 | idna==3.4 9 | multidict==6.0.4 10 | python-weather==1.0.3 11 | yarl==1.9.2 12 | -------------------------------------------------------------------------------- /weatherAppCLI/weatherAppCLI.py: -------------------------------------------------------------------------------- 1 | import python_weather 2 | import asyncio 3 | 4 | async def fetch_weather(city): 5 | async with python_weather.Client(unit=python_weather.METRIC) as client: 6 | weather = await client.get(city) 7 | return weather 8 | 9 | if __name__ == "__main__": 10 | city = input("Enter a city: ") 11 | loop = asyncio.get_event_loop() 12 | weather = loop.run_until_complete(fetch_weather(city)) 13 | 14 | print(f"=== Weather in {city} ===") 15 | print(f"Current Temperature: {weather.current.temperature}°C") 16 | print("") 17 | print(f"=== 3-Day Forecast ===") 18 | for forecast in weather.forecasts: # Taking only first 3 days for demonstration 19 | print(f"\nDate: {forecast.date}") 20 | print(f"Temperature: {forecast.temperature}°C") 21 | print(f"Moon Phase: {forecast.astronomy.moon_phase}") 22 | print(f"Sunrise: {forecast.astronomy.sun_rise}") 23 | print(f"Sunset: {forecast.astronomy.sun_set}") 24 | 25 | print("Hourly Forecast:") 26 | for hourly in forecast.hourly: # Taking only first 4 hours for demonstration 27 | print(f" {hourly.time}: {hourly.temperature}°C, {hourly.description}") 28 | 29 | -------------------------------------------------------------------------------- /word_definitions/read_me.txt: -------------------------------------------------------------------------------- 1 | This Python script allows you to look up the definitions of words using a free dictionary API. It provides word definitions, phonetic pronunciation, part of speech, and example sentences if available. 2 | 3 | --------------------------------------------------------------- 4 | 5 | Prerequisites 6 | Before using this script, ensure that you have the following prerequisites: 7 | 8 | 1)Python: You must have Python installed on your system. You can download it from python.org. 9 | 10 | 2)Required Python Libraries: You need to have the requests library installed. You can install it using pip: 11 | pip install requests 12 | 13 | --------------------------------------------------------------- 14 | 15 | Features 16 | The script provides the following features: 17 | 18 | 1)Look up word definitions from a free dictionary API. 19 | 2)Display the word's phonetic pronunciation (if available). 20 | 3)Show the part of speech for each definition. 21 | 4)Present example sentences for each definition (if available). 22 | 5)Graceful handling of errors and missing word entries. 23 | 24 | --------------------------------------------------------------- 25 | 26 | -------------------------------------------------------------------------------- /word_definitions/word_definition_and_meanings.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | def get_word_definition(word): 4 | base_url = 'https://api.dictionaryapi.dev/api/v2/entries/en' 5 | url = f"{base_url}/{word}" 6 | 7 | try: 8 | response = requests.get(url) 9 | data = response.json() 10 | 11 | if isinstance(data, list) and len(data) > 0: 12 | word_data = data[0] 13 | print(f"Word: {word_data['word']}") 14 | print(f"Phonetic: {word_data.get('phonetic', 'N/A')}") 15 | 16 | if 'meanings' in word_data: 17 | for meaning in word_data['meanings']: 18 | part_of_speech = meaning['partOfSpeech'] 19 | print(f"Part of Speech: {part_of_speech}") 20 | 21 | for definition in meaning['definitions']: 22 | print(f"Definition: {definition['definition']}") 23 | if 'example' in definition: 24 | print(f"Example: {definition['example']}") 25 | 26 | print() 27 | 28 | 29 | 30 | 31 | else: 32 | print("Word not found in the dictionary.") 33 | 34 | except requests.exceptions.RequestException as e: 35 | print(f"Error: {e}") 36 | 37 | 38 | print() 39 | print() 40 | print() 41 | 42 | 43 | if __name__ == "__main__": 44 | while True: 45 | word = input("Enter a word to look up (or type 'exit' to quit): ").strip().lower() 46 | 47 | if word == 'exit': 48 | break 49 | 50 | get_word_definition(word) 51 | --------------------------------------------------------------------------------