from collections import Counter
d = [
{
"type": "STARK COUNTRY LINE INTERACTIVE 600",
"power": 360,
"execution": "floor",
"dimensions": "359х97х147",
"battery output signal": "synthesized sine",
"price": 9940
},
{
"type": "STARK COUNTRY LINE INTERACTIVE 1000 LI",
"power": 600,
"execution": "floor",
"dimensions": "395х145х220",
"battery output signal": "pure sine",
"price": 19374
},
{
"type": "STARK COUNTRY ONLINE 1000 ONLINE",
"power": 900,
"execution": "floor",
"dimensions": "397х145х220",
"battery output signal": "pure sine",
"price": 28639,
"discount": 'yes',
},
{
"type": "STARK COUNTRY ONLINE 1000 ONLINE RT",
"power": 900,
"execution": "floor",
"dimensions": "438х410х88",
"battery output signal": "pure sine",
"price": 29313
},
{
"type": "STARK COUNTRY ONLINE 1000 ONLINE",
"power": 800,
"execution": "floor",
"dimensions": "397х145х220",
"battery output signal": "pure sine",
"price": 23333
}
]
items = [item['type'] for item in d]
item, item_count = Counter(items).most_common()[0]
print(f'Most common item - {item}, duplicate - {item_count} times')
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import showerror, showinfo
root = Tk()
root.geometry("250x200")
def clear():
entry_username.delete(0, END)
entry_password.delete(0, END)
def open_info():
showinfo(title="Info", message="Connected")
def open_error():
showerror(title="Error", message="Incorrect input")
def connect_to_db():
accepted_user = 'admin'
accepted_password = 'admin'
try:
print('Connect to DB')
username = entry_username.get()
password = entry_password.get()
if accepted_user == username and password == accepted_password:
open_info()
else:
open_error()
except Exception:
open_error()
finally:
clear()
label_username = ttk.Label(text = "USERNAME")
label_username.pack(anchor=NW, padx=6, pady=6)
entry_username = ttk.Entry()
entry_username.pack(anchor=NW, padx=6, pady=6)
label_password = ttk.Label(text = "PASSWORD")
label_password.pack(anchor=NW, padx=6, pady=6)
entry_password = ttk.Entry()
entry_password.pack(anchor=NW, padx=6, pady=6)
display_button = ttk.Button(text="Connect", command=connect_to_db)
display_button.pack(side=LEFT, anchor=N, padx=6, pady=6)
clear_button = ttk.Button(text="Clear", command=clear)
clear_button.pack(side=LEFT, anchor=N, padx=6, pady=6)
root.mainloop()
>>> class Duck:
... def __init__(self, color):
... self.color = color
... def get_color(self):
... return self.color
...
>>>
>>>
>>> d = Duck('orange')
>>> d
<__main__.Duck object at 0x000001F569CDEA08>
>>> dir(d)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'color', 'get_color']
>>> callable(d.color)
False
>>> callable(d.get_color)
True
users_text = [message.text]
mistake = 0
def mistake1(word):
global mistake
if s =='a':
mistake += 1
print("Mistake increment")
else:
mistake -= 1
print("Mistake decrement")
if __name__ == "__main__":
ask_flag = True
while ask_flag:
try:
s = input("Input word: ")
if s != "q":
mistake1(s)
except KeyboardInterrupt:
ask_flag = False
print(f"Current Count mistake = {mistake}")
print('Exit')
def _report_GaussianNB(self):
report_GaussianNB = classification_report(y_train.values, pred_train_GaussianNB)
return report_GaussianNB
def decode_str(text: str):
type_text, string_num = text.split("#")
string_text, num_text = string_num.split("&")
return type_text, string_text, num_text
test_string = [
"str#qwerty&444",
"asd#omg&777122",
"hjkl#adsf&8811"
]
for t in test_string:
result = decode_str(t)
print(f"decode string - {t}")
print(f"result decode - {result}")
import os
import subprocess
retcode = subprocess.call(['echo', 'foo'],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
@bot.message_handler(content_types=["text"])
def send_photo(message):
if message.text == "Картиночка":
img_dir = r'C:\Projects\telebot_test_functions\photo'
images = [os.path.join(img_dir, img) for img in os.listdir(img_dir) if img.endswith('png')]
random_img = random.choice(images)
if random_img:
photo = open(random_img, 'rb')
bot.send_photo(message.chat.id, photo)
else:
bot.send_photo(message.chat.id, "нет картинки")
from random import randint
from json import JSONEncoder
class TestCase:
def __init__(self, name: str):
self.id = randint(0, 999)
self.name = name
self.steps = dict()
self.result = str()
def set_step(self, step_number: int, step_text: str):
self.steps[step_number] = step_text
def delete_step(self, step_number: int):
if self.steps.get(step_number) is not None:
self.steps.pop(step_number)
def get_steps(self) -> dict:
return self.steps
def set_result(self, result: str):
self.result = result
def get_test_case(self):
current_result = TestCaseEncoder(ensure_ascii=False, indent=4).encode(self)
print(current_result)
return current_result
class TestCaseEncoder(JSONEncoder):
def default(self, o):
json_object = {
'id': o.__dict__.get('id'),
'Название': o.__dict__.get('name'),
'Шаги': o.__dict__.get('steps'),
'Ожидаемый результат': o.__dict__.get('result')
}
return json_object
t = TestCase(name="Test")
t.set_step(1, 'Перейти на сайт')
t.set_step(2, 'Перейти в раздел Товары')
t.set_step(3, 'Нажать кнопку «В корзину» у первого товара')
t.set_result(result='Товар окажется в корзине')
t.get_test_case()
t.delete_step(2)
t.get_test_case()
self.connection = pymysql.connect(host='localhost', port=3306, user='root', password='',
db='aiodb')
self.cursor = self.connection.cursor()
class Database:
def __init__(self, config):
self.config = config
self.connection = pymysql.connect(**self.config)
def execute(self, query: str, params: tuple = None):
try:
with self.connection as connect:
cursor = connect.cursor()
if params is not None:
cursor.execute(query, params)
else:
cursor.execute(query)
return cursor.fetchall()
except OperationalError as Error:
print(Error)
class Person:
def __init__(self, name):
self.name = name
self.something_1 = 'abc'
self.something_2 = 123
def check_attr(obj, attr_name):
try:
value = obj.__getattribute__(attr_name)
return f'{obj} имеет аттрибут - {attr_name} со значением - {value}'
except AttributeError:
return f'{obj} не имеет аттрибута - {attr_name}'
if __name__ == "__main__":
p = Person(name='Alex')
print(check_attr(p, 'something_1'))
print(check_attr(p, 'something_2'))
print(check_attr(p, 'something_33333'))
import time
from random import choice
from threading import Thread
version = [
{'language': 'Навахо', 'phrase': 'Ayóó ánííníshí', 'pronunciation': 'Аийоо ианинииши'},
{'language': 'Гавайский', 'phrase': 'Aloha wau iā ʻoe', 'pronunciation': 'Алоха ва уйа ой'},
{'language': 'Бангладешский', 'phrase': 'আমিতোমাকেভালবাসি', 'pronunciation': 'Ами тумакэ палабаши'},
{'language': 'Латинский', 'phrase': 'Te amo', 'pronunciation': 'Тэ амо'},
]
def read_from_stdin():
while True:
input_phrase = input()
if input_phrase.lower() == 'love':
result = choice(version)
print(result['language'])
print(result['phrase'])
print(result['pronunciation'])
else:
print(f'unknown command - {input_phrase}')
def some_worker():
while True:
print("некая переписка")
time.sleep(5)
if __name__ == "__main__":
reader_t = Thread(target=read_from_stdin).start()
worker_t = Thread(target=some_worker).start()