├── .idea
├── Python-Scripts.iml
├── workspace.xml
└── workspace.xml___jb_tmp___
├── 20200816.jpg
├── 20200830.jpg
├── AutomatedTelegramChannel.py
├── Convert-Ebook-To-Kindle-Format.py
├── Django_project_setup.py
├── README.md
├── TOTP.py
├── ascii_image.txt
├── credit_card_validator.py
├── db-backup-pythonanywhere.py
├── desktop_wallpaper_bing.py
├── image.png
├── image_to_ascii.py
├── india_flag_turtle.py
├── log_cleaner.py
├── merry_christmas_using_python.py
├── news_headlines.py
├── olx-location-scrape.py
├── one_million_websites.py
├── permission.py
├── snake_ladder.py
├── stackoverflow_most_popular_technology.py
├── stopwords.txt
├── system_information.py
├── tkinter_gui_file_upload.py
├── tweets_scrapper.py
├── usa_flag.py
├── vaccine_slot_availability.py
├── whl_file_dl.py
├── who_let_the_dogs_out.mp3
└── word_cloud.py
/.idea/Python-Scripts.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anuragrana/Python-Scripts/fda0186a0d7ba34f152a35107ca10876e9e9a7ec/.idea/workspace.xml
--------------------------------------------------------------------------------
/.idea/workspace.xml___jb_tmp___:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anuragrana/Python-Scripts/fda0186a0d7ba34f152a35107ca10876e9e9a7ec/.idea/workspace.xml___jb_tmp___
--------------------------------------------------------------------------------
/20200816.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anuragrana/Python-Scripts/fda0186a0d7ba34f152a35107ca10876e9e9a7ec/20200816.jpg
--------------------------------------------------------------------------------
/20200830.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anuragrana/Python-Scripts/fda0186a0d7ba34f152a35107ca10876e9e9a7ec/20200830.jpg
--------------------------------------------------------------------------------
/AutomatedTelegramChannel.py:
--------------------------------------------------------------------------------
1 | # Author - Anurag Rana
2 |
3 | from bs4 import BeautifulSoup
4 | import requests
5 | import telegram
6 | from config import telegram_token_news
7 |
8 | def get_news_data(starting_url):
9 | news_data = []
10 | response = requests.get(starting_url)
11 | soup = BeautifulSoup(response.text, 'lxml')
12 | element = soup.find(attrs={"class": "deQdld"})
13 | print(element)
14 | for c_wizi in element:
15 | data = {}
16 | a = c_wizi.find(attrs={"class":"nuEeue hzdq5d ME7ew"})
17 | if a:
18 | try:
19 | link = a.attrs["href"]
20 | text = a.string.strip()
21 | except Exception as e:
22 | print(e)
23 | if link and text:
24 | data["link"] = link
25 | data["text"] = text
26 | news_data.append(data)
27 |
28 | return news_data
29 |
30 |
31 | def get_msg(news_data):
32 | msg = "\n\n\n"
33 | for news_item in news_data:
34 | text = news_item["text"]
35 | link = news_item["link"]
36 | msg += text+' [source]'
37 | msg += "\n\n"
38 |
39 | return msg
40 |
41 |
42 |
43 | bot = telegram.Bot(token=telegram_token_news)
44 |
45 | urls = [
46 | 'https://news.google.com/news/headlines/section/topic/NATION.hi_in/%E0%A4%AD%E0%A4%BE%E0%A4%B0%E0%A4%A4?ned=hi_in&hl=hi',
47 | 'https://news.google.com/news/headlines/section/topic/NATION.en_in/India?ned=in&hl=en-IN',
48 | 'https://news.google.com/news/headlines/section/topic/ENTERTAINMENT.en_in/Entertainment?ned=in&hl=en-IN',
49 | ]
50 |
51 | for url in urls:
52 | news_data = get_news_data(url)
53 | if len(news_data) > 0:
54 | msg = get_msg(news_data)
55 | status = bot.send_message(chat_id="@newsindiachannel", text=msg, parse_mode=telegram.ParseMode.HTML)
56 | if status:
57 | print(status)
58 | else:
59 | print("no new news")
60 |
61 |
62 |
--------------------------------------------------------------------------------
/Convert-Ebook-To-Kindle-Format.py:
--------------------------------------------------------------------------------
1 | #
2 | # Author - Anurag Rana
3 | # Go to this article for more help. http://thepythondjango.com/python-script-1-convert-ebooks-from-epub-to-mobi-format/
4 | #
5 | from os import listdir, rename
6 | from os.path import isfile, join
7 | import subprocess
8 |
9 |
10 | # return name of file to be kept after conversion.
11 | # we are just changing the extension. azw3 here.
12 | def get_final_filename(f):
13 | f = f.split(".")
14 | filename = ".".join(f[0:-1])
15 | processed_file_name = filename+".azw3"
16 | return processed_file_name
17 |
18 |
19 | # return file extension. pdf or epub or mobi
20 | def get_file_extension(f):
21 | return f.split(".")[-1]
22 |
23 |
24 | # list of extensions that needs to be ignored.
25 | ignored_extensions = ["pdf"]
26 |
27 | # here all the downloaded files are kept
28 | mypath = "/home/user/Downloads/ebooks/"
29 |
30 | # path where converted files are stored
31 | mypath_converted = "/home/user/Downloads/ebooks/kindle/"
32 |
33 | # path where processed files will be moved to, clearing the downloaded folder
34 | mypath_processed = "/home/user/Downloads/ebooks/processed/"
35 |
36 | raw_files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
37 | converted_files = [f for f in listdir(mypath_converted) if isfile(join(mypath_converted, f))]
38 |
39 | for f in raw_files:
40 | final_file_name = get_final_filename(f)
41 | extension = get_file_extension(f)
42 | if final_file_name not in converted_files and extension not in ignored_extensions:
43 | print("Converting : "+f)
44 | try:
45 | subprocess.call(["ebook-convert",mypath+f,mypath_converted+final_file_name])
46 | s = rename(mypath+f, mypath_processed+f)
47 | print(s)
48 | except Exception as e:
49 | print(e)
50 | else:
51 | print("Already exists : "+final_file_name)
52 |
--------------------------------------------------------------------------------
/Django_project_setup.py:
--------------------------------------------------------------------------------
1 | #
2 | # Script to perform the basic setup tasks in Django Project
3 | # Author - Anurag Rana
4 | # Homepage - anuragrana.in
5 | #
6 |
7 | import os
8 | import sys
9 | import urllib
10 |
11 | BASE_DIR = os.path.dirname(os.path.abspath(__file__))
12 | PROJECT_NAME = BASE_DIR.split("/")[-1]
13 | ENV_FILE = "this_is_dev_env"
14 |
15 |
16 | def usage():
17 | msg = """
18 | This script automate the mundane tasks of setting up a django project.
19 | usage : python setup.py [param]
20 | Action can take below values:
21 | ip : initiate project. Initialize git in project directory. create gitignore file. Add paths to gitignore file.
22 | creates the environment specific settings files. etc.
23 | {python setup.py ip}
24 | ca : create app. needs appname as another argument. Creates the app. creates the directories and init file in them.
25 | {python setup.py ca appname}
26 |
27 | """
28 | print(msg)
29 |
30 |
31 | def create_logger_settings():
32 | try:
33 | link = "https://gist.githubusercontent.com/anuragrana/151129fb715980dfdef52ca464825087/raw/f12d3f48c32759b36c8e1c73eec37d378e9dfb8b/logger_settings.py"
34 | f = urllib.request.request(link)
35 | myfile = f.read()
36 |
37 | with open(PROJECT_NAME+"/settings.py", 'a+') as fh:
38 | fh.write("\n"+myfile)
39 | fh.write("\n\n")
40 |
41 | except Exception as e:
42 | print(e)
43 |
44 |
45 | def create_gitignore():
46 | gitignore = '.gitignore'
47 | try:
48 | with open(gitignore, 'a+') as fh:
49 | fh.write("./logs\n")
50 | fh.write("./static\n")
51 | fh.write("./media\n")
52 | fh.write("**/*.pyc\n")
53 | fh.write("**/migrations/*\n")
54 | # because we will not commit prod setting file. Copy securely.
55 | fh.write(PROJECT_NAME + "/settings_prod.py\n")
56 | fh.write(PROJECT_NAME + "/" + ENV_FILE + "\n")
57 | except Exception as e:
58 | print(e)
59 |
60 |
61 | def update_settings():
62 | f = open(PROJECT_NAME+"/settings.py", "r")
63 | contents = f.readlines()
64 | f.close()
65 |
66 | index = 0
67 |
68 | for l in contents:
69 | if "ALLOWED_HOSTS" in l:
70 | index = contents.index(l)
71 | break
72 |
73 | msg = "\n\nif os.path.isfile(os.path.join(BASE_DIR,'"+ENV_FILE+"')):\n\tfrom .settings_dev import *"
74 | msg += "\nelse:\n\tfrom .settings_prod import *\n\n"
75 |
76 | contents.insert(index+1, msg)
77 |
78 | f = open(PROJECT_NAME+"/settings.py", "w")
79 | contents = "".join(contents)
80 | f.write(contents)
81 | f.close()
82 |
83 | # add static and media root and urls
84 | with open(PROJECT_NAME + "/settings.py", "a+") as fh:
85 | fh.write("STATIC_ROOT = os.path.join(BASE_DIR, \"static/\")\n")
86 | fh.write("MEDIA_ROOT = os.path.join(BASE_DIR,\"media/\")\n")
87 | fh.write("MEDIA_URL = \"/media/\"\n")
88 |
89 |
90 | def create_env_settings_files():
91 | try:
92 | with open(PROJECT_NAME + "/settings_prod.py", 'w') as fh:
93 | fh.write("DEBUG = False\n")
94 | fh.write('ALLOWED_HOSTS = ["*"]')
95 |
96 | with open(PROJECT_NAME + "/settings_dev.py", 'w') as fh:
97 | fh.write("DEBUG = True\n")
98 | fh.write('ALLOWED_HOSTS = []')
99 | except Exception as e:
100 | print(e)
101 |
102 |
103 | def update_project_urls_file():
104 | try:
105 | with open(PROJECT_NAME + "/urls.py", 'a+') as fh:
106 | fh.write("\n\nfrom django.conf.urls import include\n")
107 | fh.write("from django.conf.urls import handler404, handler500\n")
108 | fh.write("from django.conf import settings\n")
109 | fh.write("from django.conf.urls.static import static\n\n")
110 | fh.write("urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n")
111 | fh.write("#handler404 = views.error_404\n")
112 | fh.write("#handler500 = views.error_500\n\n")
113 |
114 | except Exception as e:
115 | print(e)
116 |
117 |
118 | def init_project():
119 | print("Initializing the project...")
120 |
121 | print("Current working directory: " + BASE_DIR)
122 | print("Name of Project: " + PROJECT_NAME)
123 |
124 | print("Initializing git... ")
125 | os.system("git init")
126 |
127 | print("Creating Environment identification file.")
128 | os.system("touch "+PROJECT_NAME+"/"+ENV_FILE)
129 |
130 | print("creating .gitignore file...")
131 | create_gitignore()
132 |
133 | print("creating different local and prod environment setting files...")
134 | create_env_settings_files()
135 | update_settings()
136 |
137 | print("Creating logs directory...")
138 | os.system("mkdir logs")
139 |
140 | print("Updating project URL file...")
141 | update_project_urls_file()
142 |
143 | create_logger_settings()
144 |
145 | msg = """
146 | Project has been initialized. Please look into your settings files and update the settings accordingly.
147 | """
148 | print(msg)
149 |
150 |
151 | def update_project_urls_file_with_app_url(appname):
152 | try:
153 | with open(PROJECT_NAME + "/urls.py", 'a+') as fh:
154 | fh.write("urlpatterns += [\n")
155 | fh.write(" url(r'^"+appname+"/', include('"+appname+".urls', namespace='"+appname+"')),\n")
156 | fh.write("]")
157 |
158 | except Exception as e:
159 | print(e)
160 |
161 |
162 | def create_app_urls(appname):
163 | try:
164 | with open(appname + "/urls.py", 'a+') as fh:
165 | fh.write("from django.conf.urls import url\n")
166 | fh.write("from "+appname+" import views\n")
167 | except Exception as e:
168 | print(e)
169 |
170 |
171 | def create_app():
172 | if len(sys.argv) < 3:
173 | print("\nERROR: Please mention the name of app as well\n\n")
174 | usage()
175 | sys.exit(1)
176 | appname = sys.argv[2]
177 | print("Creating new app '" + appname + "' ...")
178 | os.system("python manage.py startapp " + appname)
179 |
180 | print("creating app URLs file")
181 | create_app_urls(appname)
182 |
183 | print("updating project URL file")
184 | update_project_urls_file_with_app_url(appname)
185 |
186 | list_dirs = ["models", "views", "forms", "services", "utilities", "templatetags"]
187 |
188 | for directory in list_dirs:
189 | print("Creating " + directory + " directory...")
190 | os.system("mkdir " + appname + "/" + directory)
191 | os.system("touch " + appname + "/" + directory + "/__init__.py")
192 |
193 | print("Creating templates directory...")
194 | os.system("mkdir -p " + appname + "/templates/" + appname + "/")
195 |
196 | print("Creating static directory...")
197 | list_static_dirs = ["img", "css", "js"]
198 | for directory in list_static_dirs:
199 | os.system("mkdir -p " + appname + "/static/" + appname + "/"+directory)
200 |
201 | print("Renaming unnecessary files...")
202 | os.rename(appname + "/views.py", appname + "/views.py.backup")
203 | os.rename(appname + "/models.py", appname + "/models.py.backup")
204 |
205 |
206 | def start():
207 | action = sys.argv[1]
208 |
209 | if "ip" == action:
210 | # ip - initialize project
211 | init_project()
212 | elif "ca" == action:
213 | # ca - create app
214 | create_app()
215 | elif "help" == action:
216 | # help - show usage
217 | usage()
218 |
219 |
220 | start()
221 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Python-Scripts
2 | A Collection of Python scripts developed by me to Automate the mundane tasks.
3 | Appropriate comments are placed in scripts to help understand them.
4 |
5 | --------------------------
6 |
7 | To understand how to use these scripts, visit : https://www.pythoncircle.com
8 |
9 |
10 |
--------------------------------------------------------------------------------
/TOTP.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding: utf-8
3 |
4 | #
5 | # this file was generated from jupter notebook
6 | # refer https://pythoncircle.com/post/731/implementing-2fa-in-python-django-using-time-based-one-time-password-totp/
7 | #
8 |
9 |
10 | # In[1]:
11 |
12 |
13 | # length of OTP in digits
14 | length = 6
15 | # timestep or time-window for which the token is valid
16 | step_in_seconds = 30
17 |
18 | import base64
19 |
20 | # randon key
21 | key = b"123123123djwkdhawjdk"
22 | token = base64.b32encode(key)
23 | print(token.decode("utf-8"))
24 |
25 |
26 | # In[4]:
27 |
28 |
29 | import hashlib
30 | import hmac
31 | import math
32 | import time
33 |
34 | t = math.floor(time.time() // step_in_seconds)
35 |
36 | hmac_object = hmac.new(key, t.to_bytes(length=8, byteorder="big"), hashlib.sha1)
37 | hmac_sha1 = hmac_object.hexdigest()
38 | offset = int(hmac_sha1[-1], 16)
39 | binary = int(hmac_sha1[(offset * 2):((offset * 2) + 8)], 16) & 0x7fffffff
40 | totp = str(binary)[-length:]
41 | print(totp)
42 |
43 |
44 | # In[182]:
45 |
46 |
47 | # Generating QR Code
48 | image_path = "/tmp/token_qr.png"
49 |
50 | import qrcode
51 |
52 | qr_string = "otpauth://totp/Example:my-email-address@gmail.com?secret=" + token.decode("utf-8") +"&issuer=Example&algorithm=SHA1&digits=6&period=30"
53 | print(qr_string)
54 | img = qrcode.make(qr_string)
55 | img.save(image_path)
56 |
57 |
58 | # In[167]:
59 |
60 |
61 | # Displaying Image in Jupyter Notebook
62 | from IPython.display import Image
63 | Image(filename=image_path)
64 |
--------------------------------------------------------------------------------
/ascii_image.txt:
--------------------------------------------------------------------------------
1 | $$@$$$$$@%$%%%%%%$%%%$%*%*$%$@$@#BSBBBBBBBSBBB#SSSSSS##S&S##*%**%%%%$BBBBB#S#@******!#%*&$%**%%**%$%**%%%%%%$$%%%$$$
2 | @$@$$$%$%%%%$%%%%%%$%%%%%%%%%%%##BBBBBBBBBBBBBBSSS&&S#S#&S##S@@***%%%%$BSBSS@S%*!!*!**@%&$%@%%@$&!*%*%%*%*%*%*%%%$*$%%
3 | $@$$$$%%$%%$$$*$%%%%%%%%**%$%*B&BBBBBBBBBBBBBBBBSS#####&S#&B#%*%@#&%****%S#S$#&&***%%!*&%@%$%$$$#%%*%*!%$***!*!!*%%%%%%$
4 | $%$$%$%%$%$%%%$%*%$%%%%%%$%%%#@#BBBBBBBBBBBBBBBSBS&&@@%SSBBS@%%$@@@%%%%!!!!!!*!!*:!@%*&*$%%%%$**%%****$!!!***%*!!!*%%*%*
5 | $$$%%%%$%%%$$%%$%%%%%*%%%$$$$*#SBBBBBBBBBBBBBBBSS#&@$$SB##$$&BS$$%%*%@####%*%%!:!!!@*%$@%%%%$!%%$*******!!!*****%*%%%$**
6 | $$$%%$$%$%$%$$$$%%$$$$$$$$$$$@SSBBBBBBBBBBBBBSSS#&&$SB%%&!**%*$%**!*&@$$&BB##&%!!!%$$@$$%%%@%*@$$$%!:!!*!!*:*!*******%%%
7 | @@@$$%%*@$$$$@%$$%$$$$@$$$@$%$BSBBBBBBBBBBBBBBS#&&S&$**@::!!***!!!!*@BB&BBB#&S!!!!%%@$$$%%%@*@%%$$**!******%!*!%**%%%%%%
8 | @@$$$%$*%$%$%$@%@$$$@$$$$$%%%SSSBBBBBBBBBBBBBS#&&&&$%%%*!:!!!**!!!!!*%$&BBSBS@%!!!&@@@$%%%%%%%%$*%*******!!*!!*!!*%%%%%$
9 | $@$@%$$*$$@@$$$$$$%$$$%$$%$$$&BBBBBBBBBBBBBBBSBS&@$$%%%*!!!*******!:!*%$BB#SS**!!!&&&@$%%%%%%%@*!%**!*****%***%*!***%%%%
10 | @@$$%$$*$$%$$$$$$$$@$%$@$$$$%$&SSBBBBBBBBBBBBBBSS#&$%**********$SB%%%*%@BBBB:**!!:$&@%%%%%%$$@****%%*%****!*******%%%%%$
11 | $@$$$$$!$@$$$$%$$$$@@@@$$$%$$$%$%#SBBBBBBBBBBBS##&&@%%********!!*$#@**%BBSBB!!!**%@@$%%%%$$@@*%**%%**!!%**!******%!*%$$%
12 | @@@$@@$*@$$$$$$@%$@@@$$%%$&$$$$$$$$%#BBBBSSS##B###&@$%%***%@S##@$@*$$@BBBBS:!!!!!%@%%%%%$%*%%%%%*****%***********%!*%*$$
13 | @@@$$$$!$$$%$%%$%@$@$$$$$$$$$$$$@$$$$%$SS&&&&&@BSS#&@@$%%****@$$#SS@SBBBBS*!!*!!%&$%%%%$%:%%*%%%*%*!!**!!*!*****%%%%%%$$
14 | @@$@$$$!$$@$$$$$$$$$$$@@@$$$$$$$$$$$$%%#&@$$###SBBB@%**!*%$#&&$BBBBS@!***!!%@$%%%%%%*:%%**%*%*!*!**********%%*%%%%%$
15 | @@$$@$$!$@$@&$$@@@%%$$@@@$$$$$$$$$$$$%%$@#SSS&SS%%*****#B%*!!**%$$S###&**!!:*!*$@$%%%%$**.****%!!******!**!%******%%%*%%
16 | @@@$@$@*$$@$&$$@@@$%*%$@$$$$$@@@&@$$$##S#S#S##@%*!!!!!!*%B$$***%$!%*$***!!!:**%@$$%%%$@**:**%**!*!!*****::!%!*%%**%%*$%$
17 | &@@$@$$*$@$@#@@$$%$$%!*%$$&$$$$$%@&@SBSSBB#SS%**!!!!!!!!*%BB#@$#%****!**!!!!!$&@$%%%$$!**:%%****%!!*!*!*!*!**!****%%*%%$
18 | @@@@@@@%@&@@@&@@$$@$$$**%$$@@$@$@$$BB#BBBSS#%%*!!!!!!!!!*%BB%****%******!:!*%$@$%%%%$$***:!*%**!!!:*!**::::!!***%%*%%%%$
19 | @@@$@@@*@&$@@@$@@$$@@$@%%%$@@@@@$SBBSSBSBB#$%**!!!!!!!!!**%B&******!******!*$@@%%%%%$$***:**!!!!:::!!!!!*!**%!%%%***%%$$
20 | @@$$@$$*@&@@@@@@@$$@$$$%%$$$$@$SBBBSBBBSS&$$%**!!!!!!!!!!*%*BS*%**!!!****!*$&@$%%%%%$%*%*.!!!!:::::!!!!!!***%%**%!%%%$$$
21 | $@$$$@$*@$$$@$@@$@%@@&@@$$$$@@BBBBSBBBSBS@$%%**!!!::::!!!!*%BB*%*%***!**!!%#@$$%%%%%$%***.!*!!!*!!!:!**!**%**!*%%%%%$%$$
22 | @@$$$$$*$$@$@$&$$$@$$@@@@@@$@@BBBBSSBBS#&@$%%**!!!:::::!!!*%*BS#****!***!$@@$%%%%%%$$***$:*!***!!!!!%****%*%%%*$*!$$%$$$
23 | $@@$$$$%@@$$@$@$@@@$@$$@@@@$@BBBBBBBBBB#&@$$%%**!!!::::!!!!*%B#***!!%*$&@@@%%%%%%$******!****!*****!%**%*****%**%%%$$@
24 | @@@&@$$*$@$@$%$$@$@$@@@$@@@@@SBBSBBBBBB##@@$%%**!!!:::::!!!*%###&S**%**%@&@$%%%%%%$$*************!!************%*%%%$%$$
25 | @@@$$@$*$$@@$$$@@$@@@@@$@@@@$SBBBBBBBBBS##@$$%%**!!!:::::!!***S###&***$@&@$$%%%%%$$%****!!!!******!***********%*%%%%%$$$
26 | @@@$$@$*$@$@@@@@@$$@@@@$@$$$SBBBBBBBBBBS##&@$%%%**!!:::::!!***S#SSS:$$$&&@@$$%%$$$%****!*%%******!**!%******%%**%*%%$$$@
27 | @@@$@$$*$@$@$%$@$@@$@&@@@$%$#SBBBBBBBBBBS##@$$%%***!!::::!!!**S#S##::@%%%$$@$$$$$@**!*%**!%%%*!**************%***%%$$$$$
28 | @@@#$$@*$$$@$@$$@$$$@@@$@$*!!*$BBBBBBBBBSS#&@$%%***!!!::::!!**$SSSS:#!#!%%%%%%$$@@*!*****$%*****%%*%******%*****%$%%%$$$
29 | @@@@$@@%@$$$@@@$$@$@@$@@@@@%*$$&BBBBBBBBBS#&@$%%***!!!::::!!!*%SSS#SS::B:$%%%$$$@**%*%****$****%**%**!***!**%**!%%%%%$$$
30 | &@@$$@$%@$@$@$@%@$@$@@@$@@$@$$BBBBBBBBBBB###&@$%****!!!:::!!**%BBB#B#::::$$@$@$$*%***!********%*******%***%$$%%$%$$%$$
31 | @@$@$$$%@$%$%$@%$@$@@@&@&@$&$@BBBBBBBBBBBB##&@$%%***!!!:::!!!!*#SSSS###SS#####$@***%%%*%*****!**!*%*****%%***%****%$%$$$
32 | @@&@&$$%$@$@$$$$$@@@&@&@@@@$$@&BBBBBBBBBBBB##&@$%%**!!!!::!!!**%#BBBBSSSS#######%%%%*!***%**%%%*****%%!****%%**%*%%$$@$%
33 | @@@$@$$$$$@$%%$@@@$$@$@$@@@@@@@BBBBBBBBBBBB#S#@$$%***!!!::!!!!**SSSSS###S#S#####**%$%*!**%*%**%****%***%******%*%%%%%$$@
34 | @@$$$%$@@@$$@$@@@@@&&@@@&&@$@@@BBBBBBBBBBBBBS#&@$$%**!!!::!!!!**BSSSSBBBSSSSSS##**%***%**!!******%%%%***%****%**%%%%%$$@
35 | @$$$$$$@$$$$@@$@@@@@$@&&@@@@@&@@BBBBBBBBBBBB###&@$%%**!!:::!!!**%S###SSSSSSSSSSS*%******%*:%****%**%$%%$*%%%$$%$**!*%$$$
36 | @@$$$$$&$@$@@&@@@$@@&@&@&&@@@&@@BBBBBBBBBBBBB##&@$$%**!!!::!!!!**S##SSSSSSSBSSSS!::!*%%%%***%******%%***%%*%%***%%%%$$$@
37 | @@@$$$@@@@&@@@@$@@@&&@#&@$$%$$@BBBBBBBBBBBBS##&@$%%**!!::!!!!**$SS##SS##S##BSS%%%%**%*%$$*!!%************%%**%%%%%$%$$
38 | @@@@$@&$&&&@@@$@@@@&@&@@&&@@@@&@@BBBBBBBBBBBBBSS#@@$%**!!!::!!!**%BBBS#SBSSBSSSS%*%**%%$%%$*%**%*!***%**%%**%***%%%%%$$@
39 | @@@@@@&@&@&&&&@@$%@@@@@@@@&@&&@&@&BBBBBBBBBBBBB##&@$%%**!!:!!!!!**SS##SSBBSS#S#S*%%%%%%**%$*%*%%*****%****%%*****$%%$$@@
40 | @@@@@@#@@&@@@@&@@@$@@&@&@&@@@@@&&&BBBBBBBBBBBBBS#&@$$%**!!!!!!!!**BSSSBSSS####SS%*@%%*%$%*%*%$%%%*%%!%*****%%*%*%%%%%$$$
41 | SSSSSSSSSS####SSSSSSSSSSS#SSS##&&&&BBBBBBBBBBBBBS#&@$%%**!!:!!!!**%SBS#SS#SSSSSS**@*%$%%*$****$%%%%**********%%**%%%$%%@
42 | @@@@@@$&@@&@@@&@@&@&@@@@@@@@&&&&&&&&BBBBBBBBBBBBS#&@$%%**!!!!!!!!**%BSSBSSSSSSS#B%$%%!%*@%!%%%*%%%*%%$%*%***%%*%*%%$%$@$
43 | &&S&$##&&&&&&@#&&&&&@&@&&&&&&&BBBBBBBBBBBBBS#@@$%%**!!!:!!!!!****!S#SSS#S##*%*%%%*%%:%%*%%%!%%*!*%%**%%*%***%%$$@$
44 | &&&&&&*#&&&&&&&&&#&&&&&&&&SBBBBBBBBBBBBS#&@$$%****!!!!!!!!!!!***%$#SSS#S*%**%%*%:*%%**!%*%$***%%%%*%%**%$%%$$@
45 | &&&&@@%&&&&&&@&&&&@&&&&&&&@@&&&&@#&SBBBBBBBBBBBBSS@$%%****!!!!!!!!!!!!!*!***S##S!****$%*:*%%****%***%%$%%*%%%%%%%$$$@$
46 | &&@@@$!@&&$@&&@@@&&&@&&&&&@&&S#&@&&&BBBBBBBBBBBBBS&@$%****!!!!!!!!!!!!!*!*!***!&***!*%%*:**%**%%%%!****%%*****%%%%$$$$
47 | &@@@@@*@&&@@@&&@&@@@&&@&@&&&&&&@&&SBBBBBBBBBBBBS##@$%%%****************************%$*:*%%**%*%%%!***%*****%**%$%$$$
48 | &@@@&@%@@&&&@@&@&@@&&&&&@&&&&&&&&S&SBBBBBBBBBBBBSS#&@@@$$%%%%%%%%%%%************%***%%:%%%%%%*%******%%*%%*%***%$%@@
49 | &@@@&@*@@@@@&@&&@@@@@@@&&&&&&&&&&&&&SBBBBBBBBBBBBBSSS#####&&&@@@@$$%%%%%************%*:%%%%%**%%%***********%%%%%$@@
50 | &@@&&&%&@&&#####SS####SS#BBBBBBBBBBBBBBBB#S##S###&&&@@@$$$$$$$%%%*********%%****%%******%****%%**%%%$$@$
51 | &&&&&&%####@############SSSS#BBBBBBBBBBBBBBBBBBBBB#####&&&@@@@$$$$$$$$%%%*****%**%%%**!***%***%%%*%%%%%%$$$$
52 | &&&&&&%&&&&&#################S##S##S##BBBBBSBSBBBBBBBBBBBBBBBB#&&&&&&&@@@$$$@$$@$$$%*%%****%***%!****%%**%**%$%%%@$@
53 | @&&&%&@@&&&@@&&&&&&&##S##SSSSSBBBBSSSBBBBBBBBBSBBBBBBB&&&@@@@$$$$$$$$$%%********%%%%*%%***%*%%%%$$$$
54 | &&@&@&%@@@@@$$@&@@@&@$&&@&&&@#&&&&SSSSSBSBSBSSBB#&&@@$$$%*****!!!!!!!@B#&&&&@@@$$$$%*********$%***%***%%%%%%$$$$
55 | &&&&@&%@$@@@@@$@$&@@@&&&&@&@##&&&#SSSSSSSSSS##&&&@$$%%%%****!!!!!!!:!!!!!!!!*SB&&&@@@$$%*!!!*%!**%%%%%%%%%$$$$$@
56 | &@@&&&%@$@@@$**!$@&@@&&&&&@&&#&#SSS####&&&@&@$$%%%*****!!!!!!!!:!::!::!!!!!****SSS#&&&$%*!***%%****$$%%%%$%$$$$@
57 | &&&&&@$@@@&&S%*!!!$@@$&&&&&@&&#&SS#&&@@@@@@&$$%%%*****!*!!!!!!!!!::!:::::!!!!!!***%*:BB#%**$!!!*$***%%%%%%%%%$$$%@
58 | &&&@@&$@@&@&&@@*!!!!%@&&@&&&&&#&&&&&@$$$@@@$%%%******!!!!!!!:!!!!:!!!::::::!!!!!**%%B#S#@%**:!!*!%*%%***$$%*$$$$$$
59 | &@&&@&&&$@@&&@@@%!****$@@#&&&&&&$$$$$$$$$&&$$%%*******!!!!!!!!!!!:::!!::!:!::!!!!!!**%$$##S&$!!:!***%%%%%%%%%*%%%$$@
60 | &&&@&@#&@$@&&&@&@$*****@@#&&&@$$%%%%%%%$@@$$%%******!!!!!!!!!!!!::::::::!!:::!!!!!!!**%@$#S%!:!***%%%*%%%%%*%$$$$$
61 | &&&&&&&&@&@&&@&@&@$$@$&&&&&&&&$%%*******%@&$%%%***!*!!!!!!!!!!!!!!!::::::::::::!!!!!!!**%%$@&S#&%!:!#*%*%%%**%%%%$%@$@
62 | &@&@@&S&&&&&&&@#&&&&&&$%%%********$&@$%*****!!!!!!!!!!!!!!!:::::::::::::!!!!!!!!!**%$@&S##$*!*$%**$%%%*%*%%%$$$$
63 | &&@@&&&@&@&&&&&&&&&@&&&@&$%%%********%#&$%%%****!!!!!!!!!!!:!!!!:::::::!::::!!!!!!!!***%$B###@%:!%*%%%%*%%$%$$$$@$
64 | &@&&@&@&@@&&&&&&&&&&#&&@$%%%%*******%$&&$%%****!!!!!!!!!!!!!::!!::::::::::::!!!!!*!****%$@###&&&%!!$%*$*%%$%%%$$$$$@
65 | @&@&@&@&#&#@&&&@$%%%%*******$S#@$$%%****!!!!!!!!!!!!!:!:::!::!::::!!!!!!!!!****%$@S#SS#!!%%*%*%%%%%%%$$$@$
66 | @&&&@&@&@@@&&&&@&S#S#&@$$%%%*******%@S&@$%%%******!!!!!!!!!!!!!!!:::::!:!:!!!!!!!!!***%%$$&BBBBS**%#%&%%%%%%%$$$$$$@
67 | &&&&&@@@$&@&&S##S#&&@$$%%%*******$#@@$%%%*****!*!!!!!!!!!!!!!!:!:!!::!!!!!!!!!****%%$@B$*!%%$&B$*%%$%%%%%%%$%$$@
68 | &&&$&&@&@&###S##&&&@$%%%%*****%$##&&@$%%%%********!!!!!!!!!!:!!!!::!!!!!!!!!!****%%$$@BSB&&BS**%%%%*%%%%%%$$$$$@
69 | &&&&&$@&@@&&&#&&#S##&&@$$$%%******%$###@@$$%%%%%*******!!!!!!!!!!!!!!!!!!!!!!!******%%$$@SB$@***%&&%%%*%%%%%%%$$$@@@
70 | &@&&&%&@&&&&@###&&&#&$@$$$$%%*****%@###&@@$$%%%%%********!!!!!!!!!!!!!!!!!!!!******%%$$$SSBSSS%%%%%%%%%%%%%%%$$$@@
71 | &&@&@*@@@&@@&@&@##&@@$$$$%%%***%$@####&@$$$$%%%%%*********!!!!!!!!!!!!!!!!!*****%%$$@&S$$@@%%$$*%**$%%%$%%$%%%$$@@
72 | &&&@&*@&$@&&@@&@&&S######&@@$$$$%%%%%%%@#SS#&&@$$$%%%%%*****************!*!********%*%%$$$@&$SB$$%%%**!*%**$%%%%$%%%$@@@
73 | &@@@&%&@@&@@&@&@S##&&@@$$$$%%%%%%@SBS##&@@$$$%%%%%%%*************************%%%$$@@&BS%&BB$$%%%%%**%$%%%$$$$$$$$@
74 | &&@&@%$@@@&@@@@&&#S#S#&&&@@$$$$$%%%%$@SBSSS#&&@@$$$%%%%%%%%*********%*******%%%%%%%$$$@#$S@SS$B&%%%%%%$*%%*$%%$$$@$@$$
75 | #&@%&@@@@&&&&&&##&S##&&&@@@$$$$$$$@SBSS##&@@$@$$$$%$%%%%%%%%%%%%%%%%%%%%%%%%$$@@@#%B&@BSSB&%%%$%$*%*%%***%*$$$$@$@
76 | &&&@@%$&$@@@@&&&&###SSS#&&@&@@$$$$$$$SBSSSS#&&@@@$$$$$$$$%$%%%%%%%%%%%%$$$$$$$$$@$BB$BBSBS:!*%$$%%$%%%%%*$$$$$$$$$
77 | &&&&&%&@@@&&@&&&@##SSSS#&&&@@@@$$@@SBBSSSS##&&@&@@@@@@$$$$$$$$$$$$$$@@$@@@@@&&&BBSB*SSB#BS%%*$%$%$%$$*%$*$@$$@@&
78 | &&&%@@&&&@&&@&&BSSSSS#&&&&@@@@@&&SSBBBBSS##&&&&&&&@@@@@@@@@@@@@@@@@@&#&S#&SB#SBBBB#S#@S:B$%*%$$%%@$$$@$@$@$@@@
79 | &&&&&$&@&&@&#&&#BBBSSSSS###&&&@@&&SBBBBBBSSS#S##&&&&&&&&&&&&&&&####SB&SBSS&BBBS@BBS$BBBBB@$%**%$$@$$$$%$@@@&@@
80 | ###&&$&&&&&&&&####BSBBBBBBBSSS#######SSBBBBBBBBSSSSS##########S###SSBB::&&!BBBBBS&SSSSBBS@BSBB@$%%*%@$$$$@$$$@@@@&
81 | ######&#########BBBS#$$SB#BB$SBBBBSBS&&SBBBBBBBBSSSSSSSSSBSBBBBSBB%&@BBBBBSBBSBSBSB:BS&&B&!B&%@@@@@%$@$@@@@@@@@&@@
82 | #&##############SSBS#SBBBSBBSS$BBBBSBBSSBBBB#BSBBBBBBBBBBBBS@SBBBB#BSSS&BBSB&BBBBBBBBBSS#SS@B@##&@@@@@@@$@@@@@&&&@&&
--------------------------------------------------------------------------------
/credit_card_validator.py:
--------------------------------------------------------------------------------
1 | """
2 | Python script to check validity of credit card numbers
3 | Author : PythonCircle.Com
4 | Read more : https://www.pythoncircle.com/post/485/python-script-8-validating-credit-card-number-luhns-algorithm/
5 | """
6 |
7 | import sys
8 |
9 |
10 | def usage():
11 | msg = """
12 |
13 | usage:
14 | python3 credit_card_validator credit_card_number
15 |
16 | example:
17 | python3 credit_card_validator 34678253793
18 |
19 | """
20 | print(msg)
21 |
22 |
23 | def get_cc_number():
24 | if len(sys.argv) < 2:
25 | usage()
26 | sys.exit(1)
27 |
28 | return sys.argv[1]
29 |
30 |
31 | def sum_digits(digit):
32 | if digit < 10:
33 | return digit
34 | else:
35 | sum = (digit % 10) + (digit // 10)
36 | return sum
37 |
38 |
39 | def validate(cc_num):
40 | # reverse the credit card number
41 | cc_num = cc_num[::-1]
42 | # convert to integer list
43 | cc_num = [int(x) for x in cc_num]
44 | # double every second digit
45 | doubled_second_digit_list = list()
46 | digits = list(enumerate(cc_num, start=1))
47 | for index, digit in digits:
48 | if index % 2 == 0:
49 | doubled_second_digit_list.append(digit * 2)
50 | else:
51 | doubled_second_digit_list.append(digit)
52 |
53 | # add the digits if any number is more than 9
54 | doubled_second_digit_list = [sum_digits(x) for x in doubled_second_digit_list]
55 | # sum all digits
56 | sum_of_digits = sum(doubled_second_digit_list)
57 | # return True or False
58 | return sum_of_digits % 10 == 0
59 |
60 |
61 | if __name__ == "__main__":
62 | print(validate(get_cc_number()))
63 |
--------------------------------------------------------------------------------
/db-backup-pythonanywhere.py:
--------------------------------------------------------------------------------
1 | import os
2 | import datetime
3 | from zipfile import ZipFile
4 |
5 | #
6 | # Author - Anurag Rana
7 | # anuragrana31189 at gmail dot com
8 | # place in home directory. schedule with task tab on pythonanywhere server.
9 | # https://www.pythoncircle.com/post/360/how-to-backup-database-periodically-on-pythonanywhere-server/
10 | #
11 |
12 | BACKUP_DIR_NAME = "mysql_backups"
13 | DAYS_TO_KEEP_BACKUP = 3
14 | FILE_PREFIX = "my_db_backup_"
15 | FILE_SUFFIX_DATE_FORMAT = "%Y%m%d%H%M%S"
16 | USERNAME = "username"
17 | DBNAME = USERNAME+"$dbname"
18 |
19 |
20 | # get today's date and time
21 | timestamp = datetime.datetime.now().strftime(FILE_SUFFIX_DATE_FORMAT)
22 | backup_filename = BACKUP_DIR_NAME+"/"+FILE_PREFIX+timestamp+".sql"
23 |
24 | os.system("mysqldump -u "+USERNAME+" -h "+USERNAME+".mysql.pythonanywhere-services.com '"+DBNAME+"' > "+backup_filename)
25 |
26 |
27 | # creating zip file
28 | zip_filename = BACKUP_DIR_NAME+"/"+FILE_PREFIX+timestamp+".zip"
29 | with ZipFile(zip_filename, 'w') as zip:
30 | zip.write(backup_filename, os.path.basename(backup_filename))
31 |
32 | os.remove(backup_filename)
33 |
34 | # deleting old files
35 |
36 | list_files = os.listdir(BACKUP_DIR_NAME)
37 |
38 | back_date = datetime.datetime.now() - datetime.timedelta(days=DAYS_TO_KEEP_BACKUP)
39 | back_date = back_date.strftime(FILE_SUFFIX_DATE_FORMAT)
40 |
41 | length = len(FILE_PREFIX)
42 |
43 | # deleting files older than DAYS_TO_KEEP_BACKUP days
44 | for f in list_files:
45 | filename = f.split(".")[0]
46 | if "zip" == f.split(".")[1]:
47 | suffix = filename[length:]
48 | if suffix < back_date:
49 | print("Deleting file : "+f)
50 | os.remove(BACKUP_DIR_NAME + "/" + f)
51 |
52 |
53 |
54 | # restoring backup
55 | # mysql -u yourusername -h yourusername.mysql.pythonanywhere-services.com 'yourusername$dbname' < db-backup.sql
56 |
57 | # reference
58 | # https://help.pythonanywhere.com/pages/MySQLBackupRestore/
59 |
--------------------------------------------------------------------------------
/desktop_wallpaper_bing.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | """
4 | Python script to set bing image of the day as desktop wallpaper
5 | OS: Ubuntu 16.04
6 | Author: Anurag Rana
7 | More Info: https://www.pythoncircle.com
8 | """
9 |
10 | """
11 | LICENCE
12 |
13 | Copyright 2020 Anurag Rana
14 | Permission is hereby granted, free of charge, to any person obtaining a copy of
15 | this software and associated documentation files (the "Software"), to deal in the
16 | Software without restriction, including without limitation the rights to use, copy,
17 | modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
18 | and to permit persons to whom the Software is furnished to do so, subject to the
19 | following conditions:
20 |
21 | The above copyright notice and this permission notice shall be included in all copies
22 | or substantial portions of the Software.
23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
24 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
25 | PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
27 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
28 | OR OTHER DEALINGS IN THE SOFTWARE.
29 |
30 | """
31 |
32 | import datetime
33 | import json
34 | import os
35 |
36 | import requests
37 |
38 | # get image url
39 | response = requests.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US")
40 | image_data = json.loads(response.text)
41 |
42 | image_url = image_data["images"][0]["url"]
43 | image_url = image_url.split("&")[0]
44 | full_image_url = "https://www.bing.com" + image_url
45 |
46 | # image's name
47 | image_name = datetime.date.today().strftime("%Y%m%d")
48 | image_extension = image_url.split(".")[-1]
49 | image_name = image_name + "." + image_extension
50 |
51 | # download and save image
52 | img_data = requests.get(full_image_url).content
53 | with open(image_name, 'wb') as handler:
54 | handler.write(img_data)
55 |
56 | # ubuntu command to set wallpaper
57 | os.system("`which gsettings` set org.gnome.desktop.background picture-uri file:$PWD/" + image_name)
58 |
--------------------------------------------------------------------------------
/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anuragrana/Python-Scripts/fda0186a0d7ba34f152a35107ca10876e9e9a7ec/image.png
--------------------------------------------------------------------------------
/image_to_ascii.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from PIL import Image
3 |
4 |
5 | # pass the image as command line argument
6 | image_path = sys.argv[1]
7 | img = Image.open(image_path)
8 |
9 | # resize the image
10 | width, height = img.size
11 | aspect_ratio = height/width
12 | new_width = 120
13 | new_height = aspect_ratio * new_width * 0.55
14 | img = img.resize((new_width, int(new_height)))
15 | # new size of image
16 | # print(img.size)
17 |
18 | # convert image to greyscale format
19 | # https://stackoverflow.com/questions/52307290/what-is-the-difference-between-images-in-p-and-l-mode-in-pil
20 | img = img.convert('L')
21 |
22 | pixels = img.getdata()
23 |
24 | # replace each pixel with a character from array
25 | chars = ["B","S","#","&","@","$","%","*","!",":","."]
26 | new_pixels = [chars[pixel//25] for pixel in pixels]
27 | new_pixels = ''.join(new_pixels)
28 |
29 | # split string of chars into multiple strings of length equal to new width and create a list
30 | new_pixels_count = len(new_pixels)
31 | ascii_image = [new_pixels[index:index + new_width] for index in range(0, new_pixels_count, new_width)]
32 | ascii_image = "\n".join(ascii_image)
33 | print(ascii_image)
34 |
35 | # write to a text file.
36 | with open("ascii_image.txt", "w") as f:
37 | f.write(ascii_image)
38 |
39 |
40 |
--------------------------------------------------------------------------------
/india_flag_turtle.py:
--------------------------------------------------------------------------------
1 | #
2 | # Python script to wish Merry Christmas using turtle.
3 | # Author - https://www.pythoncircle.com
4 | #
5 |
6 | import turtle
7 | import time
8 |
9 | # create a screen
10 | screen = turtle.getscreen()
11 | # set background color of screen
12 | screen.bgcolor("#b3daff")
13 | # set tile of screen
14 | screen.title("Indian Flag - https://www.pythoncircle.com")
15 | # "Yesterday is history, tomorrow is a mystery,
16 | # but today is a gift. That is why it is called the present.”
17 | # — Oogway to Po, under the peach tree, Kung Fu Panda Movie
18 | oogway = turtle.Turtle()
19 | # set the cursor/turtle speed. Higher value, faster is the turtle
20 | oogway.speed(100)
21 | oogway.penup()
22 | # decide the shape of cursor/turtle
23 | oogway.shape("turtle")
24 |
25 | # flag height to width ratio is 2:3
26 | flag_height = 300
27 | flag_width = 450
28 |
29 | # starting points
30 | # start from the first quardant, half of flag width and half of flag height
31 | start_x = -225
32 | start_y = 150
33 |
34 | # For saffron, white and green stripes. each strip width will be flag_height/3 = 100
35 | stripe_height = flag_height/3
36 | stripe_width = flag_width
37 |
38 | # Radius of Ashok Chakra, half of white stripe
39 | chakra_radius = stripe_height / 2
40 |
41 |
42 | def draw_fill_rectangle(x, y, height, width, color):
43 | oogway.goto(x,y)
44 | oogway.pendown()
45 | oogway.color(color)
46 | oogway.begin_fill()
47 | oogway.forward(width)
48 | oogway.right(90)
49 | oogway.forward(height)
50 | oogway.right(90)
51 | oogway.forward(width)
52 | oogway.right(90)
53 | oogway.forward(height)
54 | oogway.right(90)
55 | oogway.end_fill()
56 | oogway.penup()
57 |
58 |
59 | # this function is used to create 3 stripes
60 | def draw_stripes():
61 | x = start_x
62 | y = start_y
63 | # we need to draw total 3 stripes, 1 saffron, 1 white and 1 green
64 | draw_fill_rectangle(x, y, stripe_height, stripe_width, "#FF9933")
65 | # decrease value of y by stripe_height
66 | y = y - stripe_height
67 | # create middle white stripe
68 | draw_fill_rectangle(x, y, stripe_height, stripe_width, "white")
69 | y = y - stripe_height
70 |
71 | # create last green stripe
72 | draw_fill_rectangle(x, y, stripe_height, stripe_width, '#138808')
73 | y = y - stripe_height
74 |
75 |
76 | def draw_chakra():
77 | oogway.speed(1)
78 | oogway.goto(0,0)
79 | color = "#000080" # navy blue
80 | oogway.penup()
81 | oogway.color(color)
82 | oogway.fillcolor(color)
83 | oogway.goto(0, 0 - chakra_radius)
84 | oogway.pendown()
85 | oogway.circle(chakra_radius)
86 | # draw 24 spikes in chakra
87 | for _ in range(24):
88 | oogway.penup()
89 | oogway.goto(0,0)
90 | oogway.left(15)
91 | oogway.pendown()
92 | oogway.forward(chakra_radius)
93 |
94 |
95 |
96 | # start after 5 seconds.
97 | time.sleep(0)
98 | # draw 3 stripes
99 | draw_stripes()
100 | # draw squares to hold stars
101 | draw_chakra()
102 | # hide the cursor/turtle
103 | oogway.hideturtle()
104 | # keep holding the screen until closed manually
105 | screen.mainloop()
106 |
107 |
--------------------------------------------------------------------------------
/log_cleaner.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 |
4 | config = [
5 | {
6 | "folder": "/tmp",
7 | "delete_older_seconds": 3600
8 | }
9 | ]
10 |
11 |
12 | def delete_file(f, item):
13 | ctime = os.path.getctime(f)
14 | delete_older = item.get("delete_older_seconds")
15 | if delete_older is None:
16 | return
17 |
18 | if (time.time() - ctime) > delete_older:
19 | try:
20 | if os.path.isfile(f):
21 | os.remove(f)
22 | print("deleted: ", f)
23 | except Exception as e:
24 | print("Error in deleting: ", f)
25 | print(e)
26 |
27 |
28 | def start():
29 | for item in config:
30 | folder = item.get("folder")
31 | if folder is None:
32 | continue
33 |
34 | files = os.listdir(folder)
35 |
36 | for f in files:
37 | delete_file(f, item)
38 |
39 |
40 | if __name__ == "__main__":
41 | start()
--------------------------------------------------------------------------------
/merry_christmas_using_python.py:
--------------------------------------------------------------------------------
1 | #
2 | # Python script to wish Merry Christmas using turtle.
3 | # Author - Anurag Rana
4 | #
5 | from turtle import *
6 | from random import randint
7 |
8 |
9 | def create_rectangle(turtle, color, x, y, width, height):
10 | turtle.penup()
11 | turtle.color(color)
12 | turtle.fillcolor(color)
13 | turtle.goto(x, y)
14 | turtle.pendown()
15 | turtle.begin_fill()
16 |
17 | turtle.forward(width)
18 | turtle.left(90)
19 | turtle.forward(height)
20 | turtle.left(90)
21 | turtle.forward(width)
22 | turtle.left(90)
23 | turtle.forward(height)
24 | turtle.left(90)
25 |
26 | # fill the above shape
27 | turtle.end_fill()
28 | # Reset the orientation of the turtle
29 | turtle.setheading(0)
30 |
31 |
32 | def create_circle(turtle, x, y, radius, color):
33 | oogway.penup()
34 | oogway.color(color)
35 | oogway.fillcolor(color)
36 | oogway.goto(x, y)
37 | oogway.pendown()
38 | oogway.begin_fill()
39 | oogway.circle(radius)
40 | oogway.end_fill()
41 |
42 |
43 | BG_COLOR = "#0080ff"
44 |
45 | # "Yesterday is history, tomorrow is a mystery, but today is a gift. That is why it is called the present.”
46 | # — Oogway to Po under the peach tree, Kung Fu Panda
47 | oogway = Turtle()
48 | # set turtle speed
49 | oogway.speed(2)
50 | screen = oogway.getscreen()
51 | # set background color
52 | screen.bgcolor(BG_COLOR)
53 | # set tile of screen
54 | screen.title("Merry Christmas")
55 | # maximize the screen
56 | screen.setup(width=1.0, height=1.0)
57 |
58 | y = -100
59 | # create tree trunk
60 | create_rectangle(oogway, "red", -15, y-60, 30, 60)
61 |
62 | # create tree
63 | width = 240
64 | oogway.speed(10)
65 | while width > 10:
66 | width = width - 10
67 | height = 10
68 | x = 0 - width/2
69 | create_rectangle(oogway, "green", x, y, width, height)
70 | y = y + height
71 |
72 | # create a star a top of tree
73 | oogway.speed(1)
74 | oogway.penup()
75 | oogway.color('yellow')
76 | oogway.goto(-20, y+10)
77 | oogway.begin_fill()
78 | oogway.pendown()
79 | for i in range(5):
80 | oogway.forward(40)
81 | oogway.right(144)
82 | oogway.end_fill()
83 |
84 | tree_height = y + 40
85 |
86 | # create moon in sky
87 | # create a full circle
88 | create_circle(oogway, 230, 180, 60, "white")
89 | # overlap with full circle of BG color to make a crescent shape
90 | create_circle(oogway, 220, 180, 60, BG_COLOR)
91 |
92 | # now add few stars in sky
93 | oogway.speed(10)
94 | number_of_stars = randint(20,30)
95 | # print(number_of_stars)
96 | for _ in range(0,number_of_stars):
97 | x_star = randint(-(screen.window_width()//2),screen.window_width()//2)
98 | y_star = randint(tree_height, screen.window_height()//2)
99 | size = randint(5,20)
100 | oogway.penup()
101 | oogway.color('white')
102 | oogway.goto(x_star, y_star)
103 | oogway.begin_fill()
104 | oogway.pendown()
105 | for i in range(5):
106 | oogway.forward(size)
107 | oogway.right(144)
108 | oogway.end_fill()
109 |
110 | # print greeting message
111 | oogway.speed(1)
112 | oogway.penup()
113 | msg = "Merry Christmas from ThePythonDjango.Com"
114 | oogway.goto(0, -200) # y is in minus because tree trunk was below x axis
115 | oogway.color("white")
116 | oogway.pendown()
117 | oogway.write(msg, move=False, align="center", font=("Arial", 15, "bold"))
118 |
119 | oogway.hideturtle()
120 | screen.mainloop()
121 |
122 |
--------------------------------------------------------------------------------
/news_headlines.py:
--------------------------------------------------------------------------------
1 | # Author - pythoncircle.com
2 |
3 | import requests
4 | from bs4 import BeautifulSoup
5 | import json
6 |
7 |
8 | def print_headlines(response_text):
9 | soup = BeautifulSoup(response_text, 'lxml')
10 | headlines = soup.find_all(attrs={"itemprop": "headline"})
11 | for headline in headlines:
12 | print(" " + headline.text)
13 |
14 |
15 | def get_headers():
16 | return {
17 | "accept": "*/*",
18 | "accept-encoding": "gzip, deflate, br",
19 | "accept-language": "en-IN,en-US;q=0.9,en;q=0.8",
20 | "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
21 | "cookie": "_ga=GA1.2.474379061.1548476083; _gid=GA1.2.251903072.1548476083; __gads=ID=17fd29a6d34048fc:T=1548476085:S=ALNI_MaRiLYBFlMfKNMAtiW0J3b_o0XGxw",
22 | "origin": "https://inshorts.com",
23 | "referer": "https://inshorts.com/en/read/",
24 | "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
25 | "x-requested-with": "XMLHttpRequest"
26 | }
27 |
28 |
29 | url = 'https://inshorts.com/en/read'
30 | response = requests.get(url)
31 | print_headlines(response.text)
32 |
33 | # get more news
34 | url = 'https://inshorts.com/en/ajax/more_news'
35 | news_offset = "apwuhnrm-1"
36 |
37 | while True:
38 | response = requests.post(url, data={"category": "", "news_offset": news_offset}, headers=get_headers())
39 | if response.status_code != 200:
40 | print(response.status_code)
41 | break
42 |
43 | response_json = json.loads(response.text)
44 | print_headlines(response_json["html"])
45 | news_offset = response_json["min_news_id"]
46 |
--------------------------------------------------------------------------------
/olx-location-scrape.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import time
4 |
5 | url = "https://www.olx.in/api/locations?parent={parent_location}&withStats=true&hideAddressComponents=true&lang=en-IN"
6 |
7 | headers = {
8 | 'authority': 'www.olx.in',
9 | 'accept': '*/*',
10 | 'accept-language': 'en-GB,en;q=0.9',
11 | 'cookie': 'bm_sv=DFF51C5DF6385866C12732BC2F3D291C~YAAQvyEPF+iEEFiFAQAAUwC3WRI4JpG0IPgyWlh8nRH+DNHVAiK26LYDu3uEGpFRy9R8jNGi4VrUjcUS9RNfvPwvJKKcFXOGq6FxRErkoljeNDlTUdcfbzorVFUF/wwx5qSSrggf4vid/UuClaqMKmmjCyidFaoJCMVOZslp93VuwUfh1ohLqbntmxygnvrXI5sboH1Cu1j8rnBwppPkHUujmg48Nrl5PE/5wQbwQ8/BQhqrGV84fXELYfjIzUZs9w==~1',
12 | 'referer': 'https://www.olx.in/post/attributes',
13 | 'sec-fetch-dest': 'empty',
14 | 'sec-fetch-mode': 'cors',
15 | 'sec-fetch-site': 'same-origin',
16 | 'sec-gpc': '1',
17 | 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
18 | 'x-panamera-fingerprint': '103da644705db87cc823a99d71e93bce#1672235552859'
19 | }
20 |
21 | ############## step 1 - get the response of fetching states and dump in a file ##############
22 | ############## Now get the cities in each state by hitting the curl #########################
23 | ############## If 401 response, get the new cookies from browser and use them ###############
24 |
25 | # state_data = None
26 | # with open("/home/rana/parent-state.txt", "r") as fh:
27 | # state_data = fh.read()
28 | #
29 | #
30 | # state_data = json.loads(state_data)
31 | # print(state_data)
32 | # print(type(state_data))
33 | #
34 | # state_data = state_data['data']
35 | # for state in state_data:
36 | # response = requests.get(url.format(parent_location=state['id']), headers=headers)
37 | #
38 | # print(response.status_code)
39 | #
40 | # with open("/home/rana/city_" + str(state['id'] ) + '.txt', 'w') as f:
41 | # f.write(response.text)
42 | # time.sleep(5)
43 |
44 | ########## step 2 - get all cities from the cities files ##############################
45 | # import os
46 | #
47 | # files = os.listdir("/home/rana/")
48 | #
49 | # all_cities = []
50 | #
51 | # for f in files:
52 | # if "city_" in f:
53 | # print(f)
54 | # with open("/home/rana/" + f, 'r') as fh:
55 | # data = fh.read()
56 | # data = json.loads(data)
57 | # data = data['data']
58 | # for city in data:
59 | # city.pop('stats', None)
60 | # all_cities.append(city)
61 | #
62 | # with open("/home/rana/" + 'all_cities.txt', 'w') as fh:
63 | # fh.write(json.dumps(all_cities))
64 |
65 |
66 |
67 | ############# step 3 - for each city, get locality list ################
68 |
69 | # city_data = None
70 | # with open("/home/rana/all_cities.txt", "r") as fh:
71 | # city_data = fh.read()
72 | #
73 | #
74 | # city_data = json.loads(city_data)
75 | #
76 | # cookies = None
77 | #
78 | # for city in city_data:
79 | # if cookies is None:
80 | # response = requests.get(url.format(parent_location=city['id']), headers=headers)
81 | # else:
82 | # # if we have collected cookies from response, use them for next request
83 | # headers.pop('cookie', None)
84 | # response = requests.get(url.format(parent_location=city['id']), headers=headers, cookies=cookies)
85 | #
86 | # print(response.status_code)
87 | # if response.status_code == 401:
88 | # exit
89 | #
90 | # if response.status_code == 200:
91 | # with open("/home/rana/locality/locality_" + str(city['id'] ) + '.txt', 'w') as f:
92 | # f.write(response.text)
93 | #
94 | # for cookie in response.cookies:
95 | # print(cookie)
96 | #
97 | # # use cookie from this response in next request
98 | # cookies = response.cookies
99 | #
100 | # time.sleep(2)
101 |
102 |
103 | ############# step 4 - parse all state, city and locality files and store in DB or create a single JSON file ########
104 |
105 | # I have placed files in separate folder. Content is original as received from API
106 | home = '/home/rana/'
107 | state = home + 'state/'
108 | city = home + 'city/'
109 | locality = home + 'locality/'
110 |
111 |
112 |
113 |
114 |
--------------------------------------------------------------------------------
/one_million_websites.py:
--------------------------------------------------------------------------------
1 | # Scrap a website to fetch the URL of 1 million websites and dump them into a text file.
2 | # Author :- Anurag Rana
3 |
4 | import requests
5 | from bs4 import BeautifulSoup
6 | import sys
7 | import time
8 |
9 |
10 | headers = {
11 | "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
12 | "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
13 | "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/64.0.3282.167 Chrome/64.0.3282.167 Safari/537.36"
14 | }
15 |
16 | site_link_count = 0
17 |
18 | for i in range(1, 201):
19 | url = "http://websitelists.in/website-list-" + str(i) + ".html"
20 | response = requests.get(url, headers = headers)
21 | if response.status_code != 200:
22 | print(url + str(response.status_code))
23 | continue
24 |
25 | soup = BeautifulSoup(response.text, 'lxml')
26 | sites = soup.find_all("td",{"class": "web_width"})
27 |
28 | links = ""
29 | for site in sites:
30 | site = site.find("a")["href"]
31 | links += site + "\n"
32 | site_link_count += 1
33 |
34 | with open("one_million_websites.txt", "a") as f:
35 | f.write(links)
36 |
37 | print(str(site_link_count) + " links found")
38 |
39 | time.sleep(1)
40 |
41 |
42 |
--------------------------------------------------------------------------------
/permission.py:
--------------------------------------------------------------------------------
1 | #
2 | # programm to convert from octal to string representation of linux file perminssions
3 | # Author: https://www.pythoncircle.com
4 | #
5 |
6 | def octal_to_string(octal):
7 | result = ""
8 | value_letters = [(4,"r"),(2,"w"),(1,"x")]
9 | # Iterate over each of the digits in octal
10 | for digit in [int(n) for n in str(octal)]:
11 | # Check for each of the permissions values
12 | for value, letter in value_letters:
13 | if digit >= value:
14 | result += letter
15 | digit -= value
16 | else:
17 | result += '-'
18 | return result
19 |
20 | print(octal_to_string(755)) # Should be rwxr-xr-x
21 | print(octal_to_string(644)) # Should be rw-r--r--
22 | print(octal_to_string(750)) # Should be rwxr-x---
23 | print(octal_to_string(600)) # Should be rw-------
24 |
--------------------------------------------------------------------------------
/snake_ladder.py:
--------------------------------------------------------------------------------
1 | #
2 | # Text based snake and ladder game
3 | # Author - https://www.pythoncircle.com
4 | #
5 |
6 | import time
7 | import random
8 | import sys
9 |
10 | # just of effects. add a delay of 1 second before performing any action
11 | SLEEP_BETWEEN_ACTIONS = 1
12 | MAX_VAL = 100
13 | DICE_FACE = 6
14 |
15 | # snake takes you down from 'key' to 'value'
16 | snakes = {
17 | 8: 4,
18 | 18: 1,
19 | 26: 10,
20 | 39: 5,
21 | 51: 6,
22 | 54: 36,
23 | 56: 1,
24 | 60: 23,
25 | 75: 28,
26 | 83: 45,
27 | 85: 59,
28 | 90: 48,
29 | 92: 25,
30 | 97: 87,
31 | 99: 63
32 | }
33 |
34 | # ladder takes you up from 'key' to 'value'
35 | ladders = {
36 | 3: 20,
37 | 6: 14,
38 | 11: 28,
39 | 15: 34,
40 | 17: 74,
41 | 22: 37,
42 | 38: 59,
43 | 49: 67,
44 | 57: 76,
45 | 61: 78,
46 | 73: 86,
47 | 81: 98,
48 | 88: 91
49 | }
50 |
51 | player_turn_text = [
52 | "Your turn.",
53 | "Go.",
54 | "Please proceed.",
55 | "Lets win this.",
56 | "Are you ready?",
57 | "",
58 | ]
59 |
60 | snake_bite = [
61 | "boohoo",
62 | "bummer",
63 | "snake bite",
64 | "oh no",
65 | "dang"
66 | ]
67 |
68 | ladder_jump = [
69 | "woohoo",
70 | "woww",
71 | "nailed it",
72 | "oh my God...",
73 | "yaayyy"
74 | ]
75 |
76 |
77 | def welcome_msg():
78 | msg = """
79 | Welcome to Snake and Ladder Game.
80 | Version: 1.0.0
81 | Developed by: https://www.pythoncircle.com
82 |
83 | Rules:
84 | 1. Initally both the players are at starting position i.e. 0.
85 | Take it in turns to roll the dice.
86 | Move forward the number of spaces shown on the dice.
87 | 2. If you lands at the bottom of a ladder, you can move up to the top of the ladder.
88 | 3. If you lands on the head of a snake, you must slide down to the bottom of the snake.
89 | 4. The first player to get to the FINAL position is the winner.
90 | 5. Hit enter to roll the dice.
91 |
92 | """
93 | print(msg)
94 |
95 |
96 | def get_player_names():
97 | player1_name = None
98 | while not player1_name:
99 | player1_name = input("Please enter a valid name for first player: ").strip()
100 |
101 | player2_name = None
102 | while not player2_name:
103 | player2_name = input("Please enter a valid name for second player: ").strip()
104 |
105 | print("\nMatch will be played between '" + player1_name + "' and '" + player2_name + "'\n")
106 | return player1_name, player2_name
107 |
108 |
109 | def get_dice_value():
110 | time.sleep(SLEEP_BETWEEN_ACTIONS)
111 | dice_value = random.randint(1, DICE_FACE)
112 | print("Its a " + str(dice_value))
113 | return dice_value
114 |
115 |
116 | def got_snake_bite(old_value, current_value, player_name):
117 | print("\n" + random.choice(snake_bite).upper() + " ~~~~~~~~>")
118 | print("\n" + player_name + " got a snake bite. Down from " + str(old_value) + " to " + str(current_value))
119 |
120 |
121 | def got_ladder_jump(old_value, current_value, player_name):
122 | print("\n" + random.choice(ladder_jump).upper() + " ########")
123 | print("\n" + player_name + " climbed the ladder from " + str(old_value) + " to " + str(current_value))
124 |
125 |
126 | def snake_ladder(player_name, current_value, dice_value):
127 | time.sleep(SLEEP_BETWEEN_ACTIONS)
128 | old_value = current_value
129 | current_value = current_value + dice_value
130 |
131 | if current_value > MAX_VAL:
132 | print("You need " + str(MAX_VAL - old_value) + " to win this game. Keep trying.")
133 | return old_value
134 |
135 | print("\n" + player_name + " moved from " + str(old_value) + " to " + str(current_value))
136 | if current_value in snakes:
137 | final_value = snakes.get(current_value)
138 | got_snake_bite(current_value, final_value, player_name)
139 |
140 | elif current_value in ladders:
141 | final_value = ladders.get(current_value)
142 | got_ladder_jump(current_value, final_value, player_name)
143 |
144 | else:
145 | final_value = current_value
146 |
147 | return final_value
148 |
149 |
150 | def check_win(player_name, position):
151 | time.sleep(SLEEP_BETWEEN_ACTIONS)
152 | if MAX_VAL == position:
153 | print("\n\n\nThats it.\n\n" + player_name + " won the game.")
154 | print("Congratulations " + player_name)
155 | print("\nThank you for playing the game. Please visit https://www.pythoncircle.com\n\n")
156 | sys.exit(1)
157 |
158 |
159 | def start():
160 | welcome_msg()
161 | time.sleep(SLEEP_BETWEEN_ACTIONS)
162 | player1_name, player2_name = get_player_names()
163 | time.sleep(SLEEP_BETWEEN_ACTIONS)
164 |
165 | player1_current_position = 0
166 | player2_current_position = 0
167 |
168 | while True:
169 | time.sleep(SLEEP_BETWEEN_ACTIONS)
170 | input_1 = input("\n" + player1_name + ": " + random.choice(player_turn_text) + " Hit the enter to roll dice: ")
171 | print("\nRolling dice...")
172 | dice_value = get_dice_value()
173 | time.sleep(SLEEP_BETWEEN_ACTIONS)
174 | print(player1_name + " moving....")
175 | player1_current_position = snake_ladder(player1_name, player1_current_position, dice_value)
176 |
177 | check_win(player1_name, player1_current_position)
178 |
179 | input_2 = input("\n" + player2_name + ": " + random.choice(player_turn_text) + " Hit the enter to roll dice: ")
180 | print("\nRolling dice...")
181 | dice_value = get_dice_value()
182 | time.sleep(SLEEP_BETWEEN_ACTIONS)
183 | print(player2_name + " moving....")
184 | player2_current_position = snake_ladder(player2_name, player2_current_position, dice_value)
185 |
186 | check_win(player2_name, player2_current_position)
187 |
188 |
189 | if __name__ == "__main__":
190 | start()
191 |
--------------------------------------------------------------------------------
/stackoverflow_most_popular_technology.py:
--------------------------------------------------------------------------------
1 | # Script to find the most used tags in questions on stackoverflow
2 | # Author - Anurag Rana
3 | # version - 1.0.0
4 | # usage - python script_name
5 |
6 |
7 | import operator, os, sys
8 | import requests
9 | from bs4 import BeautifulSoup
10 |
11 |
12 | # global dictionary to store the count of tags processed so far
13 | tag_count_dict = {}
14 |
15 |
16 | def get_soup_from_link(link):
17 | html_text = requests.get(link).text
18 | soup = BeautifulSoup(html_text, 'html.parser')
19 | return soup
20 |
21 |
22 | def tag_crawler(question_url):
23 | soup = get_soup_from_link(question_url)
24 | tag_divs = soup.find_all('div', {'class': 'post-taglist'})
25 | for div in tag_divs:
26 | for tag_link in div.find_all('a'):
27 | tag = tag_link.string
28 | if tag is not None:
29 | tag_count_dict[tag] = tag_count_dict[tag] + 1 if tag in tag_count_dict else 1
30 | # print a dot to indicate script is progressing.
31 | print(".", end="")
32 | sys.stdout.flush()
33 |
34 |
35 | def get_question_links(soup):
36 | return soup.find_all('a', {'class': 'question-hyperlink'})
37 |
38 |
39 | def page_crawler(max_page_count):
40 | starting_url = 'http://stackoverflow.com/questions?page=PAGE_NUMBER&sort=newest'
41 | current_page_number = 1
42 | while current_page_number <= max_page_count:
43 | current_page_url = starting_url.replace('PAGE_NUMBER',str(current_page_number))
44 | soup = get_soup_from_link(current_page_url)
45 | print('Working on page number : ' + str(current_page_number))
46 | # get link of all question posted on current page
47 | question_links = get_question_links(soup)
48 | for link in question_links:
49 | question_url = 'http://stackoverflow.com/' + link.get('href')
50 | # crawl all tags on this question page
51 | tag_crawler(question_url)
52 |
53 | current_page_number += 1
54 |
55 |
56 | def print_welcome_msg():
57 | os.system('clear')
58 | print("\n\n")
59 | print("This script will crwal stackoverflow pages to fetch the count of occurances of tags.")
60 | print("And then print the top 10 tags hence predicting the most popular technology on stackoverflow.")
61 | print("Next we will ask you the number of pages to crawl.")
62 | print("Remember, more the pages, better is the accuracy but at the same time script will run longer.")
63 | print('\n\nHow many pages would you like to crawl : ', end="")
64 |
65 |
66 | def start():
67 | print_welcome_msg()
68 | max_page_count = int(input().strip())
69 | print('Starting now....')
70 | page_crawler(max_page_count)
71 | sorted_tag_count_dict = sorted(tag_count_dict.items(), key=operator.itemgetter(1), reverse=True)[:10]
72 | print("")
73 | for tag_count in sorted_tag_count_dict:
74 | print("%15s : %d" %(tag_count[0], tag_count[1]))
75 |
76 | start()
77 |
--------------------------------------------------------------------------------
/stopwords.txt:
--------------------------------------------------------------------------------
1 | ourselves
2 | hers
3 | between
4 | yourself
5 | but
6 | again
7 | there
8 | about
9 | once
10 | during
11 | out
12 | very
13 | having
14 | with
15 | they
16 | own
17 | an
18 | be
19 | some
20 | for
21 | do
22 | its
23 | yours
24 | such
25 | into
26 | of
27 | most
28 | itself
29 | other
30 | off
31 | is
32 | s
33 | am
34 | or
35 | who
36 | as
37 | from
38 | him
39 | each
40 | the
41 | themselves
42 | until
43 | below
44 | are
45 | we
46 | these
47 | your
48 | his
49 | through
50 | don
51 | nor
52 | me
53 | were
54 | her
55 | more
56 | himself
57 | this
58 | down
59 | should
60 | our
61 | their
62 | while
63 | above
64 | both
65 | up
66 | to
67 | ours
68 | had
69 | she
70 | all
71 | no
72 | when
73 | at
74 | any
75 | before
76 | them
77 | same
78 | and
79 | been
80 | have
81 | in
82 | will
83 | on
84 | does
85 | yourselves
86 | then
87 | that
88 | because
89 | what
90 | over
91 | why
92 | so
93 | can
94 | did
95 | not
96 | now
97 | under
98 | he
99 | you
100 | herself
101 | has
102 | just
103 | where
104 | too
105 | only
106 | myself
107 | which
108 | those
109 | i
110 | after
111 | few
112 | whom
113 | t
114 | being
115 | if
116 | theirs
117 | my
118 | against
119 | a
120 | by
121 | doing
122 | it
123 | how
124 | further
125 | was
126 | here
127 | than
--------------------------------------------------------------------------------
/system_information.py:
--------------------------------------------------------------------------------
1 | #
2 | # Python script to fetch system information
3 | # Author - ThePythonDjango.Com
4 | # Tested with Python3 on Ubuntu 16.04
5 | #
6 |
7 | import platform
8 |
9 | # Architecture
10 | print("Architecture: " + platform.architecture()[0])
11 |
12 | # machine
13 | print("Machine: " + platform.machine())
14 |
15 | # node
16 | print("Node: " + platform.node())
17 |
18 | # processor
19 | print("Processors: ")
20 | with open("/proc/cpuinfo", "r") as f:
21 | info = f.readlines()
22 |
23 | cpuinfo = [x.strip().split(":")[1] for x in info if "model name" in x]
24 | for index, item in enumerate(cpuinfo):
25 | print(" " + str(index) + ": " + item)
26 |
27 | # system
28 | print("System: " + platform.system())
29 |
30 | # distribution
31 | dist = platform.dist()
32 | dist = " ".join(x for x in dist)
33 | print("Distribution: " + dist)
34 |
35 | # Load
36 | with open("/proc/loadavg", "r") as f:
37 | print("Average Load: " + f.read().strip())
38 |
39 | # Memory
40 | print("Memory Info: ")
41 | with open("/proc/meminfo", "r") as f:
42 | lines = f.readlines()
43 |
44 | print(" " + lines[0].strip())
45 | print(" " + lines[1].strip())
46 |
47 | # uptime
48 | uptime = None
49 | with open("/proc/uptime", "r") as f:
50 | uptime = f.read().split(" ")[0].strip()
51 | uptime = int(float(uptime))
52 | uptime_hours = uptime // 3600
53 | uptime_minutes = (uptime % 3600) // 60
54 | print("Uptime: " + str(uptime_hours) + ":" + str(uptime_minutes) + " hours")
55 |
--------------------------------------------------------------------------------
/tkinter_gui_file_upload.py:
--------------------------------------------------------------------------------
1 | import tkinter as tk
2 | from tkinter import filedialog
3 | import hashlib
4 |
5 |
6 | def copy_button():
7 | window.clipboard_clear()
8 | window.clipboard_append(checksum_entry.get())
9 | label_file_explorer.configure(
10 | text="Checksum copies to clipboard. Save it to somewhere safe before closing this window")
11 |
12 |
13 | def browse_files():
14 | filename = filedialog.askopenfilename(initialdir="/",
15 | title="Select a File",
16 | filetypes=(
17 | ("All files",
18 | "*.*"),
19 | ))
20 |
21 | # if we click on upload file button but then click cancel
22 | if not filename or not isinstance(filename, str):
23 | label_file_explorer.configure(text="No file uploaded.")
24 | return
25 |
26 | # read file in binary mode.
27 | with open(filename, "rb") as input_file:
28 | # text is bytes type in rb mode
29 | text = input_file.read()
30 |
31 | # checksum of whole text at once
32 | checksum = hashlib.sha256(text).hexdigest()
33 | print("complete file checksum: " + checksum) # type is string
34 |
35 | # calculating checksum for one byte at a time and updating the hash
36 | byte_count = len(text)
37 | byte_chunks = [text[i: i + 2] for i in range(0, byte_count, 2)]
38 | # new hash object with sha256 algorithm
39 | h = hashlib.new('sha256')
40 | for single_byte in byte_chunks:
41 | h.update(single_byte)
42 |
43 | # final checksum of hash
44 | combined_checksum = h.hexdigest()
45 |
46 | print("byte by byte checksum: " + combined_checksum)
47 |
48 | msg = "File Opened: " + filename
49 | # Change label contents
50 | label_file_explorer.configure(text=msg)
51 |
52 | # clear the entry field before inserting checksum there
53 | checksum_entry.delete(0, tk.END)
54 | checksum_entry.insert(0, checksum)
55 |
56 |
57 | # starting program
58 | window = tk.Tk()
59 | window.title('File Checksum Generator')
60 | title = tk.Label(text="Generate file checksum. Upload a file.", pady=20)
61 | title.pack()
62 |
63 | label_file_explorer = tk.Label(window, text="", width=100, height=4, pady=10)
64 | button_explore = tk.Button(window, text="Browse Files", command=browse_files, pady=20)
65 | button_copy = tk.Button(window, text="Copy Checksum", command=copy_button, pady=10)
66 | button_exit = tk.Button(window, text="Exit", command=exit, pady=10)
67 |
68 | checksum_entry = tk.Entry(width=70)
69 | checksum_entry.insert(0, "Checksum will appear here")
70 |
71 | button_explore.pack()
72 | label_file_explorer.pack()
73 | checksum_entry.pack()
74 | button_copy.pack()
75 | button_exit.pack()
76 |
77 | window.mainloop()
78 |
--------------------------------------------------------------------------------
/tweets_scrapper.py:
--------------------------------------------------------------------------------
1 | # script to scrap tweets by a twitter user.
2 | # Author - ThePythonDjango.Com
3 | # dependencies - BeautifulSoup, requests
4 |
5 | from bs4 import BeautifulSoup
6 | import requests
7 | import sys
8 | import json
9 |
10 |
11 | def usage():
12 | msg = """
13 | Please use the below command to use the script.
14 | python script_name.py twitter_username
15 | """
16 | print(msg)
17 | sys.exit(1)
18 |
19 |
20 | def get_tweet_text(tweet):
21 | tweet_text_box = tweet.find("p", {"class": "TweetTextSize TweetTextSize--normal js-tweet-text tweet-text"})
22 | images_in_tweet_tag = tweet_text_box.find_all("a", {"class": "twitter-timeline-link u-hidden"})
23 | tweet_text = tweet_text_box.text
24 | for image_in_tweet_tag in images_in_tweet_tag:
25 | tweet_text = tweet_text.replace(image_in_tweet_tag.text, '')
26 |
27 | return tweet_text
28 |
29 | def get_this_page_tweets(soup):
30 | tweets_list = list()
31 | tweets = soup.find_all("li", {"data-item-type": "tweet"})
32 | for tweet in tweets:
33 | tweet_data = None
34 | try:
35 | tweet_data = get_tweet_text(tweet)
36 | except Exception as e:
37 | continue
38 | #ignore if there is any loading or tweet error
39 |
40 | if tweet_data:
41 | tweets_list.append(tweet_data)
42 | print(".", end="")
43 | sys.stdout.flush()
44 |
45 | return tweets_list
46 |
47 |
48 | def get_tweets_data(username, soup):
49 | tweets_list = list()
50 | tweets_list.extend(get_this_page_tweets(soup))
51 |
52 | next_pointer = soup.find("div", {"class": "stream-container"})["data-min-position"]
53 |
54 | while True:
55 | next_url = "https://twitter.com/i/profiles/show/" + username + \
56 | "/timeline/tweets?include_available_features=1&" \
57 | "include_entities=1&max_position=" + next_pointer + "&reset_error_state=false"
58 |
59 | next_response = None
60 | try:
61 | next_response = requests.get(next_url)
62 | except Exception as e:
63 | # in case there is some issue with request. None encountered so far.
64 | print(e)
65 | return tweets_list
66 |
67 | tweets_data = next_response.text
68 | tweets_obj = json.loads(tweets_data)
69 | if not tweets_obj["has_more_items"] and not tweets_obj["min_position"]:
70 | # using two checks here bcz in one case has_more_items was false but there were more items
71 | print("\nNo more tweets returned")
72 | break
73 | next_pointer = tweets_obj["min_position"]
74 | html = tweets_obj["items_html"]
75 | soup = BeautifulSoup(html, 'lxml')
76 | tweets_list.extend(get_this_page_tweets(soup))
77 |
78 | return tweets_list
79 |
80 |
81 | # dump final result in a json file
82 | def dump_data(username, tweets):
83 | filename = username+"_twitter.json"
84 | print("\nDumping data in file " + filename)
85 | data = dict()
86 | data["tweets"] = tweets
87 | with open(filename, 'w') as fh:
88 | fh.write(json.dumps(data))
89 |
90 | return filename
91 |
92 |
93 | def get_username():
94 | # if username is not passed
95 | if len(sys.argv) < 2:
96 | usage()
97 | username = sys.argv[1].strip().lower()
98 | if not username:
99 | usage()
100 |
101 | return username
102 |
103 |
104 | def start(username = None):
105 | username = get_username()
106 | url = "http://www.twitter.com/" + username
107 | print("\n\nDownloading tweets for " + username)
108 | response = None
109 | try:
110 | response = requests.get(url)
111 | except Exception as e:
112 | print(repr(e))
113 | sys.exit(1)
114 |
115 | if response.status_code != 200:
116 | print("Non success status code returned "+str(response.status_code))
117 | sys.exit(1)
118 |
119 | soup = BeautifulSoup(response.text, 'lxml')
120 |
121 | if soup.find("div", {"class": "errorpage-topbar"}):
122 | print("\n\n Error: Invalid username.")
123 | sys.exit(1)
124 |
125 | tweets = get_tweets_data(username, soup)
126 | # dump data in a text file
127 | dump_data(username, tweets)
128 | print(str(len(tweets))+" tweets dumped.")
129 |
130 |
131 | start()
132 |
--------------------------------------------------------------------------------
/usa_flag.py:
--------------------------------------------------------------------------------
1 | #
2 | # Author - https://www.pythoncircle.com
3 | #
4 |
5 | import turtle
6 | import time
7 |
8 | # create a screen
9 | screen = turtle.getscreen()
10 | # set background color of screen
11 | screen.bgcolor("white")
12 | # set tile of screen
13 | screen.title("USA Flag - https://www.pythoncircle.com")
14 | # "Yesterday is history, tomorrow is a mystery,
15 | # but today is a gift. That is why it is called the present.”
16 | # — Oogway to Po, under the peach tree, Kung Fu Panda Movie
17 | oogway = turtle.Turtle()
18 | # set the cursor/turtle speed. Higher value, faster is the turtle
19 | oogway.speed(100)
20 | oogway.penup()
21 | # decide the shape of cursor/turtle
22 | oogway.shape("turtle")
23 |
24 | # flag height to width ratio is 1:1.9
25 | flag_height = 250
26 | flag_width = 475
27 |
28 | # starting points
29 | # start from the first quardant, half of flag width and half of flag height
30 | start_x = -237
31 | start_y = 125
32 |
33 | # For red and white stripes (total 13 stripes in flag), each strip width will be flag_height/13 = 19.2 approx
34 | stripe_height = flag_height/13
35 | stripe_width = flag_width
36 |
37 | # length of one arm of star
38 | star_size = 10
39 |
40 |
41 | def draw_fill_rectangle(x, y, height, width, color):
42 | oogway.goto(x,y)
43 | oogway.pendown()
44 | oogway.color(color)
45 | oogway.begin_fill()
46 | oogway.forward(width)
47 | oogway.right(90)
48 | oogway.forward(height)
49 | oogway.right(90)
50 | oogway.forward(width)
51 | oogway.right(90)
52 | oogway.forward(height)
53 | oogway.right(90)
54 | oogway.end_fill()
55 | oogway.penup()
56 |
57 | def draw_star(x,y,color,length) :
58 | oogway.goto(x,y)
59 | oogway.setheading(0)
60 | oogway.pendown()
61 | oogway.begin_fill()
62 | oogway.color(color)
63 | for turn in range(0,5) :
64 | oogway.forward(length)
65 | oogway.right(144)
66 | oogway.forward(length)
67 | oogway.right(144)
68 | oogway.end_fill()
69 | oogway.penup()
70 |
71 |
72 | # this function is used to create 13 red and white stripes of flag
73 | def draw_stripes():
74 | x = start_x
75 | y = start_y
76 | # we need to draw total 13 stripes, 7 red and 6 white
77 | # so we first create, 6 red and 6 white stripes alternatively
78 | for stripe in range(0,6):
79 | for color in ["red", "white"]:
80 | draw_fill_rectangle(x, y, stripe_height, stripe_width, color)
81 | # decrease value of y by stripe_height
82 | y = y - stripe_height
83 |
84 | # create last red stripe
85 | draw_fill_rectangle(x, y, stripe_height, stripe_width, 'red')
86 | y = y - stripe_height
87 |
88 |
89 | # this function create navy color square
90 | # height = 7/13 of flag_height
91 | # width = 0.76 * flag_height
92 | # check references section for these values
93 | def draw_square():
94 | square_height = (7/13) * flag_height
95 | square_width = (0.76) * flag_height
96 | draw_fill_rectangle(start_x, start_y, square_height, square_width, 'navy')
97 |
98 |
99 | def draw_six_stars_rows():
100 | gap_between_stars = 30
101 | gap_between_lines = stripe_height + 6
102 | y = 112
103 | # create 5 rows of stars
104 | for row in range(0,5) :
105 | x = -222
106 | # create 6 stars in each row
107 | for star in range (0,6) :
108 | draw_star(x, y, 'white', star_size)
109 | x = x + gap_between_stars
110 | y = y - gap_between_lines
111 |
112 |
113 | def draw_five_stars_rows():
114 | gap_between_stars = 30
115 | gap_between_lines = stripe_height + 6
116 | y = 100
117 | # create 4 rows of stars
118 | for row in range(0,4) :
119 | x = -206
120 | # create 5 stars in each row
121 | for star in range (0,5) :
122 | draw_star(x, y, 'white', star_size)
123 | x = x + gap_between_stars
124 | y = y - gap_between_lines
125 |
126 | # start after 5 seconds.
127 | time.sleep(5)
128 | # draw 13 stripes
129 | draw_stripes()
130 | # draw squares to hold stars
131 | draw_square()
132 | # draw 30 stars, 6 * 5
133 | draw_six_stars_rows()
134 | # draw 20 stars, 5 * 4. total 50 stars representing 50 states of USA
135 | draw_five_stars_rows()
136 | # hide the cursor/turtle
137 | oogway.hideturtle()
138 | # keep holding the screen until closed manually
139 | screen.mainloop()
140 |
141 |
--------------------------------------------------------------------------------
/vaccine_slot_availability.py:
--------------------------------------------------------------------------------
1 | # python script to notify if a covid vaccine slot is available in selected district in India
2 | # need python3 and below packages. install using command -> pip install requests
3 | # command to run script -> python3 vaccine_slot_availability.py
4 | # Author: Anurag Rana (https://pythoncircle.com)
5 |
6 | import json
7 | import time
8 | import requests
9 | import os
10 | import sys
11 |
12 | # find your district ID from cowin site drop downs
13 | district_id = "679"
14 | date = "04-06-2021"
15 | url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id=" + district_id + "&date=" + date
16 |
17 | payload = {}
18 | headers = {
19 | 'authority': 'cdn-api.co-vin.in',
20 | 'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
21 | 'accept': 'application/json, text/plain, */*',
22 | 'sec-ch-ua-mobile': '?0',
23 | 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
24 | 'origin': 'https://www.cowin.gov.in',
25 | 'sec-fetch-site': 'cross-site',
26 | 'sec-fetch-mode': 'cors',
27 | 'sec-fetch-dest': 'empty',
28 | 'referer': 'https://www.cowin.gov.in/',
29 | 'accept-language': 'en-IN,en-US;q=0.9,en;q=0.8,hi;q=0.7',
30 | 'if-none-match': 'W/"24cd1-gIUHe5EIOLD2Ovtn3sxK2S91wZk"'
31 | }
32 |
33 |
34 | def send_alert(name, count):
35 | for i in range(3):
36 | os.system("spd-say '" + str(count) + " Slot Available at " + name + "'")
37 | time.sleep(5)
38 |
39 |
40 | def search():
41 | response = requests.request("GET", url, headers=headers, data=payload)
42 | # print(response.text)
43 | response = json.loads(response.text)
44 |
45 | slot_found = False
46 |
47 | centers = response.get("centers")
48 | for center in centers:
49 | if center.get("fee_type") == "Free":
50 | sessions = center.get("sessions")
51 | for session in sessions:
52 | if session.get("min_age_limit") == 18:
53 | if session.get("available_capacity_dose1") > 0:
54 | name = center.get("name")
55 | count = session.get("available_capacity_dose1")
56 | print(name, count)
57 | # preform an action. send notification, play an audio file, send sms etc
58 | send_alert(name, count)
59 | slot_found = True
60 | break
61 |
62 | if slot_found:
63 | sys.exit()
64 |
65 |
66 | def start():
67 | while True:
68 | search()
69 | print("Checking...")
70 | time.sleep(60)
71 |
72 |
73 | if __name__ == "__main__":
74 | start()
75 |
--------------------------------------------------------------------------------
/whl_file_dl.py:
--------------------------------------------------------------------------------
1 | #
2 | # python script to download all the whl files of packages mentioned in a requirements.txt file
3 | # Author - Anurag Rana
4 | # upload these whl files to nexus repo using twine command
5 | # twine upload --repository nexus download_folder/*
6 | #
7 |
8 | import subprocess
9 |
10 | # Specify the file path
11 | file_path = "requirements.txt"
12 |
13 | # Initialize an empty list to store the lines
14 | lines = []
15 |
16 | # Open the file and read its contents line by line
17 | with open(file_path, "r") as file:
18 | for line in file:
19 | # Remove leading and trailing whitespace (e.g., newline characters)
20 | line = line.strip()
21 | # Append the cleaned line to the list
22 | lines.append(line)
23 |
24 | # Now 'lines' contains each line from the file as separate elements
25 | print(lines)
26 |
27 | # List of package names for which you want to download .whl files
28 | package_names = lines # ["package1", "package2"]
29 |
30 | # Directory where you want to save the downloaded .whl files
31 | download_directory = "downloaded_whl_files"
32 |
33 | # Create the download directory if it doesn't exist
34 | subprocess.run(["mkdir", "-p", download_directory])
35 |
36 | # Loop through each package and download its .whl file
37 | for package_name in package_names:
38 | try:
39 | # Execute the 'pip download' command to download the .whl file
40 | subprocess.run(["pip", "download", "--dest", download_directory, package_name])
41 | print(f"Downloaded {package_name} to {download_directory}")
42 | except Exception as e:
43 | print(f"Error downloading {package_name}: {str(e)}")
44 |
45 | print("Download completed.")
46 |
--------------------------------------------------------------------------------
/who_let_the_dogs_out.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anuragrana/Python-Scripts/fda0186a0d7ba34f152a35107ca10876e9e9a7ec/who_let_the_dogs_out.mp3
--------------------------------------------------------------------------------
/word_cloud.py:
--------------------------------------------------------------------------------
1 | """
2 | Python script to generate word cloud image.
3 | Author - Anurag Rana
4 | Read more on - https://www.pythoncircle.com
5 | """
6 |
7 | from wordcloud import WordCloud
8 |
9 | # image configurations
10 | background_color = "#101010"
11 | height = 720
12 | width = 1080
13 |
14 | with open("stopwords.txt", "r") as f:
15 | stop_words = f.read().split()
16 |
17 | # Read a text file and calculate frequency of words in it
18 | with open("/tmp/sample_text.txt", "r") as f:
19 | words = f.read().split()
20 |
21 | data = dict()
22 |
23 | for word in words:
24 | word = word.lower()
25 | if word in stop_words:
26 | continue
27 |
28 | data[word] = data.get(word, 0) + 1
29 |
30 | word_cloud = WordCloud(
31 | background_color=background_color,
32 | width=width,
33 | height=height
34 | )
35 |
36 | word_cloud.generate_from_frequencies(data)
37 | word_cloud.to_file('image.png')
38 |
--------------------------------------------------------------------------------