Форум сайта python.su
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, })
import tkinter root = tkinter.Tk() top = tkinter.Toplevel(root, screen = "??????") root.mainloop()
_tkinter.TclError: couldn't connect to display "SAM02A4"
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.
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> <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>
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
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()
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]
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)
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'
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) ...
>>> strftime("%Y:%m:%d %H:%M:%S", gmtime(0x7FFFFFFF)) '2038:01:19 03:14:07'