diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..af61997 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: prateekiiest +patreon: # Replace with a single Patreon username +open_collective: prateekiiest +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: https://opencollective.com/codepython/contribute diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..b735373 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,35 @@ +--- +name: Bug report +about: Create a report to help us improve + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..066b2d9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0630d69 --- /dev/null +++ b/.gitignore @@ -0,0 +1,109 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# VS Code +.vscode/ + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +.DS_Store diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 852b894..bff9c3b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,10 +13,10 @@ While making a Pull Request, please take care of the following rules: - Make sure the master branch of your forked repo is not any commits ahead than the original master repository. - Create a new branch from master in the forked repository. Updated your changes in that branch and not in master. -- Include only one algorithm in each pull request. A PR containing more than one algorithm *will not be merged*. -- Write your algorithm in a language other coders are mostly acquainted with i.e. `C`/`C++`/`Python`/`Java`. Any -other language will be accepted only after discussion with the maintainers. -- When writing the algorithm's code, please include a small `readme.md` file in the folder briefly explaining the -algorithm. Make sure your `readme.md` provides a clear understanding of the algorithm to a new-comer. Explanation -should be given in not more than 300 characters -- Write the name of the algorithm you added and the language you used in the title while making the PR. +- Include only one work in each pull request. If its a big work, include [WIP] (Work in Progress). +- When including a new enhancement , please update the corresponding requirements.txt by adding a file there. +- Include Proper Documentation in your enhancement. + +Any other doubts/questions can be posted as an issue on this repository by using the `doubt` label function. + +Thanks again for contributing to this project :heart: diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 15d9e3f..e558e1f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,6 +5,13 @@ Thanks for all your contributions :heart: :octocat: [prateekiiest](https://github.com/prateekiiest) : CodeOwner +#### Mozilla Global Sprint Hackathon 2018 + +| Github username | Pull Request | Status | +| ------------- |:-------------:| -----:| +| [siddas27](https://github.com/siddas27) | [Logistic regression model](https://github.com/prateekiiest/Code-Sleep-Python/pull/126) | Merged | + + #### Hacktoberfest | Github username | Pull Request | Status | diff --git a/Code-Sleep-Python/.gitignore b/Code-Sleep-Python/.gitignore new file mode 100644 index 0000000..fe78bff --- /dev/null +++ b/Code-Sleep-Python/.gitignore @@ -0,0 +1,5 @@ +# Ignore all req folders inside the projects +*/req + +# Text-To-Speech +text-to-speech/speech.mp3 \ No newline at end of file diff --git a/Code-Sleep-Python/Bird_migration/README.md b/Code-Sleep-Python/Bird_migration/README.md new file mode 100644 index 0000000..d08ce75 --- /dev/null +++ b/Code-Sleep-Python/Bird_migration/README.md @@ -0,0 +1,5 @@ +### Bird Migration + +In this case study, we will continue taking a look at patterns of flight for each of the three birds in our dataset.Documentation of this project available - **[here](http://www.geeksforgeeks.org/tracking-bird-migration-using-python-3/)** + +![](https://upload.wikimedia.org/wikipedia/commons/thumb/a/a3/BrantaLeucopsisMigration.jpg/300px-BrantaLeucopsisMigration.jpg) \ No newline at end of file diff --git a/Code-Sleep-Python/Bird_migration/code.py b/Code-Sleep-Python/Bird_migration/code.py index 30f0e61..98c6a74 100644 --- a/Code-Sleep-Python/Bird_migration/code.py +++ b/Code-Sleep-Python/Bird_migration/code.py @@ -1,3 +1,12 @@ +import pandas as pd +import matplotlib.pyplot as plt +import numpy as np + +# Import bird data +birddata = pd.read_csv('https://d37djvu3ytnwxt.cloudfront.net/assets/' +'courseware/v1/c72498a54a4513c2eb4ec005adc0010c/' +'asset-v1:HarvardX+PH526x+3T2016+type@asset+block/bird_tracking.csv') + # First, use `groupby` to group up the data. grouped_birds = birddata.groupby("bird_name") @@ -5,7 +14,9 @@ mean_speeds = grouped_birds.speed_2d.mean() # The `head` method prints the first 5 lines of each bird. -grouped_birds.head() +# This is useful if you are running this in ipython and need to see some data. +# Call this only on pandas data frame. +# mean_speeds.head() # Find the mean `altitude` for each bird. # Assign this to `mean_altitudes`. @@ -13,16 +24,14 @@ mean_altitudes = grouped_birds.altitude.mean() - - # Convert birddata.date_time to the `pd.datetime` format. birddata.date_time = pd.to_datetime(birddata.date_time) # Create a new column of day of observation birddata["date"] = birddata.date_time.dt.date -# Check the head of the column. -birddata.date.head() +# If you're in ipython and want to check the head of the column run: +# birddata.date.head() grouped_bydates = birddata.groupby("date") mean_altitudes_perday = grouped_bydates.altitude.mean() @@ -33,8 +42,8 @@ grouped_birdday = birddata.groupby(["bird_name","date"]) mean_altitudes_perday = grouped_birdday.altitude.mean() -# look at the head of `mean_altitudes_perday`. -mean_altitudes_perday.head() +# If you're in ipython and want to look at the head of `mean_altitudes_perday` run: +# mean_altitudes_perday.head() grouped_birdday = birddata.groupby(["bird_name","date"]) @@ -48,4 +57,5 @@ sanne_daily_speed.plot(label="Sanne") nico_daily_speed.plot(label="Nico") plt.legend(loc="upper left") +plt.ylabel("2D mean speed (m/s)") plt.show() diff --git a/Code-Sleep-Python/Bird_migration/requirements.txt b/Code-Sleep-Python/Bird_migration/requirements.txt new file mode 100644 index 0000000..a225a6b --- /dev/null +++ b/Code-Sleep-Python/Bird_migration/requirements.txt @@ -0,0 +1,9 @@ +cycler==0.10.0 +kiwisolver==1.1.0 +matplotlib==3.1.1 +numpy==1.22.0 +pandas==0.25.2 +pyparsing==2.4.2 +python-dateutil==2.8.0 +pytz==2019.3 +six==1.12.0 diff --git a/Code-Sleep-Python/Caesar-cipher/README.md b/Code-Sleep-Python/Caesar-cipher/README.md new file mode 100644 index 0000000..4c885f2 --- /dev/null +++ b/Code-Sleep-Python/Caesar-cipher/README.md @@ -0,0 +1,11 @@ + +### Caesar-Cipher + +![Caesar-Cipher](http://www.donatantonio.net/blog/wp-content/uploads/2010/10/cesare-570x355.png) + +A cipher is a secret code for a language. In this study, we will explore a cipher that is reported by contemporary Greek historians to have been used by Julius Caesar to send secret messages to generals during times of war. + +The Caesar cipher, also known as a shift cipher, is one of the simplest forms of encryption. It is a substitution cipher where each letter in the original message (called the plaintext) is replaced with a letter corresponding to a certain number of letters up or down in the alphabet. + + +In this way, a message that initially was quite readable ends up in a form that can not be understood at a simple glance. diff --git a/Code-Sleep-Python/Caesar-cipher/code.py b/Code-Sleep-Python/Caesar-cipher/code.py index 36994ab..ff5a988 100644 --- a/Code-Sleep-Python/Caesar-cipher/code.py +++ b/Code-Sleep-Python/Caesar-cipher/code.py @@ -1,23 +1,23 @@ import string -string.ascii_lowercase +import argparse +string.ascii_lowercase # We will consider the alphabet to be these letters, along with a space. # create `letters` here! - - -## alphabet = string.ascii_lowercase + " " letters = dict(enumerate(alphabet)) -# define `coded_message` here! - +p = argparse.ArgumentParser(description="Implement Caesar Cipher Algorithm") +p.add_argument("-e", "-encription_key", help="encription key") +p.add_argument("-m", "-message", help="message") +args = p.parse_args() ################## -message = raw_input("Enter a string: ") +message = args.m def caesar(mee, encryption_key): @@ -45,7 +45,7 @@ def caesar(mee, encryption_key): return encoded_mess -encryption_key=input("Enter a number: ") +encryption_key = args.e encoded_message = (caesar(message,encryption_key)) print(encoded_message) diff --git a/Code-Sleep-Python/Classification/README.md b/Code-Sleep-Python/Classification/README.md new file mode 100644 index 0000000..ca65515 --- /dev/null +++ b/Code-Sleep-Python/Classification/README.md @@ -0,0 +1,5 @@ +### Classification + +In this case study, we will analyze a dataset consisting of an assortment of wines classified into "high quality" and "low quality", and will use k-Nearest Neighbors to predict whether or not other information about the wine helps us correctly guess whether a new wine will be of high quality. + +![](http://homepages.inf.ed.ac.uk/rbf/HIPR2/classb.gif) \ No newline at end of file diff --git a/Code-Sleep-Python/Classification/code.py b/Code-Sleep-Python/Classification/code.py index 130cde5..db3151d 100644 --- a/Code-Sleep-Python/Classification/code.py +++ b/Code-Sleep-Python/Classification/code.py @@ -1,88 +1,76 @@ +import random + +import matplotlib.pyplot as plt +import numpy as np import pandas as pd -data = pd.read_csv('https://s3.amazonaws.com/demo-datasets/wine.csv') +import sklearn.decomposition +from matplotlib.colors import ListedColormap +# More accuracy +from sklearn.neighbors import KNeighborsClassifier +def accuracy(predictions, outcomes): + # Enter your code here! + occur = 0 + v = np.array(predictions) == np.array(outcomes) + occur = np.sum(v) + return occur -df2 = data.drop('color', axis=1) # color is redundant +data = pd.read_csv('https://s3.amazonaws.com/demo-datasets/wine.csv') -import numpy as np +df2 = data.drop('color', axis=1) # color is redundant +numeric_data = df2.values +numeric_data = (numeric_data - np.mean(numeric_data)) / (np.std(numeric_data)) -numeric_data = (numeric_data - np.mean(numeric_data))/(np.std(numeric_data)) -import sklearn.decomposition pca = sklearn.decomposition.PCA(n_components=2) principal_components = pca.fit(numeric_data).transform(numeric_data) - - - - -import matplotlib.pyplot as plt -from matplotlib.colors import ListedColormap -from matplotlib.backends.backend_pdf import PdfPages observation_colormap = ListedColormap(['red', 'blue']) -x = principal_components[:,0] -y = principal_components[:,1] +x = principal_components[:, 0] +y = principal_components[:, 1] plt.title("Principal Components of Wine") -plt.scatter(x, y, alpha = 0.2, - c = data['high_quality'], cmap = observation_colormap, edgecolors = 'none') -plt.xlim(-8, 8); plt.ylim(-8, 8) -plt.xlabel("Principal Component 1"); plt.ylabel("Principal Component 2") +plt.scatter(x, y, alpha=0.2, + c=data['high_quality'], cmap=observation_colormap, + edgecolors='none') +plt.xlim(-8, 8) +plt.ylim(-8, 8) +plt.xlabel("Principal Component 1") +plt.ylabel("Principal Component 2") plt.show() +x = np.array([1, 2, 3]) +y = np.array([1, 2, 4]) +print(accuracy(x, y)) +print(accuracy([], data["high_quality"])) - -def accuracy(predictions, outcomes): - # Enter your code here! - occur =0 - for i in range(len(predictions)): - if(predictions[i] == outcomes[i]): - occur += 1 - return occur - - -x = np.array([1,2,3]) -y = np.array([1,2,4]) - -print (accuracy(x,y)) - - -print(accuracy(0,data["high_quality"])) - - -############################## More accuracy -from sklearn.neighbors import KNeighborsClassifier -knn = KNeighborsClassifier(n_neighbors = 5) +knn = KNeighborsClassifier(n_neighbors=5) knn.fit(numeric_data, data['high_quality']) # Enter your code here! library_predictions = knn.predict(numeric_data) -print(accuracy(library_predictions,data['high_quality'])) +print(accuracy(library_predictions, data['high_quality'])) -################ n_rows = data.shape[0] +print() random.seed(123) selection = random.sample(range(n_rows), 10) - predictors = np.array(numeric_data) training_indices = [i for i in range(len(predictors)) if i not in selection] outcomes = np.array(data["high_quality"]) -my_predictions = [knn_predict(p, predictors[training_indices,:], outcomes, k=5) for p in predictors[selection]] -percentage = accuracy(my_predictions,data.high_quality[selection]) +my_predictions = [ + knn.predict(predictors[training_indices, :]) for p in + predictors[selection]] +percentage = accuracy(my_predictions, outcomes) print(percentage) - - - - - diff --git a/Code-Sleep-Python/Classification/requirements.txt b/Code-Sleep-Python/Classification/requirements.txt index 3922f12..2c970b0 100644 --- a/Code-Sleep-Python/Classification/requirements.txt +++ b/Code-Sleep-Python/Classification/requirements.txt @@ -1,4 +1,4 @@ -numpy==1.13.3 +numpy==1.22.0 pandas==0.21.0 matplotlib==2.1.0 scikit-learn==0.19.1 \ No newline at end of file diff --git a/Code-Sleep-Python/Cricket_Notification/README.md b/Code-Sleep-Python/Cricket_Notification/README.md new file mode 100644 index 0000000..bb9328b --- /dev/null +++ b/Code-Sleep-Python/Cricket_Notification/README.md @@ -0,0 +1,5 @@ +### Cricket Notification + +A simple program to get the score and match status if India is playing. This information is obtained from the terminal. + +![](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgwxUvr7AfngMuzr4a8tc69jexGPoPeSdCTiDZhvlXqgZTH_wxgg) \ No newline at end of file diff --git a/Code-Sleep-Python/Cricket_Notification/requirements.txt b/Code-Sleep-Python/Cricket_Notification/requirements.txt new file mode 100644 index 0000000..2d3d1ce --- /dev/null +++ b/Code-Sleep-Python/Cricket_Notification/requirements.txt @@ -0,0 +1,2 @@ +notify2 +dbus-python diff --git a/Code-Sleep-Python/Encryption-Techniques/README.md b/Code-Sleep-Python/Encryption-Techniques/README.md index b8b842f..2fcb4e1 100644 --- a/Code-Sleep-Python/Encryption-Techniques/README.md +++ b/Code-Sleep-Python/Encryption-Techniques/README.md @@ -1,4 +1,11 @@ ### Encryption Techniques + + +Encryption is an interesting piece of technology that works by scrambling data so it is unreadable by unintended parties. The technology comes in many forms, with key size and strength generally being the biggest differences in one variety from the next. This repo has implementations of different encryption techniques. More [here](https://en.wikipedia.org/wiki/Encryption). + +![](http://img.bityard.net/blog/aes.png) + + * [Caesar Cipher](https://en.wikipedia.org/wiki/Caesar_cipher) * [Code](Caesar-Cipher/) * [Hill Cipher](https://en.wikipedia.org/wiki/Hill_cipher) diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue1.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue1.png new file mode 100644 index 0000000..d82802a Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue1.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue2.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue2.png new file mode 100644 index 0000000..034b76c Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue2.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue3.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue3.png new file mode 100644 index 0000000..900d012 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/blue3.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red1.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red1.png new file mode 100644 index 0000000..e853b95 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red1.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red2.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red2.png new file mode 100644 index 0000000..a915f7e Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red2.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red3.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red3.png new file mode 100644 index 0000000..f9ed856 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/red3.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow1.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow1.png new file mode 100644 index 0000000..e9e1c77 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow1.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow2.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow2.png new file mode 100644 index 0000000..2ca3c2d Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow2.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow3.png b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow3.png new file mode 100644 index 0000000..2f693da Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Grumpy/yellow3.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/0.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/0.png new file mode 100644 index 0000000..ad522b9 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/0.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/1.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/1.png new file mode 100644 index 0000000..55d7c89 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/1.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/2.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/2.png new file mode 100644 index 0000000..6a3af46 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/2.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/3.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/3.png new file mode 100644 index 0000000..13d88bf Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/3.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/4.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/4.png new file mode 100644 index 0000000..51cbbc3 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/4.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/5.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/5.png new file mode 100644 index 0000000..b5055ab Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/5.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/6.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/6.png new file mode 100644 index 0000000..dbc4c00 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/6.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/7.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/7.png new file mode 100644 index 0000000..04658ad Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/7.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/8.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/8.png new file mode 100644 index 0000000..f053e38 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/8.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/Score/9.png b/Code-Sleep-Python/Flappy Bird/Assets/Score/9.png new file mode 100644 index 0000000..3bd0412 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/Score/9.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/background-day.png b/Code-Sleep-Python/Flappy Bird/Assets/background-day.png new file mode 100644 index 0000000..afcb5ec Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/background-day.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/background-night.png b/Code-Sleep-Python/Flappy Bird/Assets/background-night.png new file mode 100644 index 0000000..e2a2b89 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/background-night.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/base.png b/Code-Sleep-Python/Flappy Bird/Assets/base.png new file mode 100644 index 0000000..c374f2b Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/base.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/flappybird.png b/Code-Sleep-Python/Flappy Bird/Assets/flappybird.png new file mode 100644 index 0000000..d74f2cf Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/flappybird.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/gameover.png b/Code-Sleep-Python/Flappy Bird/Assets/gameover.png new file mode 100644 index 0000000..b1df7f5 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/gameover.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/pipe-green.png b/Code-Sleep-Python/Flappy Bird/Assets/pipe-green.png new file mode 100644 index 0000000..4664401 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/pipe-green.png differ diff --git a/Code-Sleep-Python/Flappy Bird/Assets/pipe-red.png b/Code-Sleep-Python/Flappy Bird/Assets/pipe-red.png new file mode 100644 index 0000000..ab6e065 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Assets/pipe-red.png differ diff --git a/Code-Sleep-Python/Flappy Bird/README.md b/Code-Sleep-Python/Flappy Bird/README.md new file mode 100644 index 0000000..e4d44d6 --- /dev/null +++ b/Code-Sleep-Python/Flappy Bird/README.md @@ -0,0 +1,39 @@ +# Flappy Bird + +[![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com) +[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](https://forthebadge.com) +[![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) + +Flappy Bird is an implementation of the famous flappy bird game in pygame. The game is specifically meant to run on pydroid3 on android, It may not work properly in desktop. + +Install pydroid3 on Android from here : [pydroid3 playstore](https://play.google.com/store/apps/details?id=ru.iiec.pydroid3&hl=en_IN&gl=US) + +![Alt text](app.webp?raw=true "Flappy Bird") + +## How to Download + +Download this project from here [Download Flappy Bird](https://downgit.github.io/#/home?url=https://github.com/pyGuru123/Python-Games/tree/master/Flappy%20Bird) + +## Requirements + +Use the package manager [pip](https://pip.pypa.io/en/stable/) to install following packages :- +* Pygame + +```bash +pip install pygame +``` + +pygame is already installed in pydroid3, no installation required. + +## Usage + +Navigate and click main.py to open the game in pydroid3, tap anywhere to start the game. The objective of the game is jump and pass through the poles without touching them. + +Controls: +* Tap on the screen to make the bird jump. + +## Contributing + +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. + +Please make sure to update tests as appropriate. \ No newline at end of file diff --git a/Code-Sleep-Python/Flappy Bird/Sounds/die.wav b/Code-Sleep-Python/Flappy Bird/Sounds/die.wav new file mode 100644 index 0000000..9b79fbd Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Sounds/die.wav differ diff --git a/Code-Sleep-Python/Flappy Bird/Sounds/hit.wav b/Code-Sleep-Python/Flappy Bird/Sounds/hit.wav new file mode 100644 index 0000000..9d9b77c Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Sounds/hit.wav differ diff --git a/Code-Sleep-Python/Flappy Bird/Sounds/point.wav b/Code-Sleep-Python/Flappy Bird/Sounds/point.wav new file mode 100644 index 0000000..9cf19fe Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Sounds/point.wav differ diff --git a/Code-Sleep-Python/Flappy Bird/Sounds/swoosh.wav b/Code-Sleep-Python/Flappy Bird/Sounds/swoosh.wav new file mode 100644 index 0000000..bcae63e Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Sounds/swoosh.wav differ diff --git a/Code-Sleep-Python/Flappy Bird/Sounds/wing.wav b/Code-Sleep-Python/Flappy Bird/Sounds/wing.wav new file mode 100644 index 0000000..9ae2c67 Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/Sounds/wing.wav differ diff --git a/Code-Sleep-Python/Flappy Bird/app.webp b/Code-Sleep-Python/Flappy Bird/app.webp new file mode 100644 index 0000000..67672ad Binary files /dev/null and b/Code-Sleep-Python/Flappy Bird/app.webp differ diff --git a/Code-Sleep-Python/Flappy Bird/main.py b/Code-Sleep-Python/Flappy Bird/main.py new file mode 100644 index 0000000..ab54e93 --- /dev/null +++ b/Code-Sleep-Python/Flappy Bird/main.py @@ -0,0 +1,160 @@ +import pygame +import random + +from objects import Grumpy, Pipe, Base, Score + +# Setup ******************************************* + +pygame.init() +SCREEN = WIDTH, HEIGHT = 288, 512 +display_height = 0.80 * HEIGHT +info = pygame.display.Info() +width = info.current_w +height = info.current_h + +if width >= height: + win = pygame.display.set_mode(SCREEN, pygame.NOFRAME) +else: + win = pygame.display.set_mode( + SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN) + +clock = pygame.time.Clock() +FPS = 60 + +# COLORS + +RED = (255, 0, 0) +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) + +# Backgrounds + +bg1 = pygame.image.load('Assets/background-day.png') +bg2 = pygame.image.load('Assets/background-night.png') + +bg = random.choice([bg1, bg2]) +im_list = [pygame.image.load('Assets/pipe-green.png'), + pygame.image.load('Assets/pipe-red.png')] +pipe_img = random.choice(im_list) + +gameover_img = pygame.image.load('Assets/gameover.png') +flappybird_img = pygame.image.load('Assets/flappybird.png') +flappybird_img = pygame.transform.scale(flappybird_img, (200, 80)) + +# Sounds & fx + + +die_fx = pygame.mixer.Sound('Sounds/die.wav') +hit_fx = pygame.mixer.Sound('Sounds/hit.wav') +point_fx = pygame.mixer.Sound('Sounds/point.wav') +swoosh_fx = pygame.mixer.Sound('Sounds/swoosh.wav') +wing_fx = pygame.mixer.Sound('Sounds/wing.wav') + +# Objects + +pipe_group = pygame.sprite.Group() +base = Base(win) +score_img = Score(WIDTH // 2, 50, win) +grumpy = Grumpy(win) + +# Variables + +base_height = 0.80 * HEIGHT +speed = 0 +game_started = False +game_over = False +restart = False +score = 0 +start_screen = True +pipe_pass = False +pipe_frequency = 1600 + +running = True +while running: + win.blit(bg, (0, 0)) + + if start_screen: + speed = 0 + grumpy.draw_flap() + base.update(speed) + win.blit(flappybird_img, (40, 50)) + else: + + if game_started and not game_over: + + next_pipe = pygame.time.get_ticks() + if next_pipe - last_pipe >= pipe_frequency: + y = display_height // 2 + pipe_pos = random.choice(range(-100, 100, 4)) + height = y + pipe_pos + + top = Pipe(win, pipe_img, height, 1) + bottom = Pipe(win, pipe_img, height, -1) + pipe_group.add(top) + pipe_group.add(bottom) + last_pipe = next_pipe + + pipe_group.update(speed) + base.update(speed) + grumpy.update() + score_img.update(score) + + if (pygame.sprite.spritecollide(grumpy, pipe_group, False) or + grumpy.rect.top <= 0): + game_started = False + if grumpy.alive: + hit_fx.play() + die_fx.play() + grumpy.alive = False + grumpy.theta = grumpy.vel * -2 + + if grumpy.rect.bottom >= display_height: + speed = 0 + game_over = True + + if len(pipe_group) > 0: + p = pipe_group.sprites()[0] + if (grumpy.rect.left > p.rect.left and + grumpy.rect.right < p.rect.right and not pipe_pass + and grumpy.alive): + pipe_pass = True + + if pipe_pass: + if grumpy.rect.left > p.rect.right: + pipe_pass = False + score += 1 + point_fx.play() + + if not grumpy.alive: + win.blit(gameover_img, (50, 200)) + + for event in pygame.event.get(): + if event.type == pygame.QUIT: + running = False + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_ESCAPE or \ + event.key == pygame.K_q: + running = False + if event.type == pygame.MOUSEBUTTONDOWN: + if start_screen: + game_started = True + speed = 2 + start_screen = False + + game_over = False + last_pipe = pygame.time.get_ticks() - pipe_frequency + next_pipe = 0 + pipe_group.empty() + + speed = 2 + score = 0 + + if game_over: + start_screen = True + grumpy = Grumpy(win) + pipe_img = random.choice(im_list) + bg = random.choice([bg1, bg2]) + + clock.tick(FPS) + pygame.display.update() +pygame.quit() diff --git a/Code-Sleep-Python/Flappy Bird/objects.py b/Code-Sleep-Python/Flappy Bird/objects.py new file mode 100644 index 0000000..8c0d813 --- /dev/null +++ b/Code-Sleep-Python/Flappy Bird/objects.py @@ -0,0 +1,153 @@ +import pygame +import random + +SCREEN = WIDTH, HEIGHT = 288, 512 +display_height = 0.80 * HEIGHT + +pygame.mixer.init() +wing_fx = pygame.mixer.Sound('Sounds/wing.wav') + + +class Grumpy: + def __init__(self, win): + self.win = win + + self.im_list = [] + bird_color = random.choice(['red', 'blue', 'yellow']) + for i in range(1, 4): + img = pygame.image.load(f'Assets/Grumpy/{bird_color}{i}.png') + self.im_list.append(img) + + self.reset() + + def update(self): + # gravity + self.vel += 0.3 + if self.vel >= 8: + self.vel = 8 + if self.rect.bottom <= display_height: + self.rect.y += int(self.vel) + + if self.alive: + + # jump + if pygame.mouse.get_pressed()[0] == 1 and not self.jumped: + wing_fx.play() + self.jumped = True + self.vel = -6 + if pygame.mouse.get_pressed()[0] == 0: + self.jumped = False + + self.flap_counter() + + self.image = pygame.transform.rotate( + self.im_list[self.index], self.vel * -2) + else: + if self.rect.bottom <= display_height: + self.theta -= 2 + self.image = pygame.transform.rotate( + self.im_list[self.index], self.theta) + + self.win.blit(self.image, self.rect) + + def flap_counter(self): + self.counter += 1 + if self.counter > 5: + self.counter = 0 + self.index += 1 + if self.index >= 3: + self.index = 0 + + def draw_flap(self): + self.flap_counter() + if self.flap_pos <= -10 or self.flap_pos > 10: + self.flap_inc *= -1 + self.flap_pos += self.flap_inc + self.rect.y += self.flap_inc + self.rect.x = WIDTH // 2 - 20 + self.image = self.im_list[self.index] + self.win.blit(self.image, self.rect) + + def reset(self): + self.index = 0 + self.image = self.im_list[self.index] + self.rect = self.image.get_rect() + self.rect.x = 60 + self.rect.y = int(display_height) // 2 + self.counter = 0 + self.vel = 0 + self.jumped = False + self.alive = True + self.theta = 0 + self.mid_pos = display_height // 2 + self.flap_pos = 0 + self.flap_inc = 1 + + +class Base: + def __init__(self, win): + self.win = win + + self.image1 = pygame.image.load('Assets/base.png') + self.image2 = self.image1 + self.rect1 = self.image1.get_rect() + self.rect1.x = 0 + self.rect1.y = int(display_height) + self.rect2 = self.image2.get_rect() + self.rect2.x = WIDTH + self.rect2.y = int(display_height) + + def update(self, speed): + self.rect1.x -= speed + self.rect2.x -= speed + + if self.rect1.right <= 0: + self.rect1.x = WIDTH - 5 + if self.rect2.right <= 0: + self.rect2.x = WIDTH - 5 + + self.win.blit(self.image1, self.rect1) + self.win.blit(self.image2, self.rect2) + + +class Pipe(pygame.sprite.Sprite): + def __init__(self, win, image, y, position): + super(Pipe, self).__init__() + + self.win = win + self.image = image + self.rect = self.image.get_rect() + pipe_gap = 100 // 2 + x = WIDTH + + if position == 1: + self.image = pygame.transform.flip(self.image, False, True) + self.rect.bottomleft = (x, y - pipe_gap) + elif position == -1: + self.rect.topleft = (x, y + pipe_gap) + + def update(self, speed): + self.rect.x -= speed + if self.rect.right < 0: + self.kill() + self.win.blit(self.image, self.rect) + + +class Score: + def __init__(self, x, y, win): + self.score_list = [] + for score in range(10): + img = pygame.image.load(f'Assets/Score/{score}.png') + self.score_list.append(img) + self.x = x + self.y = y + + self.win = win + + def update(self, score): + score = str(score) + for index, num in enumerate(score): + self.image = self.score_list[int(num)] + self.rect = self.image.get_rect() + self.rect.topleft = self.x - 15 * len(score) + 30 * index, self.y + self.win.blit(self.image, self.rect) diff --git a/Code-Sleep-Python/Hangman/README.md b/Code-Sleep-Python/Hangman/README.md new file mode 100644 index 0000000..ee06e4e --- /dev/null +++ b/Code-Sleep-Python/Hangman/README.md @@ -0,0 +1,7 @@ +### Hangman + +Hangman is a simple game where a player will guess a word letter by letter. + +![](http://daramcq.github.io/img/hangman-game-5.png) + +In this project, you will create a program that generates a random word that you must guess. \ No newline at end of file diff --git a/Code-Sleep-Python/Inception TicTacToe/inceptionTTT.py b/Code-Sleep-Python/Inception TicTacToe/inceptionTTT.py index 45b80ae..2985b47 100644 --- a/Code-Sleep-Python/Inception TicTacToe/inceptionTTT.py +++ b/Code-Sleep-Python/Inception TicTacToe/inceptionTTT.py @@ -1,324 +1,394 @@ -from Tkinter import * -import tkMessageBox -import random - - -class pvp_app(Frame): - def __init__(self): - Frame.__init__(self) - - def PlayerGame(self): - self.pvp_button.grid_forget() - self.back_s_button.grid_forget() - self.startgame_label.grid_forget() - - self.start_label=Label(self,text="Who starts the game??") - self.start_label.grid(row=0,columnspan=11) - self.p1_button=Button(self,text="Player 1",fg="blue",command=lambda: self.startGame(TRUE,FALSE)) - self.p1_button.grid(row=0,column=0, columnspan=2) - self.p2_button=Button(self,text="Player 2",fg="blue",command=lambda: self.startGame(FALSE,TRUE)) - self.p2_button.grid(row=0,column=8, columnspan=2) - self.back_p_button=Button(self,text="Back",fg="blue",bg="green",command=self.back_r_button,height=1,width=2) - self.back_p_button.grid(row=12,column=5) - - self.button_lst=[[0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9], - [0,1,2,3,4,5,6,7,8,9]] - - for i in range(1,10): - for j in range(1,10): - self.button_lst[i][j]=Button(self,text=" ",fg="yellow",bg="red",state=DISABLED,command=lambda x=i,y=j: self.handle_button(x,y), height=1,width=2,font=("Purisa", 18)) - - L = [[[1,2,0], [2,2,1], [3,2,2], - [4,3,0], [5,3,1], [6,3,2], - [7,4,0], [8,4,1], [9,4,2]], - - [[1,2,4], [2,2,5], [3,2,6], - [4,3,4], [5,3,5], [6,3,6], - [7,4,4], [8,4,5], [9,4,6]], - - [[1,2,7], [2,2,8], [3,2,9], - [4,3,7], [5,3,8], [6,3,9], - [7,4,7], [8,4,8], [9,4,9]], - - [[1,5,0], [2,5,1], [3,5,2], - [4,6,0], [5,6,1], [6,6,2], - [7,7,0], [8,7,1], [9,7,2]], - - [[1,5,4], [2,5,5], [3,5,6], - [4,6,4], [5,6,5], [6,6,6], - [7,7,4], [8,7,5], [9,7,6]], - - [[1,5,7], [2,5,8], [3,5,9], - [4,6,7], [5,6,8], [6,6,9], - [7,7,7], [8,7,8], [9,7,9]], - - [[1,8,0], [2,8,1], [3,8,2], - [4,9,0], [5,9,1], [6,9,2], - [7,10,0], [8,10,1], [9,10,2]], - - [[1,8,4], [2,8,5], [3,8,6], - [4,9,4], [5,9,5], [6,9,6], - [7,10,4], [8,10,5], [9,10,6]], - - [[1,8,7], [2,8,8], [3,8,9], - [4,9,7], [5,9,8], [6,9,9], - [7,10,7], [8,10,8], [9,10,9]]] - - count=1 - for j in L: - for i in j: - self.button_lst[count][i[0]].grid(row=i[1], column=i[2]) - count+=1 - - def startGame(self,p1,p2): - self.p1_button.config(state=DISABLED) - self.p2_button.config(state=DISABLED) - self.back_p_button.config(state=DISABLED) - for i in range(1,10): - for j in range(1,10): - self.button_lst[i][j].config(state=NORMAL) - - if(p1==TRUE): - self.start_label.config(text="Player 1 starts with X") - self.turn=TRUE - - else: - self.start_label.config(text="Player 2 starts with O") - self.turn=FALSE - - self.bState=[[10,10,10,10,10,10,10,10,10,10], - [10,0,0,0,0,0,0,0,0,0], - [10,0,0,0,0,0,0,0,0,0], - [10,0,0,0,0,0,0,0,0,0], - [10,0,0,0,0,0,0,0,0,0], - [10,0,0,0,0,0,0,0,0,0], - [10,0,0,0,0,0,0,0,0,0], - [10,0,0,0,0,0,0,0,0,0], - [10,0,0,0,0,0,0,0,0,0], - [10,0,0,0,0,0,0,0,0,0]] - - self.bSum= [[0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0],] - - self.fState=[10,0,0,0,0,0,0,0,0,0] - - self.bWin=[10] - - self.GameDone=FALSE - - def handle_button(self,i,j): - if(self.turn==TRUE): - self.button_lst[i][j].config(text="X",state=DISABLED) - self.turn=FALSE - self.bState[i][j]=1 - if i in self.bWin: - for a in range(1,10): - for b in range(1,10): - self.button_lst[a][b].config(state=DISABLED,bg="red") - for a in range(1,10): - self.button_lst[j][a].config(state=NORMAL,bg="blue") - else: - for a in self.bWin: - for b in range(1,10): - self.button_lst[a][b].config(state=DISABLED,bg="red") - for a in range(1,10): - self.button_lst[j][a].config(state=NORMAL,bg="blue") - - - else: - self.button_lst[i][j].config(text="O",state=DISABLED) - self.turn=TRUE - self.bState[i][j]=-1 - for a in range(1,10): - for b in range(1,10): - self.button_lst[a][b].config(state=DISABLED,bg="red") - for a in range(1,10): - self.button_lst[j][a].config(state=NORMAL,bg="blue") - - self.check() - - def check(self): - - self.sum() - - count=0 - for i in self.bSum: - count+=1 - for j in i: - if(j==3): - self.fState[count]=1 - self.bWin.append(count) - elif(j==-3): - self.fState[count]=-1 - self.bWin.append(count) - else: - check=0 - for i in self.bState: - for j in i: - if j!=0 and j!=10: - check=1 - if check==0: - for a in range(1,10): - for b in range(1,10): - self.button_lst[a][b].config(state=DISABLED) - break - -''' #list of possible win combinations in the form of button numbers +import tkinter + + +class pvp_app(): + + def __init__(self): + tkinter.Frame.__init__(self) + + ''' + #list of possible win combinations in the form of button numbers WinCombo=[[1,2,3], [4,5,6], [7,8,9], #rows [1,4,7], [2,5,8], [3,6,9], #columns [1,5,9], [3,5,7]] #diagonals #after doing sums look for 3 or -3 to find if there was a winner for i in WinCombo: - if((self.bState[i[0]]+self.bState[i[1]]+self.bState[i[2]])==3): #3 means player1 has won - self.start_label.config(text="Player 1 won!!") #label if player 1 is won + if((self.bState[i[0]]+self.bState[i[1]]+self.bState[i[2]])==3): + #3 means player1 has won + self.start_label.config(text="Player 1 won!!") + #label if player 1 is won self.GameDone=TRUE for k in range(1,10): self.button_lst[k].configure(state=DISABLED) break - elif((self.bState[i[0]]+self.bState[i[1]]+self.bState[i[2]])==-3): #-3 means player2 has won - self.start_label.config(text="Player 2 won!!") #label if player 2 is won + elif((self.bState[i[0]]+self.bState[i[1]]+self.bState[i[2]])==-3): + #-3 means player2 has won + self.start_label.config(text="Player 2 won!!") + #label if player 2 is won self.GameDone=TRUE for k in range(1,10): self.button_lst[k].configure(state=DISABLED) break else: - - if not (0 in self.bState): #if there is no 0 in button state , the game is done - self.start_label.config(text="Match drawn!!") #label if match is drawn + + if not (0 in self.bState): + # if there is no 0 in button state , the game is done + self.start_label.config(text="Match drawn!!") + # label if match is drawn self.GameDone=TRUE for k in range(1,10): self.button_lst[k].configure(state=DISABLED) break -''' - - if(self.GameDone==TRUE): - self.message=tkMessageBox.askquestion(" ","Do you want to play the game again?") - if(self.message=="no"): - self.QuitGame() - else: - self.p1_button.config(state=NORMAL) - self.p2_button.config(state=NORMAL) - self.back_p_button.config(state=NORMAL) - self.start_label.config(text="Who will start the game?") - for a in range(1,10): - for b in range(1,10): - self.button_lst[a][b].config(state=NORMAL) - - def sum(self): - WinCombo=[[[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]], - [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]], - [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]], - [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]], - [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]], - [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]], - [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]], - [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]], - [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]] - - count1=0 - for i in WinCombo: - count=0 - for k in i: - self.bSum[count1][count]=0 - for j in k: - self.bSum[count1][count]+=self.bState[count1+1][j] - count+=1 - count1+=1 - - def back_r_button(self): - self.p1_button.grid_forget() - self.p2_button.grid_forget() - self.back_p_button.grid_forget() - self.start_label.grid_forget() - for a in range(1,10): - for b in range(1,10): - self.button_lst[a][b].grid_forget() - self.StartGame() - -#------------------------------------------------------------------------------------------------------------------------ - - -class MainGUI(Frame,pvp_app): - def __init__(self,master): - Frame.__init__(self,master) - self.grid() - self.configure(background="green") - self.ShowHomepage() - - - def ShowHomepage(self): - self.homepage_label = Label(self,text="WELCOME TO THE WORLD OF TIC-TAC-TOE",font=("courier",15),fg="red",bg="yellow") - self.homepage_label.grid(row=0 , column=1 , padx=20 , pady=25 ) - - self.start_button = Button(self,text="Start Game",command=self.StartGame,fg="blue") - self.start_button.grid(row=1,column=1,padx=100,pady=50) - - self.rules_button = Button(self,text="Rules",command=self.ShowRule,fg="red") - self.rules_button.grid(row=2,column=1,padx=100,pady=50) - - self.quit_button = Button(self,text="Quit",command=self.QuitGame,fg="purple") - self.quit_button.grid(row=3,column=1,padx=100,pady=50) - - def StartGame(self): - self.rules_button.grid_forget() - self.quit_button.grid_forget() - self.homepage_label.grid_forget() - self.start_button.grid_forget() - self.startgame_label = Label(self,text="Whom do you want to play against?",font=("courier",15),fg="red",bg="yellow") - self.startgame_label.grid(row=0 , column=1 , padx=20 , pady=25 ) - self.pvp_button = Button(self,text="2 Player Mode",command=lambda: pvp_app.PlayerGame(self)) - self.pvp_button.grid(row=2 , column=1 ,padx=100 , pady=50) - - self.back_s_button = Button(self,text="Back",command=self.back_startGame) - self.back_s_button.grid(row=4,column=1,padx=100,pady=50) - - - def ShowRule(self): - self.homepage_label.grid_forget() - self.start_button.grid_forget() - self.rules_button.grid_forget() - self.quit_button.grid_forget() - self.rules_label = Label(self,text="Game for two players,X and O,\nwho take turns marking the spaces\nin a 3x3 grid.The player who\nsucceeds in placing three of their marks\nin a horizontal,vertical\nor diagonal row wins the game.",font=("pursia",15),fg="red",bg="green") - self.rules_label.grid(row=0 , column=1 , padx=45, pady=35 ) - self.back_r_button = Button(self,text="Back",command=self.back_rules) - self.back_r_button.grid(row=2,column=1,padx=100,pady=50) - - def QuitGame(self): - self.message=tkMessageBox.askquestion("Exit","Do you want to exit ?") - if (self.message == 'yes'): - root.destroy() - - def back_rules(self): - self.rules_label.grid_forget() - self.back_r_button.grid_forget() - self.ShowHomepage() - - def back_startGame(self): - self.pvp_button.grid_forget() - self.back_s_button.grid_forget() - self.startgame_label.grid_forget() - self.ShowHomepage() - - -root=Tk() -root.title("Tic Tac Toe") -root.geometry("500x530") -root.config(bg="green") -appl=MainGUI(root) -root.mainloop() + ''' + + def PlayerGame(self): + self.pvp_button.grid_forget() + self.back_s_button.grid_forget() + self.startgame_label.grid_forget() + + self.start_label = tkinter.Label(self, text="Who starts the game??") + self.start_label.grid(row=0, columnspan=11) + self.p1_button = tkinter.Button(self, text="Player 1", fg="blue", + command=lambda: self.startGame( + tkinter.TRUE, tkinter.FALSE)) + self.p1_button.grid(row=0, column=0, columnspan=2) + self.p2_button = tkinter.Button(self, text="Player 2", fg="blue", + command=lambda: self.startGame( + tkinter.FALSE, tkinter.TRUE)) + self.p2_button.grid(row=0, column=8, columnspan=2) + self.back_p_button = tkinter.Button(self, text="Back", fg="blue", + bg="green", + command=self.back_r_button, + height=1, + width=2) + self.back_p_button.grid(row=12, column=5) + + self.button_lst = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] + + for i in range(1, 10): + for j in range(1, 10): + self.button_lst[i][j] = tkinter.Button(self, text=" ", + fg="yellow", + bg="red", + state=tkinter.DISABLED, + command=lambda x=i, + y=j: + self.handle_button( + x, y), height=1, + width=2, + font=("Purisa", 18)) + + L = [[[1, 2, 0], [2, 2, 1], [3, 2, 2], + [4, 3, 0], [5, 3, 1], [6, 3, 2], + [7, 4, 0], [8, 4, 1], [9, 4, 2]], + + [[1, 2, 4], [2, 2, 5], [3, 2, 6], + [4, 3, 4], [5, 3, 5], [6, 3, 6], + [7, 4, 4], [8, 4, 5], [9, 4, 6]], + + [[1, 2, 7], [2, 2, 8], [3, 2, 9], + [4, 3, 7], [5, 3, 8], [6, 3, 9], + [7, 4, 7], [8, 4, 8], [9, 4, 9]], + + [[1, 5, 0], [2, 5, 1], [3, 5, 2], + [4, 6, 0], [5, 6, 1], [6, 6, 2], + [7, 7, 0], [8, 7, 1], [9, 7, 2]], + + [[1, 5, 4], [2, 5, 5], [3, 5, 6], + [4, 6, 4], [5, 6, 5], [6, 6, 6], + [7, 7, 4], [8, 7, 5], [9, 7, 6]], + + [[1, 5, 7], [2, 5, 8], [3, 5, 9], + [4, 6, 7], [5, 6, 8], [6, 6, 9], + [7, 7, 7], [8, 7, 8], [9, 7, 9]], + + [[1, 8, 0], [2, 8, 1], [3, 8, 2], + [4, 9, 0], [5, 9, 1], [6, 9, 2], + [7, 10, 0], [8, 10, 1], [9, 10, 2]], + + [[1, 8, 4], [2, 8, 5], [3, 8, 6], + [4, 9, 4], [5, 9, 5], [6, 9, 6], + [7, 10, 4], [8, 10, 5], [9, 10, 6]], + + [[1, 8, 7], [2, 8, 8], [3, 8, 9], + [4, 9, 7], [5, 9, 8], [6, 9, 9], + [7, 10, 7], [8, 10, 8], [9, 10, 9]]] + + count = 1 + for j in L: + for i in j: + self.button_lst[count][i[0]].grid(row=i[1], column=i[2]) + count += 1 + + def startGame(self, p1, p2): + self.p1_button.config(state=tkinter.DISABLED) + self.p2_button.config(state=tkinter.DISABLED) + self.back_p_button.config(state=tkinter.DISABLED) + for i in range(1, 10): + for j in range(1, 10): + self.button_lst[i][j].config(state=tkinter.NORMAL) + + if (p1 == tkinter.TRUE): + self.start_label.config(text="Player 1 starts with X") + self.turn = tkinter.TRUE + + else: + self.start_label.config(text="Player 2 starts with O") + self.turn = tkinter.FALSE + + self.bState = [[10, 10, 10, 10, 10, 10, 10, 10, 10, 10], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [10, 0, 0, 0, 0, 0, 0, 0, 0, 0]] + + self.bSum = [[0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], ] + + self.fState = [10, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + self.bWin = [10] + + self.GameDone = tkinter.FALSE + + def handle_button(self, i, j): + if (self.turn == tkinter.TRUE): + self.button_lst[i][j].config(text="X", state=tkinter.DISABLED) + self.turn = tkinter.FALSE + self.bState[i][j] = 1 + if i in self.bWin: + for a in range(1, 10): + for b in range(1, 10): + self.button_lst[a][b].config(state=tkinter.DISABLED, + bg="red") + for a in range(1, 10): + self.button_lst[j][a].config(state=tkinter.NORMAL, + bg="blue") + else: + for a in self.bWin: + for b in range(1, 10): + self.button_lst[a][b].config(state=tkinter.DISABLED, + bg="red") + for a in range(1, 10): + self.button_lst[j][a].config(state=tkinter.NORMAL, + bg="blue") + + + else: + self.button_lst[i][j].config(text="O", state=tkinter.DISABLED) + self.turn = tkinter.TRUE + self.bState[i][j] = -1 + for a in range(1, 10): + for b in range(1, 10): + self.button_lst[a][b].config(state=tkinter.DISABLED, + bg="red") + for a in range(1, 10): + self.button_lst[j][a].config(state=tkinter.NORMAL, bg="blue") + + self.check() + + def check(self): + + self.sum() + + count = 0 + for i in self.bSum: + count += 1 + for j in i: + if (j == 3): + self.fState[count] = 1 + self.bWin.append(count) + elif (j == -3): + self.fState[count] = -1 + self.bWin.append(count) + else: + check = 0 + for i in self.bState: + for j in i: + if j != 0 and j != 10: + check = 1 + if check == 0: + for a in range(1, 10): + for b in range(1, 10): + self.button_lst[a][b].config( + state=tkinter.DISABLED) + break + if self.GameDone == tkinter.TRUE: + self.message = tkinter.messagebox.askquestion(" ", + "Do you want to " + "play the " + "game again?") + if self.message == "no": + self.QuitGame() + else: + self.p1_button.config(state=tkinter.NORMAL) + self.p2_button.config(state=tkinter.NORMAL) + self.back_p_button.config(state=tkinter.NORMAL) + self.start_label.config(text="Who will start the game?") + for a in range(1, 10): + for b in range(1, 10): + self.button_lst[a][b].config(state=tkinter.NORMAL) + + def sum(self): + WinCombo = [ + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]], + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]], + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]], + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]], + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]], + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]], + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]], + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]], + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], + [1, 5, 9], [3, 5, 7]]] + + count1 = 0 + for i in WinCombo: + count = 0 + for k in i: + self.bSum[count1][count] = 0 + for j in k: + self.bSum[count1][count] += self.bState[count1 + 1][j] + count += 1 + count1 += 1 + + def back_r_button(self): + self.p1_button.grid_forget() + self.p2_button.grid_forget() + self.back_p_button.grid_forget() + self.start_label.grid_forget() + for a in range(1, 10): + for b in range(1, 10): + self.button_lst[a][b].grid_forget() + self.StartGame() + + # ------------------------------------------------------------------------ + + +class MainGUI(tkinter.Frame, pvp_app): + def __init__(self, master=None): + tkinter.Frame.__init__(self, master) + self.grid() + self.configure(background="green") + self.master.title("Tic Tac Toe") + self.master.geometry("500x530") + self.ShowHomepage() + self.label = tkinter.Label(self) + self.label.grid(row=0, column=0) + + def ShowHomepage(self): + self.homepage_label = tkinter.Label(self, + text="WELCOME TO THE WORLD OF " + "TIC-TAC-TOE", + font=("courier", 15), fg="red", + bg="yellow") + self.homepage_label.grid(row=0, column=1, padx=20, pady=25) + + self.start_button = tkinter.Button(self, text="Start Game", + command=self.StartGame, fg="blue") + self.start_button.grid(row=1, column=1, padx=100, pady=50) + + self.rules_button = tkinter.Button(self, text="Rules", + command=self.ShowRule, + fg="red") + self.rules_button.grid(row=2, column=1, padx=100, pady=50) + + self.quit_button = tkinter.Button(self, text="Quit", + command=self.QuitGame, + fg="purple") + self.quit_button.grid(row=3, column=1, padx=100, pady=50) + + def StartGame(self): + self.rules_button.grid_forget() + self.quit_button.grid_forget() + self.homepage_label.grid_forget() + self.start_button.grid_forget() + self.startgame_label = tkinter.Label(self, + text="Whom do you want to play against?", + font=("courier", 15), fg="red", + bg="yellow") + self.startgame_label.grid(row=0, column=1, padx=20, pady=25) + self.pvp_button = tkinter.Button(self, text="2 Player Mode", + command=lambda: pvp_app.PlayerGame( + self)) + self.pvp_button.grid(row=2, column=1, padx=100, pady=50) + + self.back_s_button = tkinter.Button(self, text="Back", + command=self.back_startGame) + self.back_s_button.grid(row=4, column=1, padx=100, pady=50) + + def ShowRule(self): + self.homepage_label.grid_forget() + self.start_button.grid_forget() + self.rules_button.grid_forget() + self.quit_button.grid_forget() + self.rules_label = tkinter.Label(self, + text="Game for two players,X and O,\nwho " + "take turns marking the spaces\nin a " + "3x3 grid.The player who\nsucceeds in " + "placing three of their marks\nin a " + "horizontal,vertical\nor diagonal row " + "wins the game.", + font=("pursia", 15), fg="red", + bg="green") + self.rules_label.grid(row=0, column=1, padx=45, pady=35) + self.back_r_button = tkinter.Button(self, text="Back", + command=self.back_rules) + self.back_r_button.grid(row=2, column=1, padx=100, pady=50) + + def QuitGame(self): + self.message = tkinter.messagebox.askquestion("Exit", + "Do you want to exit ?") + if self.message == 'yes': + appl.destroy() + + def back_rules(self): + self.rules_label.grid_forget() + self.back_r_button.grid_forget() + self.ShowHomepage() + + def back_startGame(self): + self.pvp_button.grid_forget() + self.back_s_button.grid_forget() + self.startgame_label.grid_forget() + self.ShowHomepage() + + +# Below lines are no longer necessary +# root = Tk() +# root.title("Tic Tac Toe") +# root.geometry("500x530") +# root.config(bg="green") +# leaving in case it's changed to this implementation type +appl = MainGUI() +appl.mainloop() diff --git a/Code-Sleep-Python/Inception TicTacToe/requirements.txt b/Code-Sleep-Python/Inception TicTacToe/requirements.txt new file mode 100644 index 0000000..5d6fce4 --- /dev/null +++ b/Code-Sleep-Python/Inception TicTacToe/requirements.txt @@ -0,0 +1 @@ +tkinter diff --git a/Code-Sleep-Python/Koch Curve/README.md b/Code-Sleep-Python/Koch Curve/README.md new file mode 100644 index 0000000..8b3d8cd --- /dev/null +++ b/Code-Sleep-Python/Koch Curve/README.md @@ -0,0 +1,7 @@ +### Koch Curve + +A Fractal is geometrical figure, each part of which has the same statistical character as the whole. Koch Curve (also known as the **Koch snowflake**) is a mathematical fractal curve constructed recursively using an equilateral triangle (See figure). The progression for the area of the snowflake converges to 1.6 times the area of the original triangle, while the progression for the snowflake's perimeter diverges to infinity. Consequently, the snowflake has a finite area bounded by an infinitely long line. **[more info](https://en.wikipedia.org/wiki/Koch_snowflake)** + +This program traces out a 4 level Koch curve. + +![](https://upload.wikimedia.org/wikipedia/commons/f/fd/Von_Koch_curve.gif) \ No newline at end of file diff --git a/Code-Sleep-Python/Link Shortener/README.md b/Code-Sleep-Python/Link Shortener/README.md new file mode 100644 index 0000000..ea51e58 --- /dev/null +++ b/Code-Sleep-Python/Link Shortener/README.md @@ -0,0 +1,23 @@ + + +

Link Shortener

+ +

+ Python Application | 5 lines of code +
+
+

+

+ +You can create a `Python` program which can be used to shorten a big links. We'll use a shortening web service named `tinyurl`. You need to give your link in the terminal and you'll get the shorten link in the print-screen. + ``` +What the program does? + +- You've to give your big link in the terminal +- Program will use tinyurl server for shortening the link without using any browser +- Shortened link will pass by print() function +``` +### Requirements + +* Python +* Python Libraries: `pyshorteners` diff --git a/Code-Sleep-Python/Link Shortener/source-code.py b/Code-Sleep-Python/Link Shortener/source-code.py new file mode 100644 index 0000000..da3aaf8 --- /dev/null +++ b/Code-Sleep-Python/Link Shortener/source-code.py @@ -0,0 +1,8 @@ +import pyshorteners + +link = input("enter the link:") +shortener = pyshorteners.Shortener() + +x = shortener.tinyurl.short(link) + +print(x) diff --git a/Code-Sleep-Python/Prime/README.md b/Code-Sleep-Python/Prime/README.md new file mode 100644 index 0000000..8ff7ac4 --- /dev/null +++ b/Code-Sleep-Python/Prime/README.md @@ -0,0 +1,5 @@ +### Prime number finder + +The implementation of Sieve of Eratosthenes is used to find prime numbers. + +![](https://i.pinimg.com/564x/cc/c7/55/ccc7554b4ae9ee9781b752832224f3ef--sieve-of-eratosthenes-prime-factorization.jpg) \ No newline at end of file diff --git a/Code-Sleep-Python/Prime/code.py b/Code-Sleep-Python/Prime/code.py index 447b6ac..04f8e9e 100644 --- a/Code-Sleep-Python/Prime/code.py +++ b/Code-Sleep-Python/Prime/code.py @@ -65,12 +65,12 @@ def sieve_eratosthenes(range_to): def is_prime(num): """ - Returns true is the number is prime. + Returns true is the number is prime. - To check if a number is prime, we need to check - all its divisors upto only sqrt(number). + To check if a number is prime, we need to check + all its divisors upto only sqrt(number). - Reference: https://stackoverflow.com/a/5811176/7213370 + Reference: https://stackoverflow.com/a/5811176/7213370 """ # corner case. 1 is not a prime diff --git a/Code-Sleep-Python/Prime/sieve_of_eratosthenes.py b/Code-Sleep-Python/Prime/sieve_of_eratosthenes.py new file mode 100644 index 0000000..fc60370 --- /dev/null +++ b/Code-Sleep-Python/Prime/sieve_of_eratosthenes.py @@ -0,0 +1,154 @@ +import pygame +import tkinter +import math # importing modules +pygame.init() +num = 0 +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) +GREEN = (0, 255, 0) +MAUVE = (224, 176, 255) # colour tuples to be used later in the program +clock = pygame.time.Clock() + + +def get_num(m, n): + global num + num = int(n.get()) # gets value of num from Tkinter GUI + m.destroy() # destroys root window + + +def text_objects(text, font): + ''' + Function to create TextSurface and TextRect objects for + displaying text on the PyGame window. + It takes 2 parameters: + text : the text to be displayed + font : pygame.font.Font object in which the text is to be rendered + ''' + textSurface = font.render(text, True, BLACK) + return textSurface, textSurface.get_rect() + + +def message_display(text, x, y, size): + ''' + Function to display the given 'text' message + at a position of (x,y) in size 'size' + ''' + largeText = pygame.font.Font('freesansbold.ttf', size) + TextSurf, TextRect = text_objects(text, largeText) + TextRect.center = (x, y) + display.blit(TextSurf, TextRect) + pygame.display.update() + + +class Cell: # creating a class for Cell objects on the grid + def __init__(self, x, y, n): + self.pos = (x, y) + self.value = n + self.highlighted = False + # adding the number and cell pair to the celldict dictionary + celldict[self.value] = self + # display the value of the cell on the grid at the center of the cell + message_display(f"{self.value}", x + 16, y + 16, 17) + + def highlight(self): + if not self.highlighted: + x, y = self.pos + # create a MAUVE rectangle on top of the cell to highlight + # composite numbers + pygame.draw.rect(display, MAUVE, (x, y, 32, 32)) + # rewrite the value of the cell on top of the MAUVE highlight + message_display(f"{self.value}", x + 16, y + 16, 17) + # to avoid time to re-highlight cells that have already been + # highlighted + self.highlighted = True + # for the effect of moving highlight or "scanning" the grid + pygame.time.wait(50) + + +# getting user input from GUI +m = tkinter.Tk() # root window +l1 = tkinter.Label(m, text='Enter a number', width=25) # label widget +n = tkinter.Entry(m) # entry widget + +# calculate button bounded to get_num function +btn = tkinter.Button(m, text='Calculate', command=lambda: get_num(m, n)) +l1.pack() +n.pack() +btn.pack() # using pack() geometry manager +m.mainloop() # start GUI + +# setting up grid +sq_num = num +if (math.floor(math.sqrt(num))**2 - num != 0): + # getting nearest square greater than or equal to num + sq_num = (math.floor(math.sqrt(num)) + 1)**2 +dim = int(sq_num**0.5) # number of rows and columns of the window + +# creating a window having 'dim' rows and columns. Each cell has width of 32px +width = 32 * dim +display = pygame.display.set_mode((width, width)) +display.fill(WHITE) # fill the display with WHITE color + +for i in range(0, width, 32): + pygame.draw.line(display, BLACK, (i, 0), (i, width) + ) # drawing row lines 32px apart +for j in range(0, width, 32): + # drawing column lines 32px apart + pygame.draw.line(display, BLACK, (0, j), (width, j)) +pygame.display.update() + +celldict = {} # dictionary to map numbers to their respective cells + +count = 1 +for i in range(0, width, 32): + # to deal with internal PyGame events in the event queue which cause the + # system to freeze + pygame.event.pump() + for j in range(0, width, 32): + if (count <= num): + # create a Cell object at every grid intersection + cell = Cell(j, i, count) + clock.tick() + count += 1 + else: + break +pygame.display.update() +# Sieving algorithm +# all the numbers except 1 since 1 is neither prime nor composite +nums = set(range(2, num + 1)) +composites = {1} # set of composites detected so far +celldict[1].highlight() # highlight the Cell 1 + +for i in range( + 2, + round( + math.sqrt(num)) + + 1): # check all numbers till sqrt(num) + if i not in composites: + # cross out all the multiples of prime numbers + comp = [i * k for k in range(2, num // i + 1)] + composites.update(comp) + for val in comp: + pygame.event.pump() + celldict[val].highlight() # highlight the composites + +primetxt = '' # string of primes to be displayed +for val, cell in celldict.items(): + pygame.event.pump() + if not cell.highlighted: # if the cell has not been highlighted + # it is prime + x, y = cell.pos + # highlight the primes with GREEN + pygame.draw.rect(display, GREEN, (x, y, 32, 32)) + message_display(f"{val}", x + 16, y + 16, 17) + pygame.time.wait(100) # to create a moving highlight + primetxt += str(val) + ' ,' # concatenate primes to primetxt string + +# Displaying results using GUI +m = tkinter.Tk() # root window +l1 = tkinter.Label(m, text='Primes that were sieved: ') +# Message widget to display the sieved primes +msg = tkinter.Message(m, text=primetxt[:-1], width=200) +l1.pack() +msg.pack() +m.mainloop() diff --git a/Code-Sleep-Python/Snake/requirements.txt b/Code-Sleep-Python/Snake/requirements.txt new file mode 100644 index 0000000..0cb7ff1 --- /dev/null +++ b/Code-Sleep-Python/Snake/requirements.txt @@ -0,0 +1 @@ +pygame diff --git a/Code-Sleep-Python/Snake/snakegame.py b/Code-Sleep-Python/Snake/snakegame.py index 336073e..9a38ffa 100644 --- a/Code-Sleep-Python/Snake/snakegame.py +++ b/Code-Sleep-Python/Snake/snakegame.py @@ -2,79 +2,85 @@ import random import sys from pygame.locals import * -def collide(x1,x2,y1,y2,wh): - w1=20; - w2=wh; - h2=wh; - h1=20; - if x1+w1>x2 and x1y2 and y1 x2 and x1 < x2+w2 and y1+h1 > y2 and y1 < y2+h2: + return True + else: + return False + + def die(screen, score): - f=pygame.font.SysFont('Monospace',30); - t=f.render('YOUR SCORE IS : '+str(score),True,(0,0,0)); - screen.blit(t,(10,270)); - pygame.display.update(); - pygame.time.wait(2000); - sys.exit(0) -xs=[290,290,290,290,290]; -ys=[290,270,250,230,210]; -dirs=0; -score=0; -applepos=(random.randint(0,590),random.randint(0,590)); -pygame.init(); -s=pygame.display.set_mode((600,600)); -pygame.display.set_caption('SNAKE'); -appleimage=pygame.Surface((10,10)); -appleimage.fill((0,255,0)); -img=pygame.Surface((20,20)); -img.fill((255,0,0)); -f=pygame.font.SysFont('Monospace',20); -clock=pygame.time.Clock() + f = pygame.font.SysFont('Monospace', 30) + t = f.render('YOUR SCORE IS : '+str(score), True, (0, 0, 0)) + screen.blit(t, (10, 270)) + pygame.display.update() + pygame.time.wait(2000) + sys.exit(0) + + +xs = [290, 290, 290, 290, 290] +ys = [290, 270, 250, 230, 210] +dirs = 0 +score = 0 +applepos = (random.randint(0, 590), random.randint(0, 590)) +pygame.init() +s = pygame.display.set_mode((600, 600)) +pygame.display.set_caption('SNAKE') +appleimage = pygame.Surface((10, 10)) +appleimage.fill((0, 255, 0)) +img = pygame.Surface((20, 20)) +img.fill((255, 0, 0)) +f = pygame.font.SysFont('Monospace', 20) +clock = pygame.time.Clock() while True: - clock.tick(10) - for e in pygame.event.get(): - if e.type==QUIT: - sys.exit(0) - elif e.type==KEYDOWN: - if e.key==K_UP and dirs!=0: - dirs=2 - elif e.key==K_DOWN and dirs!=2: - dirs=0 - elif e.key==K_LEFT and dirs!=1: - dirs=3 - elif e.key==K_RIGHT and dirs!=3: - dirs=1 - i=len(xs)-1 - while i>=2: - if collide(xs[0],xs[i],ys[0],ys[i],20): - die(s,score) - i-=1 - if collide(xs[0],applepos[0],ys[0],applepos[1],10): - score+=1; - xs.append(700); - ys.append(700); - applepos=(random.randint(0,590),random.randint(0,590)) - if xs[0] < 0 or xs[0] > 580 or ys[0] < 0 or ys[0] > 580: - die(s,score) - i=len(xs)-1 - while i >= 1: - xs[i]=xs[i-1]; - ys[i]=ys[i-1]; - i-=1 - if dirs==0: - ys[0]+=20 - elif dirs==1: - xs[0]+=20 - elif dirs==2: - ys[0]-=20 - elif dirs==3: - xs[0]-=20 - s.fill((255,255,255)) - for i in range(0,len(xs)): - s.blit(img,(xs[i],ys[i])) - s.blit(appleimage,applepos); - t=f.render(str(score),True,(0,0,0)); - s.blit(t,(10,10)); - pygame.display.update() + clock.tick(10) + for e in pygame.event.get(): + if e.type == QUIT: + sys.exit(0) + elif e.type == KEYDOWN: + if e.key == K_UP and dirs != 0: + dirs = 2 + elif e.key == K_DOWN and dirs != 2: + dirs = 0 + elif e.key == K_LEFT and dirs != 1: + dirs = 3 + elif e.key == K_RIGHT and dirs != 3: + dirs = 1 + i = len(xs)-1 + while i >= 2: + if collide(xs[0], xs[i], ys[0], ys[i], 20): + die(s, score) + i -= 1 + if collide(xs[0], applepos[0], ys[0], applepos[1], 10): + score += 1 + xs.append(700) + ys.append(700) + applepos = (random.randint(0, 590), random.randint(0, 590)) + if xs[0] < 0 or xs[0] > 580 or ys[0] < 0 or ys[0] > 580: + die(s, score) + i = len(xs)-1 + while i >= 1: + xs[i] = xs[i-1] + ys[i] = ys[i-1] + i -= 1 + if dirs == 0: + ys[0] += 20 + elif dirs == 1: + xs[0] += 20 + elif dirs == 2: + ys[0] -= 20 + elif dirs == 3: + xs[0] -= 20 + s.fill((255, 255, 255)) + for i in range(0, len(xs)): + s.blit(img, (xs[i], ys[i])) + s.blit(appleimage, applepos) + t = f.render(str(score), True, (0, 0, 0)) + s.blit(t, (10, 10)) + pygame.display.update() diff --git a/Code-Sleep-Python/Superellipse/README.md b/Code-Sleep-Python/Superellipse/README.md new file mode 100644 index 0000000..7bce417 --- /dev/null +++ b/Code-Sleep-Python/Superellipse/README.md @@ -0,0 +1,7 @@ +### Superellipse + +A superellipse, also known as a Lamé curve after Gabriel Lamé, is a closed curve resembling the ellipse, retaining the geometric features of semi-major axis and semi-minor axis, and symmetry about them, but a different overall shape. + +**[more info](https://en.wikipedia.org/wiki/Superellipse)** + +![](https://upload.wikimedia.org/wikipedia/en/2/24/Superellipse_anim.gif) \ No newline at end of file diff --git a/Code-Sleep-Python/chatbot/code.py b/Code-Sleep-Python/chatbot/code.py new file mode 100644 index 0000000..9949058 --- /dev/null +++ b/Code-Sleep-Python/chatbot/code.py @@ -0,0 +1,38 @@ +import speech_recognition as sr +import os +import subprocess +from gtts import gTTS + +r = sr.Recognizer() + +with sr.Microphone() as source: + r.adjust_for_ambient_noise(source) + print("Say something!") + audio = r.listen(source) + print("Got the speech. Now processing...") + +# recognize speech using Wit.ai +# export your wit.ai key to your environment before running this program +WIT_AI_KEY = os.getenv("WITAIKEY") +if not WIT_AI_KEY: + print("API key not available") + exit() + +in_speech = "" +try: + in_speech = r.recognize_wit(audio, key=WIT_AI_KEY) + print("You said " + in_speech) +except sr.UnknownValueError: + print("Wit.ai could not understand audio") +except sr.RequestError as e: + print("Could not request results from Wit.ai service; {0}".format(e)) + +# in_speech contains the string of the input audio. +# It can be processed and actions can be performed based on it. +# TODO implement actions based on keywords +# Suggestions: Utilise wit.ai for proper NLP + +if (in_speech): + tts = gTTS(text=in_speech, lang="en") + tts.save("sample.mp3") + subprocess.Popen(["mpg123", "-q", "sample.mp3"]).wait() diff --git a/Code-Sleep-Python/chatbot/requirements.txt b/Code-Sleep-Python/chatbot/requirements.txt new file mode 100644 index 0000000..5b169ec --- /dev/null +++ b/Code-Sleep-Python/chatbot/requirements.txt @@ -0,0 +1,4 @@ +gTTS==2.0.0 +gTTS-token==1.1.1 +SpeechRecognition==3.8.1 +pyaudio==0.2.11 diff --git a/Code-Sleep-Python/connect_four/README.md b/Code-Sleep-Python/connect_four/README.md new file mode 100644 index 0000000..38ea418 --- /dev/null +++ b/Code-Sleep-Python/connect_four/README.md @@ -0,0 +1,3 @@ +This connect four game was created using the following tutorial: + +https://www.youtube.com/watch?v=UYgyRArKDEs&list=PLFCB5Dp81iNV_inzM-R9AKkZZlePCZdtV diff --git a/Code-Sleep-Python/connect_four/code.py b/Code-Sleep-Python/connect_four/code.py new file mode 100644 index 0000000..c1b42d6 --- /dev/null +++ b/Code-Sleep-Python/connect_four/code.py @@ -0,0 +1,158 @@ +import numpy as np +import math +import pygame +import sys + +NB_COL = 7 +NB_ROW = 6 +BLUE = (0, 0, 255) # RGB value +BLACK = (0, 0, 0) +RED = (255, 0, 0) +YELLOW = (255, 255, 0) + + +def make_board(): + board = np.zeros((NB_ROW, NB_COL)) + return board + + +def drop_piece(board, row, col, piece): + board[row][col] = piece + + +def is_valid_location(board, col): + return board[NB_ROW-1][col] == 0 + + +def get_next_open_row(board, col): + for r in range(NB_ROW): + if board[r][col] == 0: + return r + + +def print_board(board): + print(np.flip(board, 0)) + + +def winning_move(baord, piece): + # Check hozizontal locations for win + for c in range(NB_COL-3): + for r in range(NB_ROW): + if ( + board[r][c] == piece and board[r][c+1] == piece and + board[r][c+2] == piece and board[r][c+3] == piece + ): + return True + # Check verticle locations for win + for c in range(NB_COL): + for r in range(NB_ROW-3): + if ( + board[r][c] == piece and board[r+1][c] == piece and + board[r+2][c] == piece and board[r+3][c] == piece + ): + return True + # check for positively sloped diags + for c in range(NB_COL-3): + for r in range(NB_ROW-3): + if( + board[r][c] == piece and board[r+1][c+1] == piece and + board[r+2][c+2] == piece and board[r+3][c+3] == piece + ): + return True + # check for negitively sloped diags + for c in range(NB_COL-3): + for r in range(3, NB_ROW): + if( + board[r][c] == piece and board[r-1][c+1] == piece and + board[r-2][c+2] == piece and board[r-3][c+3] == piece + ): + return True + + +def draw_board(board): + for c in range(NB_COL): + for r in range(NB_ROW): + pygame.draw.rect(screen, BLUE, + (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, + SQUARESIZE, SQUARESIZE)) + pygame.draw.circle(screen, BLACK, + (int(c*SQUARESIZE+SQUARESIZE/2), + int(r*SQUARESIZE+1.5*SQUARESIZE)), RADIUS) + + for c in range(NB_COL): + for r in range(NB_ROW): + if board[r][c] == 1: + pygame.draw.circle(screen, RED, + (int(c*SQUARESIZE+SQUARESIZE/2), + height-int(r*SQUARESIZE+SQUARESIZE/2)), + RADIUS) + elif board[r][c] == 2: + pygame.draw.circle(screen, YELLOW, + (int(c*SQUARESIZE+SQUARESIZE/2), + height-int(r*SQUARESIZE+SQUARESIZE/2)), + RADIUS) + pygame.display.update() + + +board = make_board() +game_over = False +turn = 0 + +pygame.init() + +SQUARESIZE = 100 # in pixels + +width = NB_COL*SQUARESIZE +height = (NB_ROW+1)*SQUARESIZE # extra row for piece + +size = (width, height) +RADIUS = int(SQUARESIZE/2-5) +screen = pygame.display.set_mode(size) +draw_board(board) +pygame.display.update() +myfont = pygame.font.SysFont('monospace', 75) + +while not game_over: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + sys.exit() + if event.type == pygame.MOUSEMOTION: + pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE)) + pos_x = event.pos[0] + if turn == 0: + pygame.draw.circle(screen, RED, + (pos_x, int(SQUARESIZE/2)), RADIUS) + else: + pygame.draw.circle(screen, YELLOW, + (pos_x, int(SQUARESIZE/2)), RADIUS) + pygame.display.update() + if event.type == pygame.MOUSEBUTTONDOWN: + pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE)) + if turn is 0: + pos_x = event.pos[0] + col = int(math.floor(pos_x/SQUARESIZE)) + if is_valid_location(board, col): + row = get_next_open_row(board, col) + drop_piece(board, row, col, 1) + # Adds winning condition + if winning_move(board, 1): + label = myfont.render('player 1 wins!', 1, RED) + screen.blit(label, (40, 10)) + game_over = True + # ask for player 2 input + else: + pos_x = event.pos[0] + col = int(math.floor(pos_x/SQUARESIZE)) + if is_valid_location(board, col): + row = get_next_open_row(board, col) + drop_piece(board, row, col, 2) + if winning_move(board, 2): + label = myfont.render('player 2 wins!', 1, YELLOW) + screen.blit(label, (40, 10)) + game_over = True + draw_board(board) + turn += 1 + turn = turn % 2 # resets turn to zero to allow player 1 to go + + if game_over: + pygame.time.wait(3000) diff --git a/Code-Sleep-Python/connect_four/requirements.txt b/Code-Sleep-Python/connect_four/requirements.txt new file mode 100644 index 0000000..1fbac36 --- /dev/null +++ b/Code-Sleep-Python/connect_four/requirements.txt @@ -0,0 +1,2 @@ +numpy==1.22.0 +pygame==1.9.3 diff --git a/Code-Sleep-Python/connect_four/simple_connect_4.py b/Code-Sleep-Python/connect_four/simple_connect_4.py new file mode 100644 index 0000000..f44e11d --- /dev/null +++ b/Code-Sleep-Python/connect_four/simple_connect_4.py @@ -0,0 +1,97 @@ +import numpy as np +# Creates grid to be filled + +NB_COL = 7 +NB_ROW = 6 + + +def make_board(): + board = np.zeros((NB_ROW, NB_COL)) + return board + + +def drop_piece(board, row, col, piece): + board[row][col] = piece + + +def is_valid_location(board, col): + return board[NB_ROW-1][col] == 0 + + +def get_next_open_row(board, col): + for r in range(NB_ROW): + if board[r][col] == 0: + return r + + +def print_board(board): + print(np.flip(board, 0)) + + +def winning_move(baord, piece): + # Check hozizontal locations for win + for c in range(NB_COL-3): + for r in range(NB_ROW): + if ( + board[r][c] == piece and board[r][c+1] == piece and + board[r][c+2] == piece and board[r][c+3] == piece + ): + return True + # Check verticle locations for win + for c in range(NB_COL): + for r in range(NB_ROW-3): + if ( + board[r][c] == piece and board[r+1][c] == piece and + board[r+2][c] == piece and board[r+3][c] == piece + ): + return True + # check for positively sloped diags + for c in range(NB_COL-3): + for r in range(NB_ROW-3): + if ( + board[r][c] == piece and board[r+1][c+1] == piece and + board[r+2][c+2] == piece and board[r+3][c+3] == piece + ): + return True + # check for negitively sloped diags + for c in range(NB_COL-3): + for r in range(3, NB_ROW): + if ( + board[r][c] == piece and board[r-1][c+1] == piece and + board[r-2][c+2] == piece and board[r-3][c+3] == piece + ): + return True + +board = make_board() +game_over = False +turn = 0 + +print_board(board) +while not game_over: + # ask player 1 input + if turn is 0: + col = int(input('Player 1 make your Selection (0-6):')) + # ask for player 2 input + if is_valid_location(board, col): + row = get_next_open_row(board, col) + drop_piece(board, row, col, 1) + # Adds winning condition + if winning_move(board, 1): + print('player 1 wins!') + game_over = True + print_board(board) + break + else: + col = int(input('Player 2 make your Selection (0-6):')) + if is_valid_location(board, col): + row = get_next_open_row(board, col) + drop_piece(board, row, col, 2) + if winning_move(board, 2): + print('player 2 wins!') + game_over = True + print_board(board) + break + + print_board(board) + turn += 1 + turn = turn % 2 # resets turn to zero to allow player 1 to go diff --git a/Code-Sleep-Python/floating_text/README.md b/Code-Sleep-Python/floating_text/README.md new file mode 100644 index 0000000..5bfdecb --- /dev/null +++ b/Code-Sleep-Python/floating_text/README.md @@ -0,0 +1,5 @@ +### Floating Text + +Floating Text is a simple program which displays a given String as a floating string on the terminal. + +![demo](/Code-Sleep-Python/floating_text/floating_text.gif) diff --git a/Code-Sleep-Python/primitiveBlockChain/Blockchain-Structure.png b/Code-Sleep-Python/primitiveBlockChain/Blockchain-Structure.png new file mode 100644 index 0000000..2e1914f Binary files /dev/null and b/Code-Sleep-Python/primitiveBlockChain/Blockchain-Structure.png differ diff --git a/Code-Sleep-Python/primitiveBlockChain/README.md b/Code-Sleep-Python/primitiveBlockChain/README.md new file mode 100644 index 0000000..3ebf2e6 --- /dev/null +++ b/Code-Sleep-Python/primitiveBlockChain/README.md @@ -0,0 +1,3 @@ +# Primitive BlockChain Implementation + +![Blockchain-Structure.png](Blockchain-Structure.png) \ No newline at end of file diff --git a/Code-Sleep-Python/primitiveBlockChain/darkCoin.py b/Code-Sleep-Python/primitiveBlockChain/darkCoin.py new file mode 100644 index 0000000..51f51a2 --- /dev/null +++ b/Code-Sleep-Python/primitiveBlockChain/darkCoin.py @@ -0,0 +1,61 @@ +#!/bin/python3 +# Primitive implementaion of BlockChain Concept + +import hashlib as hasher +import datetime as date + +# Block structure + + +class Block(): + def __init__(self, index, timestamp, data, previous_hash): + self.index = index + self.timestamp = timestamp + self.data = data + self.previous_hash = previous_hash + self.hash = self.hashBlock() + +# Create hash of block + def hashBlock(self): + sha = hasher.sha256() + sha.update((str(self.index) + + str(self.timestamp) + + str(self.data) + + str(self.previous_hash)).encode()) + return sha.hexdigest() + + +# Create genesis block + +def createGenesisBlock(): + return Block(0, date.datetime.now(), "Genesis Block", "0") + +# Create chain of blocks + + +def nextBlock(lastBlock): + id = lastBlock.index + 1 + timeStp = date.datetime.now() + data = "Block number: " + str(id) + hash256 = lastBlock.hash + return Block(id, timeStp, data, hash256) + + +# Create blockchain and add genesis block + +blockchain = [createGenesisBlock()] +previousBlock = blockchain[0] + + +# How many blocks to add after genesis block +noOfBlocks = 20 + +# Add blocks to chain +for i in range(0, noOfBlocks): + # print(f"i value: {i}") + addBlock = nextBlock(previousBlock) + blockchain.append(addBlock) + previousBlock = addBlock + # Broadcast + print(f"Block #{addBlock.index} has been added to blockchain!") + print(f"Hash: {addBlock.hash} \n") diff --git a/Code-Sleep-Python/regression/Logistic_regression_in_Tensorflow.ipynb b/Code-Sleep-Python/regression/Logistic_regression_in_Tensorflow.ipynb new file mode 100644 index 0000000..a6773f1 --- /dev/null +++ b/Code-Sleep-Python/regression/Logistic_regression_in_Tensorflow.ipynb @@ -0,0 +1,288 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Logistic regression with Tensorflow\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import tensorflow as tf\n", + "s = tf.InteractiveSession()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Logistic regression\n", + "\n", + "Plan:\n", + "* Use a shared variable for weights\n", + "* Use a matrix placeholder for `X`\n", + " \n", + "train on a two-class MNIST dataset\n", + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "y [shape - (360,)]: [0 1 0 1 0 1 0 0 1 1]\n", + "X [shape - (360, 64)]:\n" + ] + } + ], + "source": [ + "from sklearn.datasets import load_digits\n", + "mnist = load_digits(2)\n", + "\n", + "X, y = mnist.data, mnist.target\n", + "\n", + "print(\"y [shape - %s]:\" % (str(y.shape)), y[:10])\n", + "print(\"X [shape - %s]:\" % (str(X.shape)))" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "X:\n", + " [[ 0. 0. 5. 13. 9. 1. 0. 0. 0. 0.]\n", + " [ 0. 0. 0. 12. 13. 5. 0. 0. 0. 0.]\n", + " [ 0. 0. 1. 9. 15. 11. 0. 0. 0. 0.]]\n", + "y:\n", + " [0 1 0 1 0 1 0 0 1 1]\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAPgAAAD8CAYAAABaQGkdAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAACxNJREFUeJzt3fuLXPUZx/HPp5vErRqTYqxKNjShaEAqNZqmhIjQBEus\nokJL3YCWSmGhoCiGihZL239A0h+KIFErmBpsVBDrBVsVK6QxF1M1txKDJRvURLwHTLLm6Q87gShp\n92zmnO+ZeXy/YHEvw36fQd45Z2ZnztcRIQA5fa3tAQA0h8CBxAgcSIzAgcQIHEiMwIHECBxIjMCB\nxAgcSGxKE790mk+JQZ3WxK9u1dissvfpnHPeL7bWvoMzi601OHqk2FpxZKzYWiV9poM6HIc80e0a\nCXxQp+n7XtbEr27Vez9eXHS9X61cW2yt32y+ptha59/2drG1xt55t9haJW2Iv1e6HafoQGIEDiRG\n4EBiBA4kRuBAYgQOJEbgQGIEDiRWKXDby23vsr3b9h1NDwWgHhMGbntA0h8lXSHpAkkrbF/Q9GAA\nulflCL5I0u6I2BMRhyWtlVTudY0ATlqVwGdL2nvc16Od7wHocbW92cT2iKQRSRrUqXX9WgBdqHIE\n3ydpznFfD3W+9wURcW9ELIyIhVN1Sl3zAehClcA3SjrP9jzb0yQNS3qi2bEA1GHCU/SIGLN9k6Rn\nJQ1Iuj8itjU+GYCuVXoMHhFPSXqq4VkA1IxXsgGJETiQGIEDiRE4kBiBA4kROJAYgQOJETiQWCM7\nm2RVcqcRSRqe/kGxtVbN/LTYWn/d8myxtS753S+LrSVJs+5dX3S9iXAEBxIjcCAxAgcSI3AgMQIH\nEiNwIDECBxIjcCAxAgcSq7Kzyf2299t+o8RAAOpT5Qj+J0nLG54DQAMmDDwiXpL0foFZANSMx+BA\nYmxdBCRW2xGcrYuA3sMpOpBYlT+TPSxpvaT5tkdt/6L5sQDUocreZCtKDAKgfpyiA4kROJAYgQOJ\nETiQGIEDiRE4kBiBA4kROJBY329dNLb0kmJrDU/fWmwtSbpi+XCxtWa8trPYWj99eVmxtd5f8Hmx\ntSRpVtHVJsYRHEiMwIHECBxIjMCBxAgcSIzAgcQIHEiMwIHECBxIjMCBxKpcdHGO7Rdsb7e9zfYt\nJQYD0L0qr0Ufk7QyIrbYni5ps+3nImJ7w7MB6FKVvcnejogtnc8/kbRD0uymBwPQvUm9m8z2XEkL\nJG04wc/YugjoMZWfZLN9uqRHJd0aER9/+edsXQT0nkqB256q8bjXRMRjzY4EoC5VnkW3pPsk7YiI\nu5sfCUBdqhzBl0i6QdJS21s7Hz9qeC4ANaiyN9nLklxgFgA145VsQGIEDiRG4EBiBA4kRuBAYgQO\nJEbgQGIEDiTW93uTfXZmubtw1/4Li60lSUcL7hdW0sbXv932CF8ZHMGBxAgcSIzAgcQIHEiMwIHE\nCBxIjMCBxAgcSIzAgcSqXHRx0PYrtv/V2bro9yUGA9C9Kq/zPCRpaUR82rl88su2n46IfzY8G4Au\nVbnoYkj6tPPl1M5HNDkUgHpU3fhgwPZWSfslPRcRJ9y6yPYm25uO6FDdcwI4CZUCj4jPI+IiSUOS\nFtn+zgluw9ZFQI+Z1LPoEfGhpBckLW9mHAB1qvIs+lm2Z3Y+/7qkyyXlfKMykEyVZ9HPlfSg7QGN\n/4PwSEQ82exYAOpQ5Vn01zS+JziAPsMr2YDECBxIjMCBxAgcSIzAgcQIHEiMwIHECBxIrP+3LvpG\nuX+j1qxfXGwtSTpfrxRdr5QpMw4XW2vso2nF1upFHMGBxAgcSIzAgcQIHEiMwIHECBxIjMCBxAgc\nSIzAgcQqB965NvqrtrkeG9AnJnMEv0XSjqYGAVC/qjubDEm6UtLqZscBUKeqR/BVkm6XdLTBWQDU\nrMrGB1dJ2h8Rmye4HXuTAT2myhF8iaSrbb8laa2kpbYf+vKN2JsM6D0TBh4Rd0bEUETMlTQs6fmI\nuL7xyQB0jb+DA4lN6oouEfGipBcbmQRA7TiCA4kROJAYgQOJETiQGIEDiRE4kBiBA4kROJBY329d\nNPhBuTe4fe/CN4utJUkfFVxryjlnF1vrugv+7/uWavXI05cWW6sXcQQHEiNwIDECBxIjcCAxAgcS\nI3AgMQIHEiNwIDECBxKr9Eq2zhVVP5H0uaSxiFjY5FAA6jGZl6r+ICLea2wSALXjFB1IrGrgIelv\ntjfbHmlyIAD1qXqKfmlE7LP9TUnP2d4ZES8df4NO+COSNKhTax4TwMmodASPiH2d/+6X9LikRSe4\nDVsXAT2myuaDp9mefuxzST+U9EbTgwHoXpVT9LMlPW772O3/HBHPNDoVgFpMGHhE7JH03QKzAKgZ\nfyYDEiNwIDECBxIjcCAxAgcSI3AgMQIHEiNwILG+37rojF3lNvj57dCTxdaSpJ+N3FZsranXHii2\nVknz7lzf9git4ggOJEbgQGIEDiRG4EBiBA4kRuBAYgQOJEbgQGIEDiRWKXDbM22vs73T9g7bi5se\nDED3qr5U9Q+SnomIn9ieJnHhc6AfTBi47RmSLpP0c0mKiMOSDjc7FoA6VDlFnyfpgKQHbL9qe3Xn\n+ugAelyVwKdIuljSPRGxQNJBSXd8+Ua2R2xvsr3piA7VPCaAk1El8FFJoxGxofP1Oo0H/wVsXQT0\nngkDj4h3JO21Pb/zrWWStjc6FYBaVH0W/WZJazrPoO+RdGNzIwGoS6XAI2KrpIUNzwKgZrySDUiM\nwIHECBxIjMCBxAgcSIzAgcQIHEiMwIHECBxIrO/3Jjv62s5ia113z8pia0nSXSsfLrbWqjeXFVtr\n40UDxdb6quMIDiRG4EBiBA4kRuBAYgQOJEbgQGIEDiRG4EBiBA4kNmHgtufb3nrcx8e2by0xHIDu\nTPhS1YjYJekiSbI9IGmfpMcbngtADSZ7ir5M0psR8Z8mhgFQr8m+2WRY0gnfAWF7RNKIJA2y+SjQ\nEyofwTubHlwt6S8n+jlbFwG9ZzKn6FdI2hIR7zY1DIB6TSbwFfofp+cAelOlwDv7gV8u6bFmxwFQ\np6p7kx2UdGbDswCoGa9kAxIjcCAxAgcSI3AgMQIHEiNwIDECBxIjcCAxR0T9v9Q+IGmybymdJem9\n2ofpDVnvG/erPd+KiLMmulEjgZ8M25siYmHbczQh633jfvU+TtGBxAgcSKyXAr+37QEalPW+cb96\nXM88BgdQv146ggOoWU8Ebnu57V22d9u+o+156mB7ju0XbG+3vc32LW3PVCfbA7Zftf1k27PUyfZM\n2+ts77S9w/bitmfqRuun6J1rrf9b41eMGZW0UdKKiNje6mBdsn2upHMjYovt6ZI2S7q23+/XMbZv\nk7RQ0hkRcVXb89TF9oOS/hERqzsXGj01Ij5se66T1QtH8EWSdkfEnog4LGmtpGtanqlrEfF2RGzp\nfP6JpB2SZrc7VT1sD0m6UtLqtmepk+0Zki6TdJ8kRcThfo5b6o3AZ0vae9zXo0oSwjG250paIGlD\nu5PUZpWk2yUdbXuQms2TdEDSA52HH6s71yPsW70QeGq2T5f0qKRbI+Ljtufplu2rJO2PiM1tz9KA\nKZIulnRPRCyQdFBSXz8n1AuB75M057ivhzrf63u2p2o87jURkeWKtEskXW37LY0/nFpq+6F2R6rN\nqKTRiDh2prVO48H3rV4IfKOk82zP6zypMSzpiZZn6ppta/yx3I6IuLvteeoSEXdGxFBEzNX4/6vn\nI+L6lseqRUS8I2mv7fmdby2T1NdPik52b7LaRcSY7ZskPStpQNL9EbGt5bHqsETSDZJet721871f\nR8RTLc6Eid0saU3nYLNH0o0tz9OV1v9MBqA5vXCKDqAhBA4kRuBAYgQOJEbgQGIEDiRG4EBiBA4k\n9l+8Q5/pEyhkXAAAAABJRU5ErkJggg==\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "print('X:\\n',X[:3,:10])\n", + "print('y:\\n',y[:10])\n", + "plt.imshow(X[0].reshape([8,8]));" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's your turn now!\n", + "Just a small reminder of the relevant math:\n", + "\n", + "$$\n", + "P(y=1|X) = \\sigma(X \\cdot W + b)\n", + "$$\n", + "$$\n", + "\\text{loss} = -\\log\\left(P\\left(y_\\text{predicted} = 1\\right)\\right)\\cdot y_\\text{true} - \\log\\left(1 - P\\left(y_\\text{predicted} = 1\\right)\\right)\\cdot\\left(1 - y_\\text{true}\\right)\n", + "$$\n", + "\n", + "$\\sigma(x)$ is available via `tf.nn.sigmoid` and matrix multiplication via `tf.matmul`" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, random_state=42)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Your code goes here.__ For the training and testing scaffolding to work, please stick to the names in comments." + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Model parameters - weights and bias\n", + "weights = tf.get_variable(shape=(X.shape[1], 1), dtype=tf.float64,name=\"w\")\n", + "b=tf.Variable(0,dtype=tf.float64,name='bias')" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Placeholders for the input data\n", + "input_X = tf.placeholder('float64', shape=(None, X.shape[1]))\n", + "input_y = tf.placeholder('float64')" + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# The model code\n", + "\n", + "# Compute a vector of predictions, resulting shape should be [input_X.shape[0],]\n", + "# This is 1D, if you have extra dimensions, you can get rid of them with tf.squeeze .\n", + "# Don't forget the sigmoid.\n", + "predicted_y = tf.squeeze(tf.nn.sigmoid(tf.matmul(input_X,weights)+b))\n", + "\n", + "# Loss. Should be a scalar number - average loss over all the objects\n", + "# tf.reduce_mean is your friend here\n", + "loss = tf.reduce_mean(-input_y * tf.log(predicted_y)-(1-input_y) * tf.log(1-predicted_y))\n", + " #\n", + "\n", + "# See above for an example. tf.train.*Optimizer\n", + "optimizer = tf.train.MomentumOptimizer(0.01, 0.5).minimize(loss)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A test to help with the debugging" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "validation_weights = 1e-3 * np.fromiter(map(lambda x:\n", + " s.run(weird_psychotic_function, {my_scalar:x, my_vector:[1, 0.1, 2]}),\n", + " 0.15 * np.arange(1, X.shape[1] + 1)),\n", + " count=X.shape[1], dtype=np.float32)[:, np.newaxis]\n", + "# Compute predictions for given weights and bias\n", + "prediction_validation = s.run(\n", + " predicted_y, {\n", + " input_X: X,\n", + " weights: validation_weights,\n", + " b: 1e-1})\n", + "\n", + "# Load the reference values for the predictions\n", + "validation_true_values = np.loadtxt(\"validation_predictons.txt\")\n", + "\n", + "assert prediction_validation.shape == (X.shape[0],),\\\n", + " \"Predictions must be a 1D array with length equal to the number \" \\\n", + " \"of examples in input_X\"\n", + "assert np.allclose(validation_true_values, prediction_validation)\n", + "loss_validation = s.run(\n", + " loss, {\n", + " input_X: X[:100],\n", + " input_y: y[-100:],\n", + " weights: validation_weights+1.21e-3,\n", + " b: -1e-1})\n", + "assert np.allclose(loss_validation, 0.728689)" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "loss at iter 0:0.4043\n", + "train auc: 0.948232323232\n", + "test auc: 0.980731225296\n", + "loss at iter 1:1.2870\n", + "train auc: 0.973429951691\n", + "test auc: 0.991600790514\n", + "loss at iter 2:0.1875\n", + "train auc: 0.993302591129\n", + "test auc: 1.0\n", + "loss at iter 3:0.0827\n", + "train auc: 0.997419850681\n", + "test auc: 1.0\n", + "loss at iter 4:0.0921\n", + "train auc: 0.998407992973\n", + "test auc: 1.0\n" + ] + } + ], + "source": [ + "from sklearn.metrics import roc_auc_score\n", + "s.run(tf.global_variables_initializer())\n", + "for i in range(5):\n", + " s.run(optimizer, {input_X: X_train, input_y: y_train})\n", + " loss_i = s.run(loss, {input_X: X_train, input_y: y_train})\n", + " print(\"loss at iter %i:%.4f\" % (i, loss_i))\n", + " print(\"train auc:\", roc_auc_score(y_train, s.run(predicted_y, {input_X:X_train})))\n", + " print(\"test auc:\", roc_auc_score(y_test, s.run(predicted_y, {input_X:X_test})))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Code-Sleep-Python/regression/requirements.txt b/Code-Sleep-Python/regression/requirements.txt new file mode 100644 index 0000000..bc325ab --- /dev/null +++ b/Code-Sleep-Python/regression/requirements.txt @@ -0,0 +1,5 @@ +numpy==1.22.0 +pandas==0.21.0 +matplotlib==2.1.0 +scikit-learn==0.19.1 +tensorflow >= 1.0 diff --git a/Code-Sleep-Python/social_network/README.md b/Code-Sleep-Python/social_network/README.md new file mode 100644 index 0000000..139129f --- /dev/null +++ b/Code-Sleep-Python/social_network/README.md @@ -0,0 +1,5 @@ +### Social Network Analysis + +Homophily is a network characteristic. Homophily occurs when nodes that share an edge share a characteristic more often than nodes that do not share an edge. In this case study, we will investigate homophily of several characteristics of individuals connected in social networks in rural India. + +![](https://images.pond5.com/social-media-animation-after-effect-046838541_iconm.jpeg) \ No newline at end of file diff --git a/Code-Sleep-Python/social_network/code.py b/Code-Sleep-Python/social_network/code.py index 862266a..da3bd1f 100644 --- a/Code-Sleep-Python/social_network/code.py +++ b/Code-Sleep-Python/social_network/code.py @@ -1,5 +1,16 @@ import pandas as pd -df = pd.read_stata(data_filepath + "individual_characteristics.dta") +from os import getcwd +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument('-d', '--data_filepath', help="""Select the directory where + is stored the file. Default is the current directory.""", + default=getcwd()) + +args = parser.parse_args() +data_filepath = args.data_filepath + +df = pd.read_stata(data_filepath + "individual_characteristics.dta") df1 = df[df.village == 1] df2 = df[df.village == 2] @@ -7,29 +18,30 @@ df1.head() -sex1 = {df1.pid[i] : df1.resp_gend[i] for i in range(len(df1.pid))} -caste1 = {df1.pid[i] : df1.caste[i] for i in range(len(df1.pid))} -religion1 = {df1.pid[i] : df1.religion[i] for i in range(len(df1.pid))} +def get_params(dfx, elem, items_range): + return {dfx.pid[i]: elem[i] for i in items_range} + +sex1 = get_params(df1, df1.resp_gend, range(len(df1.pid))) +caste1 = get_params(df1, df1.caste, range(len(df1.pid))) +religion1 = (df1, df1.religion, range(len(df1.pid))) + # Continue for df2 as well. j = 203 -sex2 = {df2.pid[j] : df2.resp_gend[j] for j in range(203,406)} -caste2 = {df2.pid[j] : df2.caste[j] for j in range(203,406) } -religion2 = {df2.pid[j] : df2.religion[j] for j in range(203,406)} - +sex2 = get_params(df2, df2.resp_gend, range(203, 406)) +caste2 = get_params(df2, df2.caste, range(203, 406)) +religion2 = (df2, df2.religion, range(203, 406)) -from collections import Counter def chance_homophily(chars): # Enter code here! z = set(chars.values()) su = 0 for c in z: - - su = su + pow((sum(x == c for x in chars.values())/len(chars) * 1.0),2) - + su = su + pow((sum(x == c for x in chars.values())/len(chars) * 1), 2) return su + favorite_colors = { "ankit": "red", "xiaoyu": "blue", @@ -40,7 +52,6 @@ def chance_homophily(chars): print(color_homophily) - print("Village 1 chance of same sex:", chance_homophily(sex1)) # Enter your code here. print("Village 1 chance of same caste:", chance_homophily(caste1)) @@ -51,6 +62,31 @@ def chance_homophily(chars): print("Village 2 chance of same caste:", chance_homophily(caste2)) +def checks_for_homophility(nodes, G, chars, IDs): + + num_ties = 0; + num_same_ties = 0; + n1 = nodes[0] + n2 = nodes[1] + + if n1 <= n2: + return num_ties, num_same_ties + + # do not double-count edges! + if (IDs[n1] in chars and IDs[n2] in chars) == False: + return num_ties, num_same_ties + + if G.has_edge(n1, n2) == False: + return num_ties, num_same_ties + + # Should `num_ties` be incremented? + # What about `num_same_ties`? + num_ties = 1 + if chars[IDs[n1]] == chars[IDs[n2]]: + num_same_ties = 1 + + return num_ties, num_same_ties + def homophily(G, chars, IDs): """ @@ -61,26 +97,25 @@ def homophily(G, chars, IDs): num_same_ties, num_ties = 0, 0 for n1 in G.nodes(): for n2 in G.nodes(): - if n1 > n2: # do not double-count edges! - if IDs[n1] in chars and IDs[n2] in chars: - if G.has_edge(n1, n2): - # Should `num_ties` be incremented? What about `num_same_ties`? - num_ties += 1 - if chars[IDs[n1]] == chars[IDs[n2]]: + nodes = [n1, n2] + ties, same_ties = check_for_homophily(nodes, G, chars, IDs) - return (num_same_ties / num_ties) - - -print("Village 1 observed proportion of same sex:", homophily(G1, sex1, pid1)) -print("Village 1 observed proportion of same caste:", homophily(G1, caste1, pid1)) -print("Village 1 observed proportion of same religion:", homophily(G1, religion1, pid1)) -# Enter your code here! -print("Village 2 observed proportion of same sex:", homophily(G2, sex2, pid2)) -print("Village 2 observed proportion of same caste:", homophily(G2, caste2, pid2)) -print("Village 2 observed proportion of same religion:", homophily(G1, religion2, pid2)) - + num_ties += ties + num_same_ties += same_ties + return (num_same_ties / num_ties) +print("Village 1 observed proportion of same sex:", homophily(G1, sex1, pid1)) +print("Village 1 observed proportion of same caste:", + homophily(G1, caste1, pid1)) +print("Village 1 observed proportion of same religion:", + homophily(G1, religion1, pid1)) +# Enter your code here! +print("Village 2 observed proportion of same sex:", homophily(G2, sex2, pid2)) +print("Village 2 observed proportion of same caste:", + homophily(G2, caste2, pid2)) +print("Village 2 observed proportion of same religion:", + homophily(G1, religion2, pid2)) diff --git a/Code-Sleep-Python/speech-to-text/README.md b/Code-Sleep-Python/speech-to-text/README.md new file mode 100644 index 0000000..3fc2dbe --- /dev/null +++ b/Code-Sleep-Python/speech-to-text/README.md @@ -0,0 +1,39 @@ +# Speech-To-Text + +Simple Script to get User input from microphone and use Google's API to transform into text. + +# Installation + +Install python-pyaudio: + +``` +sudo apt-get install python-pyaudio +``` + +Install portaudio: + +``` +sudo apt-get install portaudio19-dev +``` + +Sadly, the PyAudio is not updated and doesn't work on the latest version of Python3 so: + +``` +virtualenv -p python2.7 req +source req/bin/activate +pip install PyAudio +pip install SpeechRecognition +``` + +# Test the app: + +``` +source req/bin/activate +python stt.py +``` + +# TODO: + +- Find a way to make this work for Python3. + +- Add new recognition APIs. \ No newline at end of file diff --git a/Code-Sleep-Python/speech-to-text/requirements.txt b/Code-Sleep-Python/speech-to-text/requirements.txt new file mode 100644 index 0000000..cf7df45 --- /dev/null +++ b/Code-Sleep-Python/speech-to-text/requirements.txt @@ -0,0 +1,2 @@ +PyAudio==0.2.11 +SpeechRecognition==3.8.1 diff --git a/Code-Sleep-Python/speech-to-text/stt.py b/Code-Sleep-Python/speech-to-text/stt.py new file mode 100644 index 0000000..96dcfed --- /dev/null +++ b/Code-Sleep-Python/speech-to-text/stt.py @@ -0,0 +1,17 @@ +import speech_recognition as sr + +r = sr.Recognizer() +flag = 1 +while flag=1: + + with sr.Microphone() as source: + print("Say something... ") + audio = r.listen(source) + + try: + print("Google thinks you said: {}".format(r.recognize_google(audio))) + flag = 0 + except sr.UnkownValueError: + print("Couldn't understand your voice. Please speak again.") + except sr.RequestError as e: + print("Couldn't request results. Please speak again.; {}".format(e)) diff --git a/Code-Sleep-Python/tests b/Code-Sleep-Python/tests new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Code-Sleep-Python/tests @@ -0,0 +1 @@ + diff --git a/Code-Sleep-Python/text-to-speech/README.md b/Code-Sleep-Python/text-to-speech/README.md new file mode 100644 index 0000000..a53c692 --- /dev/null +++ b/Code-Sleep-Python/text-to-speech/README.md @@ -0,0 +1,22 @@ +# Text-To-Speech + +This code uses the gtts library to read a textinput and create an mp3 file. Very simple but very cool. + +Create a virtualenv using python3 and install the requirements with: + +``` +virtualenv -p python3 req +source req/bin/activate +pip install -r requirements.txt +``` + +To run the app just do: +``` +python tts.py +``` + +For the first version the text is just hard coded inside the file but next step is to make the app take an optional input like: + +``` +python tts.py -t "Some random text that we want in an mp3 file" +``` diff --git a/Code-Sleep-Python/text-to-speech/requirements.txt b/Code-Sleep-Python/text-to-speech/requirements.txt new file mode 100644 index 0000000..5e87ccb --- /dev/null +++ b/Code-Sleep-Python/text-to-speech/requirements.txt @@ -0,0 +1,11 @@ +beautifulsoup4==4.6.0 +bs4==0.0.1 +certifi==2018.4.16 +chardet==3.0.4 +click==6.7 +gTTS==2.0.0 +gTTS-token==1.1.1 +idna==2.6 +requests>=2.20.0 +six==1.11.0 +urllib3>=1.23 diff --git a/Code-Sleep-Python/text-to-speech/tts.py b/Code-Sleep-Python/text-to-speech/tts.py new file mode 100644 index 0000000..6507dfc --- /dev/null +++ b/Code-Sleep-Python/text-to-speech/tts.py @@ -0,0 +1,5 @@ +from gtts import gTTS + +text = input("Enter the text you want to convert: ") +tts = gTTS(text=text, lang='en') +tts.save("speech.mp3") diff --git a/Code-Sleep-Python/tic-tac-toe/README.md b/Code-Sleep-Python/tic-tac-toe/README.md new file mode 100644 index 0000000..48a570d --- /dev/null +++ b/Code-Sleep-Python/tic-tac-toe/README.md @@ -0,0 +1,7 @@ +### Tic-Tac-Toe + +Tic-Tac-Toe (or noughts and crosses) is a simple strategy game in which two players take turns placing a mark on a 3x3 board, attempting to make a row, column, or diagonal of three with their mark. In this homework, we will use the tools we've covered in the past two weeks to create a Tic-Tac-Toe simulator and evaluate basic winning strategies. + +![](https://upload.wikimedia.org/wikipedia/commons/8/8e/TicTacToe-6549127nnXOp.gif) + +Players soon discover that best play from both parties leads to a draw. Because of the simplicity of Tic-Tac-Toe, it is often used as a pedagogical tool for teaching the concepts of good sportsmanship and the branch of artificial intelligence that deals with the searching of game trees. It is straightforward to write a computer program to play Tic-Tac-Toe perfectly, to enumerate the 765 essentially different positions (the state space complexity), or the 26.830 possible games up to rotations and reflections (the game tree complexity) on this space. \ No newline at end of file diff --git a/Code-Sleep-Python/tic-tac-toe/code.py b/Code-Sleep-Python/tic-tac-toe/code.py index 8c433e2..66ab0f0 100644 --- a/Code-Sleep-Python/tic-tac-toe/code.py +++ b/Code-Sleep-Python/tic-tac-toe/code.py @@ -1,28 +1,44 @@ import numpy as np +import random +import time +import matplotlib.pyplot as plt + + def create_board(): - x = np.zeros((3,3)) + x = np.zeros((3, 3)) return x board = create_board() + +def place(board, player, position): + if board[position] == 0: + board[position] = player + return board + + def possibilities(board): - y = np.where(board == 0 ) #it gives the indices wherever there are zeros in the form of 2 seperate arrays in a tuple. (array([0, 0, 1, 1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2, 0, 1, 2])) - y= np.array(y) # convert it into array. - z=list(map(tuple, np.transpose(y))) #transpose it to get [0,1],[0,2],[1,0] ... and so on. Then using map function convert each of them to tuple. And keep it totally as a list. + # it gives the indices wherever there are zeros in the form of 2 seperate + # arrays in a tuple. + # (array([0, 0, 1, 1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2, 0, 1, 2])) + y = np.where(board == 0) + y = np.array(y) + z = list(map(tuple, np.transpose(y))) + # transpose it to get [0,1],[0,2],[1,0] + # ... and so on. Then using map function convert each of them to tuple. + # And keep it totally as a list. return z -#selection=possibilities(board) -#print (y) -def random_place(board,player): + + +def random_place(board, player): position = random.choice(possibilities(board)) - #print (position) + # print (position) return place(board, player, position) -board = random_place(board,2) +board = random_place(board, 2) -# row_win -# write your code here! -def row_win(board,player): +def row_win(board, player): for i in range(3): if(player == board[i][0]): if((player == board[i][1]) and (player == board[i][2])): @@ -31,15 +47,11 @@ def row_win(board,player): print("False") else: print("False") - -row_win(board,1) - -# ccol_win -# write your code here! + +row_win(board, 1) -# write your code here! -def col_win(board,player): +def col_win(board, player): for i in range(3): if(player == board[0][i]): if((player == board[1][i]) and (player == board[2][i])): @@ -48,15 +60,11 @@ def col_win(board,player): print("False") else: print("False") - -col_win(board,1) + +col_win(board, 1) -#diag_win -# write your code here! -# write your code here! -# write your code here! -def diag_win(board,player): +def diag_win(board, player): z = 0 for i in range(3): if(player == board[i][i]): @@ -65,42 +73,40 @@ def diag_win(board,player): print("True") else: print("False") - -diag_win(board,1) + +diag_win(board, 1) -## Evaluate +# Evaluate def evaluate(board): winner = 0 for player in [1, 2]: - # Check if `row_win`, `col_win`, or `diag_win` apply. if so, store `player` as `winner`. - if(row_win(board,player)== True or col_win(board,player)== True): + # Check if `row_win`, `col_win`, or `diag_win` apply. + # if so, store `player` as `winner`. + if (row_win(board, player) is True or col_win(board, player) is True): winner = player - if(diag_win(board,player)== True): + if(diag_win(board, player) is True): winner = player if np.all(board != 0) and winner == 0: winner = -1 return winner -# add your code here. evaluate(board) -## play_game() +# play_game() def play_game(): - board= create_board() + + board = create_board() if(0 in board): player = 1 - random_place(board,player) + random_place(board, player) z = evaluate(board) player = 2 - return z - -# plot -import time -import matplotlib.pyplot as plt + +# plot R = 1000 ty = [] r = [] @@ -108,8 +114,8 @@ def play_game(): for i in range(R): z = play_game() r.append(z) - -e = time.time() + +e = time.time() c = e-s print(c) @@ -120,30 +126,29 @@ def play_game(): # play strategic def play_strategic_game(): board, winner = create_board(), 0 - board[1,1] = 1 + board[1, 1] = 1 while winner == 0: - for player in [2,1]: + for player in [2, 1]: # use `random_place` to play a game, and store as `board`. - board =random_place(board,player) + board = random_place(board, player) # use `evaluate(board)`, and store as `winner`. winner = evaluate(board) if winner != 0: break return winner -play_strategic_game() +play_strategic_game() + # plotting play-strategic-game # write your code here! -import time - R = 1000 s = time.time() z = [] for i in range(R): k = play_strategic_game() z.append(k) - + e = time.time() x = [z[j] for j in range(R)] diff --git a/Code-Sleep-Python/tic-tac-toe/requirements.txt b/Code-Sleep-Python/tic-tac-toe/requirements.txt index 297540b..e2ebf76 100644 --- a/Code-Sleep-Python/tic-tac-toe/requirements.txt +++ b/Code-Sleep-Python/tic-tac-toe/requirements.txt @@ -1 +1 @@ -numpy==1.13.3 \ No newline at end of file +numpy==1.22.0 \ No newline at end of file diff --git a/Code-Sleep-Python/translation_hamlet/README.md b/Code-Sleep-Python/translation_hamlet/README.md new file mode 100644 index 0000000..6405e71 --- /dev/null +++ b/Code-Sleep-Python/translation_hamlet/README.md @@ -0,0 +1,5 @@ +### Translations of Hamlet + +In this case study, we will find and plot the distribution of word frequencies for each translation of Hamlet. Perhaps the distribution of word frequencies of Hamlet depends on the translation. + +![](http://www.aboutlanguageschools.com/images/language-translations.jpg) \ No newline at end of file diff --git a/Code-Sleep-Python/voice assistant/friday.py b/Code-Sleep-Python/voice assistant/friday.py new file mode 100644 index 0000000..dd5ae31 --- /dev/null +++ b/Code-Sleep-Python/voice assistant/friday.py @@ -0,0 +1,92 @@ +import pyttsx3 +import datetime +import speech_recognition as sr +import wikipedia +import webbrowser +import subprocess +import os + +engine = pyttsx3.init('sapi5') +voices = engine.getProperty('voices') +# print(voices[0].id) +engine.setProperty('voice', voices[0].id) + + +def speak(audio): + engine.say(audio) + engine.runAndWait() + + +def wishMe(): + hour = int(datetime.datetime.now().hour) + if hour >= 0 and hour < 12: + speak("good morning sir") + elif hour >= 12 and hour < 18: + speak("good afternoon sir") + else: + speak("Good evening sir") + + speak("I am Friday, your virtual assistant running on python?") + speak("How may I help you?") + +def takeCommand(): + r = sr.Recognizer() + with sr.Microphone() as source: + print("Listening..") + r.pause_threshold = 1 + audio = r.listen(source) + + try: + print("Recognizing...") + query = r.recognize_google(audio, language='en-in') + print(f"User said: {query}\n") + except Exception as e: + print(e) + + print("Please repeat your command..") + return "None" + return query + + +if __name__ == "__main__": + wishMe() +while True: + query = takeCommand().lower() + + if 'wikipedia' in query: + speak('Searching wikipedia...') + query = query.replace("wikipedia", "") + results = wikipedia.summary(query, sentences=1) + speak("According to what i found on wikipedia") + print(results) + speak(results) + elif 'what can you do' in query: + speak("I can search for something in wikipedia,") + speak("open websites, play friends or even open your whatsapp.") + speak("If you are interested to read some amazing blogs say open my blog.") + elif 'who are you' in query: + speak("I am friday, the successor of Jarvis.") + elif 'open youtube' in query: + webbrowser.open("youtube.com") + elif 'open google' in query: + webbrowser.open("google.com") + elif 'open instagram' in query: + webbrowser.open("instagram.com") + elif 'open my blog' in query: + webbrowser.open("codehustler.dev") + elif 'open stackoverflow' in query: + webbrowser.open("stackoverflow.com") + elif 'the time' in query: + strTime = datetime.datetime.now().strftime("%H:%M:%S") + speak(f"Sir, the time is {strTime}") + elif 'open whatsapp' in query: + subprocess.call( + 'C:\\Users\\hp\\AppData\\Local\\WhatsApp\\WhatsApp.exe') + elif 'play friends' in query: + friends_dir = 'G:\\F.R.I.E.N.D.S' + friends = os.listdir(friends_dir) + print(friends) + os.startfile(os.path.join(friends_dir, friends[0])) + elif 'terminate' in query: + speak("Goodbye sir see you soon.") + exit() diff --git a/Code-Sleep-Python/website_status_check/README.md b/Code-Sleep-Python/website_status_check/README.md new file mode 100644 index 0000000..93f8ed5 --- /dev/null +++ b/Code-Sleep-Python/website_status_check/README.md @@ -0,0 +1,5 @@ +### Website status check + +A simple website crawler to check the return code of a website. It returns with a message indicating whether the website is online, redirected, or not found. + +![](http://yootheme.com/media/docs/assets/images/warp/error_pages_404.jpg) \ No newline at end of file diff --git a/Code-Sleep-Python/website_status_check/website_status_check.py b/Code-Sleep-Python/website_status_check/website_status_check.py index d72fd47..c6b9718 100644 --- a/Code-Sleep-Python/website_status_check/website_status_check.py +++ b/Code-Sleep-Python/website_status_check/website_status_check.py @@ -1,30 +1,103 @@ import requests -# TODO: Add more status code functionality. - def check_url(url): # This function uses status codes to check various states of any website. + # modified to only return the status code + try: + r = requests.get(url) # added spacing for PEP8 + return r.status_code + except requests.ConnectionError: + # added default code in case of failure in the requests library + return 999 + + +def print_message(code): + status_message = { + 100: "Website is slow to respond, but appears ok.", + 101: "Server is upgrading to the requested protocol.", + 102: "Request received, website has yet to respond.", + 103: "Early hints, returns response header preview before the rest " + "of the server's response is ready.", + 200: "Website is online.", + 201: "The request has succeeded and a new resource has been created.", + 202: "The request has been received but not yet acted upon.", + 203: "Website returned meta-information from a copy of the server.", + 204: "There is no content to send for this request.", + 205: "Reset document view which sent this request.", + 206: "Separate download into multiple streams.", + 207: "Website returned XML which could contain multiple status codes.", + 208: "Website issued multiple responses.", + 226: "Website returned a GET response.", + 300: "Website has different choices and cannot be resolved into one.", + 301: "Website has been redirected permanently.", + 302: "Website has been redirected temporarily.", + 303: "Website sent this response to direct the client to get the " + "requested resource at another URI.", + 304: "Website cache has not been modified.", + 305: "Website requested response must be accessed by a proxy.", + 306: "Unused staus code, held for upcoming purpose", + 307: "Website has been redirected temporarily.", + 308: "Website has been redirected permanently.", + 400: "The request could not be understood by the server due to " + "malformed syntax.", + 401: "The request requires user authentication", + 402: "Website requires payment before serving responses.", + 403: "Forbidden. The server understood the request, but is refusing " + "to fulfill it.", + 404: "Website not found!", + 405: "The request method is known by the server but has been " + "disabled and cannot be used.", + 406: "No Content found!", + 407: "Website requires 3rd party authentication.", + 408: "Website request Timed out.", + 409: "Server conflict, please try again.", + 410: "Requested content has been permanently deleted from server.", + 411: 'Website rejected the request because the Content-Length header ' + 'field is not defined.', + 412: "Website doesn't meet client preconditions.", + 413: "Request entity is larger than limits defined by server.", + 414: "The URI requested by the client is too long.", + 415: "The media format of the requested data is not supported by the " + "server.", + 416: "The range specified by the Range header field in the request " + "can't be fulfilled by the website.", + 417: "Data indicated by the Expect request header field can't be met " + "by the server.", + 418: "The server refuses the attempt to brew coffee with a teapot.", + 421: "Website redirection failed.", + 422: "The request failed due to semantic errors.", + 423: "The resource that is being accessed is locked.", + 424: "The request failed due to failure of a previous request.", + 426: "The server refuses to perform the request using the current " + "protocol.", + 428: "Data update conflict.", + 429: "Website refused due to too many requests, please try again " + "later.", + 431: "Request refused due to large size headers.", + 451: "Request refused due to legal reasons.", + 500: "Website is experiencing errors.", + 501: "Unsupported request.", + 502: "Website Gateway error.", + 503: "The web server is unable to handle your HTTP request at the " + "time.", + 504: "Gateway Timeout.", + 505: "HTTP Version Not Supported.", + 506: "The server has an internal configuration error.", + 507: "The server is out of space.", + 508: "The server went to infinity and beyond, but could not return " + "your request.", + 510: "Further extensions to the request are required for the server " + "to fulfill it.", + 511: "Network Authentication Required.", + 999: 'Failed to connect.' + } + print(status_message[code]) - r=requests.get(url) - if r.status_code == 200: - return "Website is online." - elif r.status_code == 300: - return "Website has different choices and cannot be resolved into one" - elif r.status_code == 301: - return "Website has been redirected permanently." - elif r.status_code == 302: - return "Website has been redirected temporarily" - elif r.status_code == 400: - return "The request could not be understood by the server due to malformed syntax" - elif r.status_code == 401: - return "The request requires user authentication" - elif r.status_code == 403: - return "Forbidden. The server understood the request, but is refusing to fulfill it" - elif r.status_code == 404: - return "Website not found!" - elif r.status_code == 503: - return "The web server is unable to handle your HTTP request at the time" +# added extra line for PEP8 url = input("Please enter a website, inclusive of 'http://' > ") -print(check_url(url)) +# created a variable to store the status code +status = check_url(url) +# call new function to print status +print_message(status) diff --git a/Code-Sleep-Python/whisky_classification/README.md b/Code-Sleep-Python/whisky_classification/README.md new file mode 100644 index 0000000..e95410f --- /dev/null +++ b/Code-Sleep-Python/whisky_classification/README.md @@ -0,0 +1,3 @@ +### Whisky Classification + +In this case study, we have prepared step-by-step instructions for you on how to prepare plots in Bokeh, a library designed for simple and interactive plotting. We will demonstrate Bokeh by continuing the analysis of Scotch whiskies.You can go through the article - **[here](http://www.geeksforgeeks.org/project-scikit-learn-whisky-clustering/)** \ No newline at end of file diff --git a/Code-Sleep-Python/whisky_classification/requirements.txt b/Code-Sleep-Python/whisky_classification/requirements.txt index 23b2cc0..cf875d5 100644 --- a/Code-Sleep-Python/whisky_classification/requirements.txt +++ b/Code-Sleep-Python/whisky_classification/requirements.txt @@ -1,2 +1,2 @@ -numpy==1.13.3 +numpy==1.22.0 bokeh==0.12.10 \ No newline at end of file diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md index 31a08c0..de77a08 100644 --- a/ISSUE_TEMPLATE.md +++ b/ISSUE_TEMPLATE.md @@ -1,4 +1,4 @@ -Maintainer: @prateekiiest +Maintainer: [@prateekiiest](https://github.com/prateekiiest) ## DESCRIPTION diff --git a/README.md b/README.md index 8b97581..8654bd2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Code Sleep Python +# Code Sleep Python :snake: ------------------------------------------------- @@ -6,12 +6,15 @@ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/8a2a1adf12034f0ab92d99dac6da7ef8)](https://www.codacy.com/app/prateekkol21/Code-Sleep-Python?utm_source=github.com&utm_medium=referral&utm_content=prateekiiest/Code-Sleep-Python&utm_campaign=badger) [![Build status](https://ci.appveyor.com/api/projects/status/ugq1vwa8045p307g?svg=true)](https://ci.appveyor.com/project/prateekiiest/code-sleep-python) [![Build Status](https://travis-ci.org/prateekiiest/Code-Sleep-Python.svg?branch=master)](https://travis-ci.org/prateekiiest/Code-Sleep-Python) + + [![License MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/LICENSE) [![chat on Slack](https://img.shields.io/badge/chat%20on%20-Slack-blue.svg)](https://join.slack.com/t/code-sleep-python/shared_invite/enQtMzE0NTIwNzY0MTM1LWFhNGY0NWQ0MDIxNjZmMzgyMzlhOTk3YTY4YjQwNjJmOGIyMTZiNzA4MzkwZWE0ZjgyOWQ2MmMzMWJlMDExMjY) [![made with &hearts in Python](https://img.shields.io/badge/made%20with%20%E2%9D%A4%20in-Python-red.svg)](http://shields.io/#your-badge) -#### [Join Slack](https://join.slack.com/t/code-sleep-python/shared_invite/enQtMzE0NTIwNzY0MTM1LWFhNGY0NWQ0MDIxNjZmMzgyMzlhOTk3YTY4YjQwNjJmOGIyMTZiNzA4MzkwZWE0ZjgyOWQ2MmMzMWJlMDExMjY) + +#### [Join Slack](https://join.slack.com/t/code-sleep-python/shared_invite/enQtMzE0NTIwNzY0MTM1LTY2ZDYwMmNiMzM1MDNjMjQzZTcwNGY0YmFjZjczNjIzNmNkZjk3ZTlhOWQyNWUxZjNmMjMxOTM1ODFmYTBjNzE) ![](codesleeppython.png) @@ -25,7 +28,7 @@ This project is for all the **Python lovers** out there. #### Description This repository contains a curated list of some of the awesome small projects made in Python that you can code away this summer. -It includes analysis of different Python modules, a deep analysis of the Python statistics modules and dataframes like Pandas. +It includes analysis of different Python modules, a deep analysis of the Python statistics modules, and dataframes like Pandas. It has some projects on classification, correlation and regression which are the fundamental building blocks of Machine Learning and Neural Networks. @@ -33,6 +36,12 @@ The repository is still under development. Only the source code has been uploade New to Python? Take a look [here](https://github.com/prateekiiest/Code-Sleep-Python#getting-started-with-python). + +## HACKTOBERFEST 2018 + +![](https://raw.githubusercontent.com/prateekiiest/Code-Sleep-Python/master/Screenshot%20(190).png) + + #### Downloading and Running A step-by-step guide to download all the codes from here and test yourself in your local machine. @@ -44,7 +53,9 @@ A step-by-step guide to download all the codes from here and test yourself in yo cd Code-Sleep-python cd Code-Sleep-Python # all the codes are present Here - ipython notebook + pip install jupyterlab + + jupyter notebook ``` This will open a new jupyter notebook in your localhost where you can run all the codes and test it for yourself. @@ -56,206 +67,32 @@ This will open a new jupyter notebook in your localhost where you can run all th ---------------------------------------------------- -## Projects - -* [Tic-Tac-Toe](https://github.com/prateekiiest/Code-Sleep-Python#tic-tac-toe) -* [Hangman](https://github.com/prateekiiest/Code-Sleep-Python#hangman) -* [Caesar-Cipher](https://github.com/prateekiiest/Code-Sleep-Python#caesar-cipher) -* [Translations of Hamlet](https://github.com/prateekiiest/Code-Sleep-Python#translations-of-hamlet) -* [Classification](https://github.com/prateekiiest/Code-Sleep-Python#classification) -* [Whisky Classification](https://github.com/prateekiiest/Code-Sleep-Python#whisky-classification) +#### Code of Conduct [See here](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/CODE_OF_CONDUCT.md) -* [Bird Migration](https://github.com/prateekiiest/Code-Sleep-Python#bird-migration) -* [Social Network Analysis](https://github.com/prateekiiest/Code-Sleep-Python#social-network-analysis) -* [Prime](https://github.com/prateekiiest/Code-Sleep-Python#prime-number-finder) -* [Website status check](https://github.com/prateekiiest/Code-Sleep-Python#website-status-check) -* [Encryption-Techniques](#encryption-techniques) -* [Inception Tic-Tac-Toe](https://github.com/prateekiiest/Code-Sleep-Python#inception-tic-tac-toe) -* [Sprint](https://github.com/prateekiiest/Code-Sleep-Python#sprint) -* [Floating Text](#floating-text) -* [Koch Curve](https://github.com/prateekiiest/Code-Sleep-Python#koch-curve) -* [Superellipse](https://github.com/prateekiiest/Code-Sleep-Python#superellipse) -* [Cricket Notification](https://github.com/prateekiiest/Code-Sleep-Python#cricket-notification) - ----------------------------------- - -### Tic-Tac-Toe - -Tic-Tac-Toe (or noughts and crosses) is a simple strategy game in which two players take turns placing a mark on a 3x3 board, attempting to make a row, column, or diagonal of three with their mark. In this homework, we will use the tools we've covered in the past two weeks to create a Tic-Tac-Toe simulator and evaluate basic winning strategies. - -![](https://upload.wikimedia.org/wikipedia/commons/8/8e/TicTacToe-6549127nnXOp.gif) - -Players soon discover that best play from both parties leads to a draw. Because of the simplicity of Tic-Tac-Toe, it is often used as a pedagogical tool for teaching the concepts of good sportsmanship and the branch of artificial intelligence that deals with the searching of game trees. It is straightforward to write a computer program to play Tic-Tac-Toe perfectly, to enumerate the 765 essentially different positions (the state space complexity), or the 26.830 possible games up to rotations and reflections (the game tree complexity) on this space. - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/tic-tac-toe/code.py)** ----------------------------------- -### Hangman - -Hangman is a simple game where a player will guess a word letter by letter. - -![](http://daramcq.github.io/img/hangman-game-5.png) - -In this project, you will create a program that generates a random word that you must guess. - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Hangman/code.py)** - --------------------------------------------- - -### Caesar-Cipher - -A cipher is a secret code for a language. In this study, we will explore a cipher that is reported by contemporary Greek historians to have been used by Julius Caesar to send secret messages to generals during times of war. - -The Caesar cipher, also known as a shift cipher, is one of the simplest forms of encryption. It is a substitution cipher where each letter in the original message (called the plaintext) is replaced with a letter corresponding to a certain number of letters up or down in the alphabet. - - -In this way, a message that initially was quite readable ends up in a form that can not be understood at a simple glance. - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Caesar-cipher/code.py)** - ------------------------------------------------- - -### Translations of Hamlet - -In this case study, we will find and plot the distribution of word frequencies for each translation of Hamlet. Perhaps the distribution of word frequencies of Hamlet depends on the translation. - -![](http://www.aboutlanguageschools.com/images/language-translations.jpg) +* [Tic-Tac-Toe](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/tic-tac-toe) +* [Hangman](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Hangman) +* [Caesar-Cipher](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Caesar-cipher) +* [Translations of Hamlet](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/translation_hamlet) +* [Classification](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Classification) +* [Whisky Classification](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/whisky_classification) +* [Bird Migration](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Bird_migration) +* [Social Network Analysis](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/social_network) +* [Prime](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Prime) +* [Website status check](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/website_status_check) +* [Encryption-Techniques](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Encryption-Techniques) +* [Inception Tic-Tac-Toe](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Inception%20TicTacToe) +* [Sprint](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Sprint) +* [Floating Text](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/floating_text) +* [Koch Curve](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Koch%20Curve) +* [Superellipse](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Superellipse) +* [Cricket Notification](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Cricket_Notification) -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/translation_hamlet/code.py)** ----------------------------------------------------- -### Classification - -In this case study, we will analyze a dataset consisting of an assortment of wines classified into "high quality" and "low quality", and will use k-Nearest Neighbors to predict whether or not other information about the wine helps us correctly guess whether a new wine will be of high quality. - -![](http://homepages.inf.ed.ac.uk/rbf/HIPR2/classb.gif) - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Classification/code.py)** - ----------------------------------------------- - -### Whisky Classification - -In this case study, we have prepared step-by-step instructions for you on how to prepare plots in Bokeh, a library designed for simple and interactive plotting. We will demonstrate Bokeh by continuing the analysis of Scotch whiskies.You can go through the article - **[here](http://www.geeksforgeeks.org/project-scikit-learn-whisky-clustering/)** - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/whisky_classification/code.py)** - ---------------------------------------------- - -### Bird Migration - -In this case study, we will continue taking a look at patterns of flight for each of the three birds in our dataset.Documentation of this project available - **[here](http://www.geeksforgeeks.org/tracking-bird-migration-using-python-3/)** - -![](https://upload.wikimedia.org/wikipedia/commons/thumb/a/a3/BrantaLeucopsisMigration.jpg/300px-BrantaLeucopsisMigration.jpg) - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Bird_migration/code.py)** - -------------------------------------------------- - -### Social Network Analysis - -Homophily is a network characteristic. Homophily occurs when nodes that share an edge share a characteristic more often than nodes that do not share an edge. In this case study, we will investigate homophily of several characteristics of individuals connected in social networks in rural India. - -![](https://images.pond5.com/social-media-animation-after-effect-046838541_iconm.jpeg) - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/social_network/code.py)** - ----------------------------------------------------- - - -### Prime number finder - -The implementation of Sieve of Eratosthenes is used to find prime numbers. - -![](https://i.pinimg.com/564x/cc/c7/55/ccc7554b4ae9ee9781b752832224f3ef--sieve-of-eratosthenes-prime-factorization.jpg) - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Prime/code.py)** - ----------------------------------------------------- - -### Website status check - -A simple website crawler to check the return code of a website. It returns with a message indicating whether the website is online, redirected, or not found. - -![](http://yootheme.com/media/docs/assets/images/warp/error_pages_404.jpg) - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/website_status_check/website_status_check.py)** - - ----------------------------------------------------- - -### Encryption-Techniques - -Encryption is an interesting piece of technology that works by scrambling data so it is unreadable by unintended parties. The technology comes in many forms, with key size and strength generally being the biggest differences in one variety from the next. This repo has implementations of different encryption techniques. More [here](https://en.wikipedia.org/wiki/Encryption). - -![](http://img.bityard.net/blog/aes.png) - -**[CODE](Encryption-Techniques/)** - ----------------------------------------------------- - ----------------------------------------------------- - -### Inception Tic-Tac-Toe - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Inception%20TicTacToe/inceptionTTT.py)** - ----------------------------------------------------- - -### Sprint - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Sprint/sprint.py)** - ----------------------------------------------------- - -### Floating Text - -Floating Text is a simple program which displays a given String as a floating string on the terminal. - -![demo](/floating_text/floating_text.gif) - -**[CODE](/floating_text/floating_text.py)** - ----------------------------------------------------- - -### Koch Curve - -A Fractal is geometrical figure, each part of which has the same statistical character as the whole. Koch Curve (also known as the **Koch snowflake**) is a mathematical fractal curve constructed recursively using an equilateral triangle (See figure). The progression for the area of the snowflake converges to 1.6 times the area of the original triangle, while the progression for the snowflake's perimeter diverges to infinity. Consequently, the snowflake has a finite area bounded by an infinitely long line. **[more info](https://en.wikipedia.org/wiki/Koch_snowflake)** - -This program traces out a 4 level Koch curve. - -![](https://upload.wikimedia.org/wikipedia/commons/f/fd/Von_Koch_curve.gif) - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Koch%20Curve/koch%20curve.py)** - ----------------------------------------------------- - -### Superellipse - -A superellipse, also known as a Lamé curve after Gabriel Lamé, is a closed curve resembling the ellipse, retaining the geometric features of semi-major axis and semi-minor axis, and symmetry about them, but a different overall shape. - -**[more info](https://en.wikipedia.org/wiki/Superellipse)** - -![](https://upload.wikimedia.org/wikipedia/en/2/24/Superellipse_anim.gif) - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Superellipse/test.py)** - ----------------------------------------------------- - -### Cricket Notification - -A simple program to get the score and match status if India is playing. This information is obtained from the terminal. - -![](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgwxUvr7AfngMuzr4a8tc69jexGPoPeSdCTiDZhvlXqgZTH_wxgg) - -**[CODE](https://github.com/prateekiiest/Code-Sleep-Python/blob/master/Code-Sleep-Python/Cricket_Notification/cricket_notification.py)** - ----------------------------------------------------- - - ----------------------------------------------------- ## Wanna Contribute ? @@ -282,13 +119,15 @@ New to Python? No problem! Take a look at the following resources: - [Python beginners guide](https://wiki.python.org/moin/BeginnersGuide) - [Python course by Google](https://developers.google.com/edu/python/) (online course) +- [Python course by sentdex on YouTube](https://www.youtube.com/playlist?list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M)(online course) - [Learn Python the Hard Way](https://learnpythonthehardway.org/book/) (book) +- [Learn Python Programming](https://www.scaler.com/topics/python) - [MIT: Introduction to Computer Science and Programming in Python](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/) (open courseware) - [Python for Developers](http://ricardoduarte.github.io/python-for-developers/)(book) - [How to Think Like a Computer Scientist](http://openbookproject.net/thinkcs/python/english3e/)(book) - [Byte of Python](https://python.swaroopch.com/)(book) - [Pycharm EDU](https://www.jetbrains.com/pycharm-edu/) - A helpful program that teaches Python. It includes many lessons on basic Python. It also has tests, checks, and hints to help you through each programming activity! - +- [Build applications in Python the anti-textbook](https://github.com/thewhitetulip/build-app-with-python-antitextbook/) - Teaches Python through example and Youtube Screencasts. -------------------------------------- diff --git a/Screenshot (190).png b/Screenshot (190).png new file mode 100644 index 0000000..d318ea2 Binary files /dev/null and b/Screenshot (190).png differ diff --git a/_config.yml b/_config.yml index 277f1f2..03167a7 100644 --- a/_config.yml +++ b/_config.yml @@ -1 +1,3 @@ -theme: jekyll-theme-cayman +theme: jekyll-theme-minimal +plugins: + - jemoji diff --git a/requirements.txt b/requirements.txt index c669e05..495c76f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,5 +6,5 @@ scikit-learn >= 0.19 bokeh >= 0.12 requests >= 2.18 msvcrt >= 0.14.0 - +pygame >= 1.9.6