Форум сайта python.su
import os import numpy import cv2 import shutil import math from PIL import Image, ImageEnhance
from urllib.request import urlretrieve import vk, os, time, math session = vk.Session(access_token="[u]Мой токен[/u]") vkapi = vk.API(session) url = input("Введите url альбома: ") album_id = url.split('/')[-1].split('_')[1] owner_id = url.split('/')[-1].split('_')[0].replace('album', '') print("album id: ", album_id) print("owner_id: ", owner_id) photos_count = vkapi.photos.getAlbums(owner_id=owner_id, album_ids=album_id)[0]["size"] counter = 0 # текущий счетчик prog = 0 # процент загруженных breaked = 0 # не загружено из-за ошибки time_now = time.time() # время старта # Создадим каталоги if not os.path.exists('saved'): os.mkdir('saved') photo_folder = 'saved/album{0}_{1}'.format(owner_id, album_id) if not os.path.exists(photo_folder): os.mkdir(photo_folder) for j in range(math.ceil( photos_count / 1000)): # Подсчитаем сколько раз нужно получать список фото, так как число получится не целое - округляем в большую сторону photos = vkapi.photos.get(owner_id=owner_id, album_id=album_id, count=1000, offset=j * 1000) # Получаем список фото for photo in photos: counter += 1 url = photo["src_big"] # Получаем адрес изображения print('Загружаю фото № {} из {}. Прогресс: {} %'.format(counter, photos_count, prog)) prog = round(100 / photos_count * counter, 2) try: urlretrieve(url, photo_folder + "/" + os.path.split(url)[1]) # Загружаем и сохраняем файл except Exception: print('Произошла ошибка, файл пропущен.') breaked += 1 continue time_for_dw = time.time() - time_now print("\nВ очереди было {} файлов. Из них удачно загружено {} файлов, {} не удалось загрузить. Затрачено времени: {} сек.". format(photos_count, photos_count-breaked, breaked, round(time_for_dw,1)))
exercise = db.Table( 'exercise', db.Column('programm_id', db.Integer, db.ForeignKey('programm.id'), primary_key=True), db.Column('exercise_id', db.Integer, db.ForeignKey('exercises.id'), primary_key=True) ) class Programm(Base): __tablename__ = 'programm' user_id = db.Column(db.Integer, db.ForeignKey('auth_user.id')) name = db.Column(db.Text) exercise = db.relationship('Exercises', secondary=exercise, lazy='subquery', backref=db.backref('programm', lazy=True), cascade='all, delete-orphan', single_parent=True)
def delete_programm(id): form = IdForm(formdata=MultiDict({'id': id})) if not form.validate(): return jsonify(error='Проверьте введеные данные!') instance = Programm.query.get(form.id.data) if instance is None: return jsonify(error="Object does not exist") if not instance.user_id == current_user.id: return jsonify(error='Отказано в доступе') try: db.session.delete(instance) db.session.commit() except SQLAlchemyError: return jsonify(error='Не удалось сохранить. Попробуйте позже.') return '', 200
class RabbitMQProcessConsumer(ConsumerMixin): def __init__( self, host, user, password, exchange, queue, vhost, insist, entity): self.host = host self.user = user self.password = password self.exchange_name = exchange self.queue_name = queue self.vhost = vhost self.insist = insist self.logger = logging.getLogger('graylog') def get_consumers(self, Consumer, channel): return [Consumer( queues=[self.queue], on_message=self.on_request, # callback prefetch_count=1, )] def __enter__(self): self.connection = Connection( hostname=self.host, userid=self.user, password=self.password, virtual_host=self.vhost, insist=self.insist ) try: self.connection.connect() except (OSError, Exception) as e: self.logger.log(**{ 'msg': str(e), 'level': logging.ERROR, }) raise RabbitMQError(e) self.exchange = Exchange( name=self.exchange_name, type='topic', durable=True ) self.queue = Queue( name=self.queue_name, exchange=self.exchange, routing_key=self.queue_name ) return self def on_request(self, message): print(str(message.body)) # как бы так не удалять message.ack() def __exit__(self, exc_type, exc_val, exc_tb): self.connection.release()
from math import pow, abs def f(x): x = (a + b) / 2 R = f(x) = pow(x, 2) + 2*x # ввод значений a = float(input('Введите начало отрезка: ')) b = float(input('Введите конец отрезка: ')) eps = float(input('Введите точность: ')) # Вычисляем значения функций f(x1), f(x2) x1 = a + 0.382 * (b - a) x2 = b - 0.382 * (b - a) f(x1) = pow(x1, 2) + 2*x1 f(x2) = pow(x2, 2) + 2*x2 while (True): if (f(x1) < f(x2)): b = x2 else: a = x1 if (math.abs(b - a) < eps): return x return R print (x, R) else: if b = x2: x2 = x1 f(x2) = f(x1) x1 = a + 0.382 * (b - a) f(x1) = pow(x1, 2) + 2*x1 if a = x1: x1 = x2 f(x1) = f(x2) x2 = b - 0.382 * (b - a) f(x2) = pow(x2, 2) + 2*x2
@bot.message_handler(commands=['game']) def game(message): db_worker = SQLighter(config.database_name) row = db_worker.select_single(random.randint(1, utils.get_rows_count())) markup = utils.generate_markup(row[2], row[3]) bot.send_voice(message.chat.id, row[1], reply_markup=markup) utils.set_user_game(message.chat.id, row[2]) db_worker.close() @bot.message_handler(func=lambda message: True, content_types=['text']) def check_answer(message): answer = utils.get_answer_for_user(message.chat.id) if not answer: bot.send_message(message.chat.id, 'Чтобы начать игру, выберите команду /game') else: keyboard_hider = types.ReplyKeyboardRemove() if message.text == answer: bot.send_message(message.chat.id, 'Верно!', reply_markup=keyboard_hider) else: bot.send_message(message.chat.id, 'Неправильно', reply_markup=keyboard_hider) utils.finish_user_game(message.chat.id) if __name__ == '__main__': utils.count_rows() random.seed() bot.polling(none_stop=True)
l1 = int(input()) r1 = int(input()) l2 = int(input()) r2 = int(input()) l3 = int(input()) r3 = int(input()) if r1 >= l2 and (r2 >= l3 or r1 >= l3): print(0) elif r2 + r1 - l1 >= l3: print(1) elif r1 + r3 - l3 >= l2: print(3) elif r2 + r1 - l1 >= l3 and r1 + r3 - l3 >= l2: print(1) else: print(-1)