Уведомления

Группа в Telegram: @pythonsu

Уведомления

  • Found 3494 posts.

Python для новичков » vk_api проблемы с чтением приходящих сооющений » Окт. 27, 2018 06:24:09

Скопировал программу из одного видео урока. Решил побаловаться с vk_api, отправка сообщений происходит без проблем, а вот получение с помощью “messages.getConversations” не как не получается подскажите.

Python для новичков » Как прикрепить описание к изображению вк? » Окт. 19, 2018 14:16:03

Кто знает как прикрепить описание к фото? знаю что это photos.saveWallPhoto метод, поле “caption”.
Просто не могу разобраться как это сделать в библиотеке vk_api парочкой строчек.
Неважно описание к одному изображению или к двум.
 import vk_api
from vk_api import VkUpload
 
# Авторизация по логину/паролю (если нужно по токену, заполнять параметр token)
login, password = 'login', 'pass'
app_id = '5182501'
vk_session = vk_api.VkApi(login, password, app_id)
vk_session.auth()
 
upload = VkUpload(vk_session)  # Для загрузки изображений
 
photos = ['1.jpg', '2.jpg']
# Или:
# photos = [open('1.jpg', 'rb'), open('2.jpg', 'rb')]
photo_list = upload.photo_wall(photos)
attachment = ','.join('photo{owner_id}_{id}'.format(**item) for item in photo_list)
 
vk_session.method("wall.post", {
    'owner_id': '-171537373',  # Посылаем себе на стену
    'message': 'Test!',
    'attachment': attachment,
})

Python для новичков » Запросы к вк апи » Окт. 15, 2018 11:36:19

Здравствуйте!
Вообщем, возникла необходимость получить общее количество записей по запросу к новостной ленте вк
Т.е, конкретно записи мне не нужны, нужно лишь получить число результатов на конкретный запрос.
И если есть возможность с определенного периода времени. Облазил документацию но не могу найти метод

GUI » Tkinter и окна на разных экранах » Окт. 13, 2018 03:14:46

Всем привет, задача: необходимо выводить дополнительное окно на второй экран. Для этого у tkinter.Toplevel есть специальная опция опция “screen”
  
import tkinter
root = tkinter.Tk()
top = tkinter.Toplevel(root, screen = "??????")
root.mainloop()

, где “??????” - имя экрана.
Вопрос: откуда взять это имя? Перепробовал всё что придумал: цифры, цифры строчные, названия из реестра, названия из диспетчера устройств, все ID из сведений об оборудовании, вообще всё что нашёл на монитор, ничего не подходит, пишет что не найден такой монитор, например:
_tkinter.TclError: couldn't connect to display "SAM02A4"

PS: описание, вдруг перевёл не так
screen - Specifies the screen on which to place the new window. 
Any valid screen name may be used, even one associated with a different display.
Defaults to the same screen as its parent. This option is special in that it may not be
specified via the option database, and it may not be modified with the configure method.

GUI » PyQt: Не работают ссылки в QWebView » Сен. 24, 2018 21:17:32

Пытаюсь интегрировать веб-сервис в приложение. Для этого в QWebView открываю HTML с JS кодом (в дальнейшем планируется вызов функций JS и отслеживание сигналов от JS), но почему-то не работают ссылки. При щелчке по ссылкам ничего не происходит. Также попытки отладки через QWebInspector приводят к зависанию приложения. В браузере HTML страница работает нормально.

Linux, Qt/PyQt 5.10.1, Python 3.6.5.

Может, подскажете что не так?

Тестовый код
 import os
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKitWidgets import QWebView, QWebInspector, QWebPage
filePath = os.path.join(os.path.dirname(__file__), 'index.html')
app = QApplication(sys.argv)
webView = QWebView()
QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True)
QWebSettings.globalSettings().setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
webView.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
inspector = QWebInspector()
inspector.setPage(webView.page())
content = ''
with open(filePath, 'rb') as f:
    content = f.read()
webView.setContent(content)
webView.show()
app.exec_()
Вот HTML файл, который открываю
 <html>
  <head>
    <script type="text/javascript" src="https://cdn.3dmapping.cloud/18.1.4/javascript/orbitgt_3dm_sdk.js"></script>
  </head>
  <body >
    <div id="app">
    <script type="text/javascript">
      var viewer;
      function handleReady() {
        viewer.setSize(600,400);
      }
      function handleDOMReady() {
        var applicationName = "QGIS Orbit plugin";
        var appElement = document.getElementById("m3dviewer");
        viewer = new orbitgt.mapping3d.sdk.viewer.SDKViewer(applicationName, appElement);
        viewer.isReady.then(handleReady);
      }
      document.addEventListener("DOMContentLoaded", handleDOMReady);
    </script>
    <div id="m3dviewer"/>
  </body>
</html>

Django » Доработка сайта на Python django 1.4.22 пакет xapian » Сен. 20, 2018 13:21:28

Требуются работы по доработке сайта. Подробнее напишу в личку, после подписания NDA.
Подрядчик должен быть с юр. лицом. Работы необходимо выполнять на постоянной основе.

Django » Как правильно расширить модель Use » Сен. 13, 2018 23:09:59



Здравствуйте! Не гневитесь если этот вопрос где то подымался, честное слово искал, смотрел не нашел. Прошу помощи у знатоков. Собственно к сути вопроса. С Django я не так давно, но стараюсь развиваться очень интересно. Пишу проект и стандартная модель User не устраивает вообше. Погуглил почитал остановился на методе с переопределением модели на свою.

Пример моей модели.

from django.contrib.auth.base_user import BaseUserManager from django.core.mail import send_mail from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.validators import UnicodeUsernameValidator from django.db import models from uuid import uuid4 from datetime import datetime from django.contrib.auth.hashers import make_password

class UserManager(BaseUserManager): use_in_migrations = True

def _create_user(self, email, full_name, password, **extra_fields):
“”“
Create and save a user with the given email,
full_name, and password.
”“”
if not email:
raise ValueError('email должен быть указан')
if not full_name:
raise ValueError('ФИО должно быть указанно')
email = self.normalize_email(email)
user = self.model(
email=email, full_name=full_name,
**extra_fields
)
user.set_password(make_password(password))
user.save(using=self._db)
return user

def create_user(self, email, full_name, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(
email, full_name, password, **extra_fields
)

def create_superuser(self, email, full_name, password, **extra_fields):
extra_fields.setdefault('dob', datetime.now())
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)

if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')

return self._create_user(
email, full_name, password, **extra_fields
)

class User(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator()

email = models.EmailField(
unique=True,
blank=False,
null=False,
verbose_name='E-Mail сотрудника'
)
full_name = models.CharField(
max_length=255,
null=False,
blank=False,
verbose_name='ФИО сотрудника'
)
dob = models.DateField(
null=False,
blank=False,
verbose_name='Датв рождения сотрудника'
)
emp_uid = models.UUIDField(
unique=True,
default=uuid4,
verbose_name='Уникальный индекс пользователя'
)
password = models.CharField(
max_length=150,
blank=False,
null=False,
verbose_name='Пароль'
)
is_active = models.BooleanField(
default=True,
verbose_name='Сотрудник активен'
)
is_staff = models.BooleanField(
default=False,
verbose_name='Наличие привилегий'
)

USERNAME_FIELD = ‘email’
REQUIRED_FIELDS =

objects = UserManager()

def __str__(self):
return self.email

def get_short_name(self):
return self.email

def get_full_name(self):
return self.full_name

def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, , **kwargs)

class Meta:
verbose_name = ‘Сотрудник’
verbose_name_plural = ‘Сотрудники’

Все бы ничего, но нарушилась работа админки. Мне показывается просто страниц с предложением заполнить поля. И все не так при вводе пользователя как на чистом проекте. Пароль остается текстом, назначение прав не работает. Что делать? Как поправить? Где почитать? Или все так и должно работать и после смены модели все тяготы ложатся на программиста? Спасибо за помощь, буду благодарен!
https://ibb.co/hvk3s9 - админка теперь

Python для новичков » Добавить данные в SQLite » Сен. 11, 2018 16:38:45

Добрый день.
Пытаюсь добавить данные в SQLite через функцию executemany:

 for i in phrases:
    lemma = str(phrases[id_phrase]).replace("('","").replace("',)", "").split()
    n_lemma = 0
    lemma_collection = ''
    l_count = 0
    for y in lemma:
        lemma_phrase = str(id_lemma) + "," + str(id_phrase) + ",'"+ lemma[l_count] +"'"
        lemma_collection += lemma_phrase
        if len(lemma) == l_count + 1:
            lemma_collection_list = lemma_collection.split("_")
            cursor.executemany("INSERT INTO lemmas VALUES (?, ?, ?)", lemma_collection_list)
            conn.commit()
        else:
            lemma_collection += '_'
        l_count += 1
        id_lemma += 1
    id_phrase += 1

В lemma_collection_list собирается список “0,0,'word1'”, “1,0,'word0'”, “2,0,'word3'”
Ранее у меня работал вот такой формат (0,'word1'),(1,'word2'),(2,'word3')
Подскажите, как в листе заменить кавычки на скобки, или наверняка есть более правильной способ формирования листа для загрузки.
Спасибо.

GUI » Kivy python не отрисовывает ни один виджет? » Сен. 10, 2018 14:56:14

Добрый день, пытаюсь запустить Kivy на linux Mint. Код самый простой:
 from kivy.app import App
from kivy.uix.button import Button
class MyFirstProgramApp(App):
    def duild(self):
        return Button(text = "Hello world!")
if __name__ == '__main__':
    MyFirstProgramApp().run()
Результат - просто черный экран. Хотел получить кнопку с надписью, менял на Label - то же самое, просто черный экран. В консоли вроде все нормально, никаких ошибок. Поставил уже кучу дополнительных библиотек, но ничего так и не отображается.

Python для экспертов » Keras - получение статистики за каждую эпоху. » Сен. 10, 2018 14:21:49

Хотел спросить - как максимально удобно получать статитстику, за каждую эпоху обучения в Keras?
МОжно ли как нибудь в нег например запихнуть каллбак который будет вызываться после окончания одной эпохи?

Python для новичков » Посчитать количество "person" на изображении. » Сен. 10, 2018 04:57:53

Добрый день. Делаю анализ изображений по скриншотам видио. Столкнулся с проблемой. Подскажите как сделать так что бы при анализе изображения считал количество объектов? Так же есть вопрос. как сделать так что бы модель определяла только класс “person”?

Ранее для подсчета с видео использовал код и он работал для счета.

 cnt = [category_index.get(value) for index,value in enumerate(classes[0]) if scores[0,index] > 0.5]
Сейчас подредактирвал под код:


 cnt = [category_index.get(value) for index,value in enumerate(output_dict['detection_classes'][0]) if output_dict['detection_scores'][0,index] > 0.5]
Но что то пошло не так с немного измененным кодом. и теперь данный метод не работает. и выдает ошибку

TypeError: ‘numpy.uint8’ object is not iterable

 import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
 
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append(r"Путь к файлам")
from object_detection.utils import ops as utils_ops
 
if tf.__version__ < '1.4.0':
  raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')
# This is needed to display the images.# This  
%matplotlib inline
 
from utils import label_map_util
 
from utils import visualization_utils as vis_util
 
# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
 
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
 
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
 
NUM_CLASSES = 90
 
if not os.path.exists(MODEL_NAME + '/frozen_inference_graph.pb'): #Проверяет наличие файла, Если нет файла то начинается загрузка модели
    print ('Downloading the model') # прокси блокирует доступ к сайту загрузки. Нужно качать напрямую, через ссылку и название нужного пакета
    opener = urllib.request.URLopener() # Модуль определяет функции и классы , которые помогают в открытии URL ( в основном HTTP)
    opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
    tar_file = tarfile.open(MODEL_FILE) # Открывает архив
    for file in tar_file.getmembers():  #Верните элементы архива в список TarInfo объектов. Список имеет тот же порядок, что и члены в архиве.
      file_name = os.path.basename(file.name) #os.path.basename(path) - базовое имя пути (эквивалентно os.path.split(path)[1]).file.name - возможно имя коренвого катлога в архиве
      if 'frozen_inference_graph.pb' in file_name: #Если есть файл frozen_inference_graph.pb в корневом катологе, то извлекает только его. 
       tar_file.extract(file, os.getcwd()) # Извлекает файл  в os.getcwd() - текущая рабочая директория.
    print ('Download complete')
else:
    print ('Model already exists')
 
detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')
 
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
 
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)
 
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = r'Путь к файлам'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'Image{}.jpg'.format(i)) for i in range(0, 11) ]
 
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)
 
def run_inference_for_single_image(image, graph):
  with graph.as_default():
    with tf.Session() as sess:
      # Get handles to input and output tensors
      ops = tf.get_default_graph().get_operations()
      all_tensor_names = {output.name for op in ops for output in op.outputs}
      tensor_dict = {}
      for key in [
          'num_detections', 'detection_boxes', 'detection_scores',
          'detection_classes', 'detection_masks'
      ]:
        tensor_name = key + ':0'
        if tensor_name in all_tensor_names:
          tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
              tensor_name)
      if 'detection_masks' in tensor_dict:
        # The following processing is only for single image
        detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
        detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
        # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
        real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
        detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
        detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
        detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
            detection_masks, detection_boxes, image.shape[0], image.shape[1])
        detection_masks_reframed = tf.cast(
            tf.greater(detection_masks_reframed, 0.5), tf.uint8)
        # Follow the convention by adding back the batch dimension
        tensor_dict['detection_masks'] = tf.expand_dims(
            detection_masks_reframed, 0)
      image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
 
      # Run inference
      output_dict = sess.run(tensor_dict,
                             feed_dict={image_tensor: np.expand_dims(image, 0)})
 
      # all outputs are float32 numpy arrays, so convert types as appropriate
      output_dict['num_detections'] = int(output_dict['num_detections'][0])
      output_dict['detection_classes'] = output_dict[
          'detection_classes'][0].astype(np.uint8)
      output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
      output_dict['detection_scores'] = output_dict['detection_scores'][0]
      if 'detection_masks' in output_dict:
        output_dict['detection_masks'] = output_dict['detection_masks'][0]
  return output_dict
 
 
for image_path in TEST_IMAGE_PATHS:
  image = Image.open(image_path)
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = load_image_into_numpy_array(image)
  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  image_np_expanded = np.expand_dims(image_np, axis=0)
  # Actual detection.
  output_dict = run_inference_for_single_image(image_np, detection_graph)
  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks'),
      use_normalized_coordinates=True,
      line_thickness=8)
  plt.figure(figsize=IMAGE_SIZE)
  plt.imshow(image_np)

События » CryptoBazar Serial Hacking » Сен. 7, 2018 20:40:49

Приглашаем вас на масштабный полугодовой блокчейн-хакатон от CryptoBazar Fund в онлайн формате.
🔸 Лучшие python программисты со всего мира
🔸 Общий призовой фонд - более 10 000 000 рублей;
🔸 2000+ разработчиков из России, Украины, Белоруссии, Казахстана и стран Балтики;
🔸 4 полуфинальных раунда, каждый из которых включает этап ✅online подготовки и последующий очный хакатон в Москве;
🔸 Финал в Гонконге: двухдневный круиз на суперлайнере, где лучшие из лучших будут соревноваться за главный приз и оцениваться ведущими мировыми разработчиками;

✅ Сайт с подробной информацией:
http://HackathonSerial.CryptoBazar.io/?utm_source=prm..
✅ Telegram:
@CryptoBazarHackathon

Python для новичков » где мой потомок потерял метод родителя? » Сен. 7, 2018 18:38:09

родитель:
 class KspVar(KspObject):
    '''Abstract base class for every object can behave like variable:
    int, string or real(float) variables and arrays of KSP
    abstract methods required:
    @abstractmethod
    def _get_compiled(self)
    @abstractmethod
    def _set_runtime(self, val)
    @abstractmethod
    def _get_runtime(self)
    # can be used via super().val()
    @property
    @abstractmethod
    def val(self):
        if self.is_compiled():
            return self._get_compiled()
        return self._get_runtime()
    also has property for getting and setting value as defaul value
    handler of instantiation via kwarg "value":
    _value
    Strongly reommended to assign kwarg "ref_type". In other case
    KspVar will be used as ref_type.
    '''
    def __init__(self, name, value=None,
                 ref_type=None,
                 name_prefix='',
                 name_postfix='',
                 preserve_name=False,
                 has_init=True, is_local=False,
                 persist=False):
        super().__init__(name, name_prefix=name_prefix,
                         name_postfix=name_postfix,
                         preserve_name=preserve_name,
                         has_init=has_init, is_local=is_local,
                         has_executable=False)
        if ref_type:
            if not isinstance(ref_type, tuple):
                raise TypeError('ref_type has to be tuple of classes')
            for item in ref_type:
                if not isinstance(item, type):
                    raise TypeError('ref_type has to be tuple' +
                                    ' of classes')
            self._ref_type = ref_type
        else:
            self._ref_type = self.__class__
        if value is not None:
            self.__value = self._get_rutime_other(value)
        else:
            self.__value = []
        self._persistent = persist
        self._read = False
    def _check_val_type(self, val):
        '''check if val is instance of ref_type.
        expands val if it is instance of KspVar
        returns val
        '''
        if not isinstance(val, self.ref_type):
            raise TypeError(f'has to be one of: {self.ref_type}.' +
                            f'val ({val}) is of type({type(val)})')
        if isinstance(val, KspVar):
            val = val.val
        return val
    def read(self):
        '''calls KSP function read_persistent_var() and adds
        make_persistent() function call at declaration if not any
        '''
        if not self.in_init():
            raise RuntimeError('can not be outside init')
        if self.is_local:
            raise RuntimeError('is local var')
        if self._read:
            warn('read has been called yet', category=Warning,
                 stacklevel=2)
        Output().put(f'read_persistent_var({self.name()})')
        self._read = True
    @property
    def ref_type(self):
        '''getter. returns tuple of types'''
        return self._ref_type
    def _set_compiled(self, val):
        '''Puts AstAssign to Output()
        calls self._set_runtime with "val" rutime val
        '''
        self._set_runtime(self._get_rutime_other(val))
        Output().put(AstAssign(self, val).expand())
    def _get_rutime_other(self, other):
        '''returns runtime representation of KspVar and AstBase
        or just passed value'''
        if not isinstance(other, self.ref_type):
            raise TypeError(f'has to be one of: {self.ref_type}.' +
                            f'other is of type({type(other)})')
        if hasattr(other, 'get_value'):
            return other.get_value()
        if hasattr(other, '_get_runtime'):
            return other._get_runtime()
        return other
    @abstractmethod
    def _get_compiled(self):
        pass
    @abstractmethod
    def _set_runtime(self, val):
        pass
    @abstractmethod
    def _get_runtime(self):
        pass
    def __ilshift__(self, other):
        '''under compilation calls self._set_compiled
        otherwise calls self._set_runtime
        returns self'''
        self._check_val_type(other)
        if self.is_compiled():
            self._set_compiled(other)
            return self
        self._set_runtime(other)
        return self
    def __rlshift__(self, other):
        '''under compilation calls self._get_compiled
        otherwise calls self._get_runtime
        '''
        if self.is_compiled():
            return self._get_compiled()
        return self._get_runtime()
    @property
    def val(self):
        '''under compilation calls self._get_compiled
        otherwise calls self._get_runtime
        '''
        if self.is_compiled():
            return self._get_compiled()
        return self._get_runtime()
    @property
    def _value(self):
        '''returns value passed in __init__ as "value" parameter'''
        return self.__value
    @_value.setter
    def _value(self, val):
        '''sets the value could be taken from _value property'''
        self._check_val_type(val)
        val = self._get_rutime_other(val)
        self.__value = val

потомок:
 class KspNumeric(KspVar):
    '''abstract base class for int and real KSP variables
    has to keep class variable "warning_types", consists tuple
    of classes for blocking magic methods.
    For example:
    warning_types = (KspIntVar, str, KspStrVar)
    '''
    warning_types = None
    _warning_types_exc_str =\
        "class var warning_types has to consist tuple of " +\
        'classes to warn within operations'
    # @classmethod
    # def warning_types(cls):
    #     return cls.warning_types
    class TypeWarn(Warning):
        '''raised when type convertion is needed'''
        def __init__(self, val):
            super().__init__(
                f'Value {val} (type{type(val)}) ' +
                'has to be converted within built-in func')
    def __new__(cls, *args, **kwargs):
        '''checks correct assignement of cls.warning_types'''
        if cls.warning_types is None:
            raise TypeError(cls._warning_types_exc_str)
        if not isinstance(cls.warning_types, tuple):
            raise TypeError(cls._warning_types_exc_str)
        for item in cls.warning_types:
            if not isinstance(item, type):
                raise TypeError(cls._warning_types_exc_str)
        obj = super().__new__(cls)
        # obj.__init__(*args, **kwargs)
        return obj
    def _generate_executable(self):
        raise NotImplementedError('has not to be called')
    def _warn_other(self, value):
        if isinstance(value, self.warning_types):
            raise self.TypeWarn(value)
    @abstractmethod
    def __truediv__(self, other):
        pass
    @abstractmethod
    def __rtruediv__(self, other):
        pass
    @abstractmethod
    def __itruediv__(self, other):
        pass
    @abstractmethod
    def __floordiv__(self, other):
        raise ArithmeticError('use regular / instead')
    @abstractmethod
    def __rfloordiv__(self, other):
        raise ArithmeticError('use regular / instead')
    @abstractmethod
    def __ifloordiv__(self, other):
        raise ArithmeticError('use regular / instead')
    def _expand_other(self, other):
        '''returns other, expanded via val property if is
        instance of KspVar'''
        if isinstance(other, self.warning_types):
            raise self.TypeWarn(other)
        if not isinstance(other, self.ref_type):
            raise TypeError(f'has to be one of {self.ref_type}')
        if isinstance(other, (int, str, float)):
            return other
        return other.val
    def __neg__(self):
        if self.is_compiled():
            return AstNeg(self)
        return -self._get_runtime()
    def __invert__(self):
        if self.is_compiled():
            return AstNot(self)
        return ~self._get_runtime()
    def __add__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            return AstAdd(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() + other
    def __radd__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            return AstAdd(other, self)
        other = self._get_runtime_other(other)
        return self._get_runtime() + other
    def __iadd__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            self._set_compiled(AstAdd(self, other))
            return self
        other = self._get_runtime_other(other)
        self._set_runtime(self._get_runtime() + other)
        return self
    def __sub__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            return AstSub(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() - other
    def __rsub__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            return AstSub(other, self)
        other = self._get_runtime_other(other)
        return self._get_runtime() - other
    def __isub__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            self._set_compiled(AstSub(self, other))
            return self
        other = self._get_runtime_other(other)
        self._set_runtime(self._get_runtime() - other)
        return self
    def __mul__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            return AstMul(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() * other
    def __rmul__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            return AstMul(other, self)
        other = self._get_runtime_other(other)
        return self._get_runtime() * other
    def __imul__(self, other):
        self._warn_other(other)
        if self.is_compiled():
            self._set_compiled(AstMul(self, other))
            return self
        other = self._get_runtime_other(other)
        self._set_runtime(self._get_runtime() * other)
        return self
    def __and__(self, other):
        if self.is_compiled():
            if self.is_bool():
                return AstLogAnd(self, other)
            return AstBinAnd(self, other)
        other = self._get_runtime_other(other)
        if self.is_bool():
            return self._get_runtime() and other
        return self._get_runtime() & other
    def __rand__(self, other):
        if self.is_compiled():
            if self.is_bool():
                return AstLogAnd(other, self)
            return AstBinAnd(other, self)
        other = self._get_runtime_other(other)
        if self.is_bool():
            return self._get_runtime() and other
        return self._get_runtime() & other
    def __iand__(self, other):
        raise NotImplementedError
    def __or__(self, other):
        if self.is_compiled():
            if self.is_bool():
                return AstLogOr(self, other)
            return AstBinOr(self, other)
        other = self._get_runtime_other(other)
        if self.is_bool():
            return self._get_runtime() or other
        return self._get_runtime() | other
    def __ror__(self, other):
        if self.is_compiled():
            if self.is_bool():
                return AstLogOr(other, self)
            return AstBinOr(other, self)
        other = self._get_runtime_other(other)
        if self.is_bool():
            return self._get_runtime() or other
        return self._get_runtime() | other
    def __ior__(self, other):
        raise NotImplementedError
    def __eq__(self, other):
        if self.is_compiled():
            return AstEq(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() == other
    def __ne__(self, other):
        if self.is_compiled():
            return AstNe(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() != other
    def __lt__(self, other):
        if self.is_compiled():
            return AstLt(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() < other
    def __gt__(self, other):
        if self.is_compiled():
            return AstGt(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() > other
    def __le__(self, other):
        if self.is_compiled():
            return AstLe(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() <= other
    def __ge__(self, other):
        if self.is_compiled():
            return AstGe(self, other)
        other = self._get_runtime_other(other)
        return self._get_runtime() >= other
ошибка:
 Traceback (most recent call last):
  File "E:\packages\pyksp\pyksp\compiler\tests\test_base_types.py", line 678, in test_real
    self.assertEqual(x + 1.0, 2)
  File "E:\packages\pyksp\pyksp\compiler\tests/..\base_types.py", line 838, in __add__
    other = self._get_runtime_other(other)
AttributeError: 'TestRealVar' object has no attribute '_get_runtime_other'

Центр помощи » Решение СЛАУ с подстановкой полученных значений в следующий цикл. » Авг. 31, 2018 14:42:55

Добрый день! Подскажите, пожалуйста, как реализовать решение следующей задачи: есть коэффициенты перед неизвестными в СЛАУ. Нужно, чтобы полученные значения “работали” дальше в цикле (наподобие как я написала в комментариях).

GUI » PyQT5 QCalendatWidget » Авг. 30, 2018 12:00:38

У меня вопрос - как прописать (сначала вытащить цифру) в переменную - число дня недели исходя из выбранного дня в виджете PyQt5 (QCalendatWidget) - например выбрано 30 августа 2018 = это четверг и соответственно число недели будет 4 (условно, т.к не знаю как там идет нумерация)
Желательно, чтобы можно было потом совершать математические операции с этим числом (т.е оно изначально не было типа string, а было integer)
Поможете ?

Django » Как отследить изменения many_to_many полей у модели в админке » Авг. 28, 2018 05:43:52

Есть модели Player и Match, связанные many_to_many
 class Player(models.Model):
    number = models.IntegerField(u'Номер', blank=True, null=True)
    last_name = models.CharField(u'Фамилия', max_length=100)
    name = models.CharField(u'Имя', max_length=100)
class Match(models.Model):
    tournament = models.ForeignKey(Tournament, verbose_name=u'Турнир', on_delete=models.CASCADE)
    tour = models.ForeignKey(Tour, verbose_name=u'Тур', on_delete=models.CASCADE)
    structure_home = models.ManyToManyField(
        Player, verbose_name=u'Состав команды хозяев', related_name='home_players', blank=True)
    
class Statistics(models.Model):
    player = models.ForeignKey(Player, verbose_name=u'Игрок', on_delete=models.CASCADE)
    tournament = models.ForeignKey('tournaments.Tournament', verbose_name=u'Турнир', on_delete=models.CASCADE)
    ...
    games = models.IntegerField(u'Игры', default=0)
   ...

Для игрока мне необходимо считать количество матчей (games), в которых он принял участие. Я бы хотел при сохранении матча делать так:
если игрока добавили в structure_home, то games прибавить 1, если игрока удалили из structure_home, то соответственно games отнять 1.
Соответственно мне для этого надо знать каким был structure_home до сохранения и каким стал после.
Как это возможно сделать?

Python для экспертов » django-channels + nginx. Error during WebSocket handshake: Unexpected response code: 404 » Авг. 26, 2018 17:08:35

Добрый день! Вопрос про настройку вебсокетов с django-channels==2.1 + nginx
При создании инстанса WebSocket
var ws = new WebSocket('ws/' + window.location.host + ‘/ws/chat/’ + roomName + ‘/’);
Получаю ошибку:
WebSocket connection to ‘ws/домен пурум пум/ws/chat/84062a02-f8a0-4737-ad44-5fa2ae8336d6/’ failed: Error during WebSocket handshake: Unexpected response code: 404

Настройки nginx:
server {
listen 8001;

server_name example:8001;

client_max_body_size 100M;

location /static/ {
alias ../static/;
expires 365d;
access_log off;
}

location /ws/ {
proxy_pass http://127.0.0.1:8098;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”;
}

location / {
proxy_pass http://127.0.0.1:8099;
}
}

daphne запускается через supervisor
command=/home/deploy/projects/venv/bin/daphne -p 8098 project.asgi:application


На локальной машине при старте через runserver все работает нормально
Как исправить эту ошибку? Или может кто знает ошибка в настройках nginx или в настройках django-channels?

Python для новичков » Обойти 2038:01:19 03:14:07 » Авг. 24, 2018 22:37:47

Именно эта дата представляет собой максимальное 32-битное число, и это пдц. (Что дальше, придется всем 64 битные компы собирать?)
И мне интересно, можно ли на 32битном компе(моем) с
 >>> strftime("%Y:%m:%d %H:%M:%S", gmtime(0x7FFFFFFF))
'2038:01:19 03:14:07'
Обойти это число и использовать 0x80000000? Я пытался, он ругается на то, что я сишный time_t сломал.

UPD: Хочу вечный будильник замутить

Python для новичков » Как задать точку вокруг которой вращать спрайт в PyGame? » Авг. 23, 2018 17:35:01

Добрый день, пытаюсь вращать спрайт с помощью pygame.transform.rotate(), но логика вращения меня не устраивает, не могу нигде найти как задать центр вращения для сего действа.