# -*- coding: utf-8 -*-
"""
# @file name  : target.py
# @author     : chenzhanpeng https://github.com/chenzpstar
# @date       : 2022-01-09
# @brief      : FCOS训练目标类
"""

import torch
import torch.nn as nn

from models.config import FCOSConfig
from models.utils import coords2centers, coords2offsets, decode_coords, reshape_feat

class FCOSTarget(nn.Module):
    def __init__(self, cfg=None):
        super(FCOSTarget, self).__init__()
        if cfg is None:
            self.cfg = FCOSConfig
        else:
            self.cfg = cfg

        self.strides = self.cfg.strides
        self.ranges = self.cfg.ranges
        assert len(self.strides) == len(self.ranges)

    def forward(self, feats, labels, boxes):
        stages_num = len(self.strides)
        assert len(feats) == stages_num

        cls_targets = []
        reg_targets = []
        ctr_targets = []

        for i in range(stages_num):
            stage_targets = self._gen_stage_targets(
                feats[i],
                labels,
                boxes,
                self.strides[i],
                self.ranges[i],
            )
            cls_targets.append(stage_targets[0])
            reg_targets.append(stage_targets[1])
            ctr_targets.append(stage_targets[2])

        return cls_targets, reg_targets, ctr_targets

    def _gen_stage_targets(self,
                           feat,
                           labels,
                           boxes,
                           stride,
                           range,
                           sample_radio=1.5):
        coords = decode_coords(feat, stride).to(device=boxes.device)
        feat = reshape_feat(feat)  # bchw -> b(hw)c

        batch_size, hw = feat.shape[:2]  # b(hw)c
        boxes_num = boxes.shape[1]  # bnc

        # 1.计算每个坐标到所有标注框四边的偏移量
        offsets = coords2offsets(coords, boxes)
        assert offsets.shape == (batch_size, hw, boxes_num, 4)

        offsets_min = offsets.min(dim=-1)[0]
        offsets_max = offsets.max(dim=-1)[0]
        boxes_mask = offsets_min > 0
        stage_mask = (offsets_max > range[0]) & (offsets_max <= range[1])

        # 2.计算每个坐标到所有标注框中心的偏移量
        ctr_offsets = coords2centers(coords, boxes)
        assert ctr_offsets.shape == (batch_size, hw, boxes_num, 4)

        radius = sample_radio * stride
        ctr_offsets_max = ctr_offsets.max(dim=-1)[0]
        ctr_mask = ctr_offsets_max <= radius

        pos_mask = boxes_mask & stage_mask & ctr_mask
        assert pos_mask.shape == (batch_size, hw, boxes_num)

        # 3.计算所有标注框面积
        areas = (offsets[..., 0] + offsets[..., 2]) * (offsets[..., 1] +
                                                       offsets[..., 3])
        areas[~pos_mask] = 999999  # neg_areas
        areas_min_idx = areas.min(dim=-1)[1].unsqueeze(dim=-1)
        areas_min_mask = torch.zeros_like(areas, dtype=torch.bool).scatter(
            -1, areas_min_idx, 1)
        assert areas_min_mask.shape == (batch_size, hw, boxes_num)

        # 4.计算分类目标
        labels = torch.broadcast_tensors(
            labels[:, None, :], areas.long())[0]  # [b,1,n] -> [b,h*w,n]
        cls_targets = labels[areas_min_mask].reshape((batch_size, -1, 1))
        assert cls_targets.shape == (batch_size, hw, 1)

        # 5.计算回归目标
        offsets = offsets / stride
        reg_targets = offsets[areas_min_mask].reshape((batch_size, -1, 4))
        assert reg_targets.shape == (batch_size, hw, 4)

        # 6.计算中心度目标
        lr_min = torch.min(reg_targets[..., 0], reg_targets[..., 2])
        lr_max = torch.max(reg_targets[..., 0], reg_targets[..., 2])
        tb_min = torch.min(reg_targets[..., 1], reg_targets[..., 3])
        tb_max = torch.max(reg_targets[..., 1], reg_targets[..., 3])
        ctr_targets = ((lr_min * tb_min) /
                       (lr_max * tb_max).clamp(min=1e-10)).sqrt().unsqueeze(
                           dim=-1)
        assert ctr_targets.shape == (batch_size, hw, 1)

        # 7.处理负样本
        pos_mask = pos_mask.long().sum(dim=-1)
        pos_mask = pos_mask >= 1
        assert pos_mask.shape == (batch_size, hw)

        cls_targets[~pos_mask] = 0
        reg_targets[~pos_mask] = -1
        ctr_targets[~pos_mask] = -1

        return cls_targets, reg_targets, ctr_targets

if __name__ == "__main__":

    import torch
    torch.manual_seed(0)

    model = FCOSTarget()

    preds = (
        [torch.rand(2, 3, 2, 2)] * 5,
        [torch.rand(2, 4, 2, 2)] * 5,
        [torch.rand(2, 1, 2, 2)] * 5,
    )
    labels = torch.rand(2, 3)
    boxes = torch.rand(2, 3, 4)

    out = model(preds[0], labels, boxes)
    [print(stage_out.shape) for branch_out in out for stage_out in branch_out]


import fcntl
import logging
import socket
import struct
import urllib.request
from urllib.parse import urlparse
from xml.dom import minidom
from functools import wraps
import urllib.error
import xml

SIOCGIFINDEX = 0x8933  # Get interface index
logger = logging.getLogger(__name__)

class NotRetrievedError(Exception):
    """Custom exception for objects that have not been retrieved

    Custom object not retrieved exception class. Raised whenever a certain
    property for a device or service was not retrieved.

    """
    pass

class NotAvailableError(Exception):
    """Custom exception for when a certain URL could not be retrieved

    Custom element not retrieved exception class. Raised whenever a value
    needed to be accessed could not be retrieved from the URL.

    """
    pass

def parse_http_header(header, header_key):
    """Parse HTTP header value

    Parse the value of a specific header from a RAW HTTP response.

    :param header: String containing the RAW HTTP response and headers
    :type header: str
    :param header_key: The header name of which to extract a value from
    :type header_key: str
    :return: The value of the header
    :rtype: str

    """
    split_headers = header.split('\r\n')

    for entry in split_headers:
        header = entry.strip().split(':', 1)

        if header[0].strip().lower() == header_key.strip().lower():
            return ''.join(header[1::]).split()[0]

def make_http_request(url, data=None, headers=None):
    """Helper function for making HTTP requests

    Helper function for making HTTP requests using urllib.

    :param url: The URL to which a request should be made
    :type url: str
    :param data: Provide data for the request. Request method will be set to
                 POST if data is provided
    :type data: str
    :param headers: Provide headers to send with the request
    :type headers: dict
    :return: A urllib.Request.urlopen object
    :rtype: urllib.Request.urlopen

    """
    if not headers:
        headers = {}

    # If data is provided the request method will automatically be set to POST
    # by urllib
    request = urllib.request.Request(url, data=data, headers=headers)
    return urllib.request.urlopen(request)

def _device_description_required(func):
    """Decorator for checking whether the device description is available on a
    device.

    """

    @wraps(func)
    def wrapper(device, *args, **kwargs):
        if device.description is None:
            raise NotRetrievedError(
                'No device description retrieved for this device.')
        elif device.description == NotAvailableError:
            return
        return func(device, *args, **kwargs)

    return wrapper

def _get_if_index(ifname, fd):
    """Get the index corresponding to interface ifname used by socket fd"""
    ifreq = struct.pack('16si', ifname.encode(), 0)
    res = fcntl.ioctl(fd, SIOCGIFINDEX, ifreq)
    return int(struct.unpack('16si', res)[1])

class SSDPDevice:
    """Represents an SSDP device

    Object for representing an SSDP device.

    :param address: SSDP device address
    :type address: tuple
    :param response: Device discovery response data
    :type response: str

    """

    def __init__(self, address, response):
        self.address = address
        self.host = address[0]
        self.port = address[1]
        self.response = response
        self.description = None
        self.friendly_name = None
        self.type_ = None
        self.base_url = None

        self._get_description_request(parse_http_header(response, 'Location'))
        self._get_friendly_name_request()
        self._get_type_request()
        self._get_base_url_request()

    def get_friendly_name(self):
        """Get the friendly name for the device

        Gets the device's friendly name

        :return: Friendly name of the device
        :rtype: str

        """
        return self.friendly_name

    def _get_description_request(self, url):
        try:
            device_description = make_http_request(url).read()
            self.description = device_description
            return device_description.decode()

        except (urllib.error.HTTPError, urllib.error.URLError):
            self.description = NotAvailableError
            return None

    @_device_description_required
    def _get_friendly_name_request(self):
        root = minidom.parseString(self.description)
        device_friendly_name = root.getElementsByTagName(
            'friendlyName')[0].firstChild.nodeValue
        self.friendly_name = device_friendly_name
        return self.friendly_name

    @_device_description_required
    def _get_type_request(self):
        root = minidom.parseString(self.description)
        device_type = root.getElementsByTagName(
            'deviceType')[0].firstChild.nodeValue
        self.type_ = device_type
        return self.type_

    @_device_description_required
    def _get_base_url_request(self):
        location_header_value = parse_http_header(self.response, 'Location')
        header_url = urlparse(location_header_value)
        root = minidom.parseString(self.description)
        try:
            parsed_url = urlparse(
                root.getElementsByTagName('URLBase')[0].firstChild.nodeValue)

            if parsed_url.port is not None:
                base_url = '{}://{}'.format(parsed_url.scheme,
                                            parsed_url.netloc)
            else:
                base_url = '{}://{}:{}'.format(parsed_url.scheme,
                                               parsed_url.netloc,
                                               header_url.port)
        except (IndexError, AttributeError):
            base_url = '{}://{}'.format(header_url.scheme, header_url.netloc)

        self.base_url = base_url
        return base_url

class SSDPHeader:

    def __init__(self, **headers):
        """
        Example M-SEARCH header:
        ------------------------------------------------------------------------
        M-SEARCH * HTTP/1.1          SSDP method for search requests
        HOST: 239.255.255.250:1900   SSDP multicast address and port (REQUIRED)
        MAN: "ssdp:discover"         HTTP Extension Framework scope (REQUIRED)
        MX: 2                        Maximum wait time in seconds (REQUIRED)
        ST: upnp:rootdevice          Search target (REQUIRED)
        ------------------------------------------------------------------------
        """
        self.headers = {}
        self.set_headers(**headers)

        self._available_methods = ['M-SEARCH']

        self.method = None
        self.host = self.headers.get('HOST')
        self.man = self.headers.get('MAN')
        self.mx = self.headers.get('MX')
        self.st = self.headers.get('ST')

    def _check_method_required_params(self):
        if self.method == 'M-SEARCH':
            # M-SEARCH required parameters: HOST, MAN, MX, ST
            if None in [self.host, self.man, self.mx, self.st]:
                raise ValueError(
                    'M-SEARCH method requires HOST, MAN, MX and ST headers '
                    'to be set.')

    def set_method(self, method):
        method = method.upper()
        if method in self._available_methods:
            self.method = method.upper()
        else:
            raise ValueError('Method must be either' +
                             ' or '.join(self._available_methods))

    def set_header(self, name, value):
        self.headers[name.upper()] = value

    def set_headers(self, **headers):
        for key, value in headers.items():
            self.set_header(key.upper(), value)

class SSDPRequest(SSDPHeader):
    """Create and perform an SSDP request

    :param method: SSDP request method [M-SEARCH]

    """

    def __init__(self,
                 ssdp_mcast_addr='239.255.255.250',
                 ssdp_port=1900,
                 src_port=None,
                 interface=None,
                 **headers):
        super().__init__(**headers)

        self.SSDP_MCAST_ADDR = ssdp_mcast_addr
        self.SSDP_PORT = ssdp_port

        self.set_header('HOST', "{}:{}".format(self.SSDP_MCAST_ADDR,
                                               self.SSDP_PORT))

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        if (src_port is not None):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.bind(('', src_port))

        if (interface is not None):
            try:
                ifindex = _get_if_index(interface, self.socket.fileno())
            except OSError:
                logger.error(
                    "Could not find interface \"{}\"".format(interface))
                return
            except ValueError:
                logger.error(
                    "Failed to parse the index of interface \"{}\"".format(
                        interface))
                return
            ip_mreqn = struct.pack(
                '4s4si',
                socket.inet_aton(ssdp_mcast_addr),
                socket.inet_aton('0.0.0.0'),  # INADDR_ANY
                ifindex)
            self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
                                   ip_mreqn)

    def __del__(self):
        self.socket.close()

    def m_search(self, discover_delay=2, st='ssdp:all', **headers):
        """Perform an M-SEARCH SSDP request

        Send an SSDP M-SEARCH request for finding UPnP devices on the network.

        :param discover_delay: Device discovery delay in seconds
        :type discover_delay: int
        :param st: Specify device Search Target
        :type st: str
        :param headers: Specify M-SEARCH specific headers
        :type headers: str
        :return: List of device that replied
        :rtype: list

        """
        self.set_method('M-SEARCH')

        self.set_header('MAN', '"ssdp:discover"')
        self.set_header('MX', discover_delay)
        self.set_header('ST', st)
        self.set_headers(**headers)

        self.socket.settimeout(discover_delay)

        devices = self._send_request(self._get_raw_request())

        for device in devices:
            yield device

    def _get_raw_request(self):
        """Get raw request data to send to server"""

        final_request_data = ''

        if self.method is not None:
            ssdp_start_line = '{} * HTTP/1.1'.format(self.method)
        else:
            ssdp_start_line = 'HTTP/1.1 200 OK'

        final_request_data += '{}\r\n'.format(ssdp_start_line)

        for header, value in self.headers.items():
            final_request_data += '{}: {}\r\n'.format(header, value)

        final_request_data += '\r\n'

        return final_request_data

    def _send_request(self, message):
        self.socket.sendto(message.encode(),
                           (self.SSDP_MCAST_ADDR, self.SSDP_PORT))

        devices = []

        try:
            while True:

                # UDP packet data limit is 65507 imposed by IPv4
                # https://en.wikipedia.org/wiki/User_Datagram_Protocol#Packet_structure

                response, addr = self.socket.recvfrom(65507)
                try:
                    device = SSDPDevice(addr, response.decode())
                except xml.parsers.expat.ExpatError:
                    continue
                devices.append(device)
        except socket.timeout:
            pass

        return devices

class UPnP:
    """UPnP object

    A UPnP object used for device discovery

    """

    def __init__(self, src_port=None, interface=None):
        self.ssdp = SSDPRequest(src_port=src_port, interface=interface)
        self.discovered_devices = []

    def discover(self, delay=2, **headers):
        """Find UPnP devices on the network

        Find available UPnP devices on the network by sending an M-SEARCH
        request.

        :param delay: Discovery delay, amount of time in seconds to wait for a
                      reply from devices
        :type delay: int
        :param headers: Optional headers for the request
        :return: List of discovered devices
        :rtype: list

        """

        discovered_devices = []
        for device in self.ssdp.m_search(discover_delay=delay,
                                         st='upnp:rootdevice',
                                         **headers):
            discovered_devices.append(device)

        self.discovered_devices = discovered_devices
        return self.discovered_devices


import h5py
import os
from torch.utils.data import Dataset
from DVS_dataload.my_transforms import *
from PIL import Image
import torch
import numpy as np

class DVSGestureDataset(Dataset):
    def __init__(self, root, train=True, transform=None):
        super(DVSGestureDataset, self).__init__()
        self.n = 0
        self.root = root
        self.train = train
        self.transform = transform

        if train:
            root_train = os.path.join(self.root, 'DvsGesture_train_40step_downsample')
            for _, _, self.files_train in os.walk(root_train):
                pass
            self.n = len(self.files_train)
        else:
            root_test = os.path.join(self.root, 'DvsGesture_test_40step_downsample')
            for _, _, self.files_test in os.walk(root_test):
                pass
            self.n = len(self.files_test)

    def __len__(self):
        return self.n

    def __getitem__(self, idx):
        if self.train:
            root_test = os.path.join(self.root, 'DvsGesture_train_40step_downsample')

            with h5py.File(root_test + os.sep + self.files_train[idx], 'r', swmr=True, libver="latest") as f:
                target = f['label'][()]
                data = f['data'][()]
            if self.transform is not None:
                data = self.transform(data)

            return data, target
        else:
            root_test = os.path.join(self.root, 'DvsGesture_test_40step_downsample')

            with h5py.File(root_test + os.sep + self.files_test[idx], 'r', swmr=True, libver="latest") as f:
                target = f['label'][()]
                data = f['data'][()]
            if self.transform is not None:
                data = self.transform(data)

            return data, target


# creates the finale report

import sys
import os
import glob

CL_HOME = os.environ['CL_HOME']
obj_folder = CL_HOME + "/testFinale"

las_f = obj_folder + "/finale_las.tsv"
mlas_f = obj_folder + "/finale_mlas.tsv"
blex_f = obj_folder + "/finale_blex.tsv"

ltcode2results = {}
for out_file in glob.glob(obj_folder+"/out_*"):
  fname = out_file.split("/")[-1]
  ltcode = fname[fname.find('_')+1:fname.rfind('_')]
  las_score, mlas_score, blex_score = None, None, None
  with open(out_file, 'r') as f:
    for line in f:
      line = line.strip()
      if line.startswith("LAS F1"):
        las_score = line
      if line.startswith("MLAS"):
        mlas_score = line
      if line.startswith("BLEX"):
        blex_score = line
  if las_score and mlas_score and blex_score:
    if ltcode not in ltcode2results:
      ltcode2results[ltcode] = {}
    if fname.endswith('udtags'):
      ltcode2results[ltcode]['udpipe'] = {}
      for name, score in [('las', las_score), ('mlas', mlas_score), ('blex', blex_score)]:
        ltcode2results[ltcode]['udpipe'][name] = score.split()[3] if name == 'las' else score.split()[2]
      ltcode2results[ltcode]['elmolex-udtags'] = {}
      for name, score in [('las', las_score), ('mlas', mlas_score), ('blex', blex_score)]:
        ltcode2results[ltcode]['elmolex-udtags'][name] = score.split()[5] if name == 'las' else score.split()[4]
    if fname.endswith('bentags'):
      ltcode2results[ltcode]['elmolex-bentags'] = {}
      for name, score in [('las', las_score), ('mlas', mlas_score), ('blex', blex_score)]:
        ltcode2results[ltcode]['elmolex-bentags'][name] = score.split()[5] if name == 'las' else score.split()[4]

def get_map(mp, fst, scnd):
  if fst in mp:
    if scnd in mp[fst]:
      return mp[fst][scnd]
  return 'None'

las_w = open(las_f, 'w')
mlas_w = open(mlas_f, 'w')
blex_w = open(blex_f, 'w')
header = 'tb\tudpipe\telmolex-udtags\telmolex-bentags\n'
las_w.write(header)
mlas_w.write(header)
blex_w.write(header)
for ltcode in sorted(ltcode2results):
  for name, w in [('las', las_w), ('mlas', mlas_w), ('blex', blex_w)]:
    udpipe = get_map(ltcode2results[ltcode], 'udpipe', name)
    udtags = get_map(ltcode2results[ltcode], 'elmolex-udtags', name)
    bentags = get_map(ltcode2results[ltcode], 'elmolex-bentags', name)
    w.write(ltcode+"\t"+udpipe+"\t"+udtags+"\t"+bentags+"\n")
las_w.close()
mlas_w.close()
blex_w.close()

print('las, mlas and blex results respecitvely can be fetched from the following files:')
print(las_f)
print(mlas_f)
print(blex_f)


import threading

import wikipedia
from kivy.clock import mainthread
from kivymd.app import MDApp

class MainApp(MDApp):
    url = ""

    def build(self):
        self.title = "Wikipedia-App"

    @mainthread
    def search(self, text):
        t1 = threading.Thread(target=self.get_wiki, args=(text,), daemon=True)
        t1.start()

    def get_wiki(self, text):
        self.root.ids.rc_spin.active = True
        self.root.ids.summary.text = ""
        self.root.ids.title.text = ""

        wikipedia.set_lang("en")
        try:
            summary = wikipedia.page(text.strip())
            self.root.ids.title.text = summary.title
            self.root.ids.summary.text = f"\n{summary.summary}"
        except Exception as e:
            print(e)
            self.root.ids.title.text = (
                "[color=#EE4B2B]"
                + "Sorry unable to find "
                + self.root.ids.fld.text
                + "[/color]"
            )
        self.root.ids.rc_spin.active = False

if __name__ == "__main__":
    MainApp().run()


from .api import genshindb as gdb

def calc_talent_cost(name, current_level, to_level):
    """
    Calculate talent cost.
    :param name: character name
    :param current_level: current level
    :param to_level: to level
    :return: talent cost dict
    """
    if current_level >= to_level:
        return None
    json_data = gdb.get_tdata_by_cname(name)["costs"]

    talent_cost = {}
    for level in range(current_level + 1, to_level + 1):
        for cost in json_data[f"lvl{level}"]:
            name = cost["name"]
            count = cost["count"]
            if name not in talent_cost:
                talent_cost[name] = 0
            talent_cost[name] += count

    return talent_cost


#!/usr/bin/env python3
"""
Cache class. In the __init__ method, store an instance of the Redis }
client as a private variable named _redis (using redis.Redis()) and
flush the instance using flushdb.

"""

import redis
from typing import Union, Optional, Callable
from uuid import uuid4
from functools import wraps

def count_calls(method: Callable) -> Callable:
    """
    count how many times the function was called
    """

    key = method.__qualname__

    @wraps(method)
    def wrapper(self, *args, **kwargs):
        """ Wrapper for decorator functionality """
        self._redis.incr(key)
        return method(self, *args, **kwargs)

    return wrapper

def call_history(method: Callable) -> Callable:
    """
        store the history of inputs and outputs for a particular function.
    """

    inputs = '{}:inputs'.format(method.__qualname__)
    outputs = '{}:outputs'.format(method.__qualname__)

    @wraps(method)
    def wrapper(self, *args, **kwds):
        """wrapper function"""

        self._redis.rpush(inputs, str(args))
        output = method(self, *args, **kwds)
        self._redis.rpush(outputs, output)
        return output
    return wrapper

def replay(methodName: Callable) -> None:
    """
    Display the history of calls of a function
    """

    _redis = redis.Redis()
    try:
        calls = _redis.get(methodName.__qualname__).decode('utf-8')
    except Exception:
        calls = 0

    print(f'{methodName.__qualname__} was called {calls} times:')

    inputs = _redis.lrange(methodName.__qualname__ + ':inputs', 0, -1)
    outputs = _redis.lrange(methodName.__qualname__ + ':outputs', 0, -1)

    for input, output in zip(inputs, outputs):
        print('{}(*{}) -> {}'.format(methodName.__qualname__,
                                     input.decode('utf-8'),
                                     output.decode('utf-8')))

class Cache():
    """
    Main class for cache
    """
    def __init__(self):
        """ CONSTRUCTOR"""
        self._redis = redis.Redis()
        self._redis.flushdb()

    @call_history
    @count_calls
    def store(self, data: Union[str, bytes, int, float]) -> str:
        """
        Takes a data as argumen a store in a REDIS db
        Remember that data can be a str, bytes, int or float.

        Returns: A key in string format
        """
        _randomkey = uuid4().__str__()
        self._redis.set(_randomkey, data)
        return _randomkey

    def get(self, key: str,
            fn: Optional[Callable] = None) -> Union[str, bytes, int, float]:
        """  Get the values as specific func"""
        data = self._redis.get(key)
        if fn:
            return fn(data)
        return data

    def get_int(self, data: int) -> int:
        """  Get the values as int" """
        try:
            int(data)
            return data
        except Exception:
            return 0

    def get_str(self, data: str) -> str:
        """  Get the values as str"""
        return self._redis.get(data).decode('utf_8')


from os import system
def img():
      if x==1:
        y=input("enter the name of img")
        z=input("u want version y/n if n it will take latest").lower()
        if z=='y':
            a=input("enter the version eg 0.2")
            system(f"docker pull {y}:{a}")
        else:
            system(f"docker pull {y}")
def seeimg():
    system(f"docker image ls")
def seecon():
    print("all the containers")
    system("docker ps -a")
    print("all the running container")
    system("docker ps")
def attach():
    name=input("enter the name of docker")
    system(f"docker restart {name}")
    z=input("u want to attach to docker y/n")
    if z=='y':
        system(f"docker attach {name}")
def rmimg():
    seeimg()
    name=input()
    system(f"docker image rm -f {name}")
def rmcon():
    seecon()
    name=input()
    system(f"docker container rm -f {name}")
("\t\t\tWelcome to docker automation")
system("systemctl start docker")
while True:
    print("""\t\t\tpress 1 to pull img
             \t\t\tpress 2 to run docker
             \t\t\tpress 3 to make your own img
             \t\t\tpress 4 to make your own network
             \t\t\tpress 5 to make your own permanent storage
             \t\t\tpress 6 to see img
             \t\t\tpress 7 to see container
             \t\t\tpress 8 to remove container
             \t\t\tpress 9 to remove img
             \t\t\tpress 10 to exit
             \t\t\tpress 11 to attach
             \t\t\tpress 12 to remove network
             \t\t\tpress 13 to remove storage""")
    x=int(input())
    if x==1:
        img()
    elif x==2:
        k=""
        print("the img u have")
        p=system("docker image ls")
        print(p)
        z=input("enter image name:version")
        p="null"
        p=system(f"docker image ls|grep {z}")
        if p!=z:
            img()
        i=input("u want to run on back  y/n ").lower()
        if i=='y':
            k=k+" -d "
        i=input("u want to add name y/n ").lower()
        if i=='y':
            name=input("enter the new name")
            k=k+" --name "+name
        i=input("u want to add network y/n").lower()
        if i=='y':
            name=input("enter the name of network")
            k=k+" --network "+name
        i=input("u want to add volume y/n").lower()
        if i=='y':
            name=input("enter the name of volume or directory")
            name1=input("enter the directory where u want to copy")
            k=k+" --v "+name+":"+" "+name1
        k=k+" "+z
        system(f"docker run -it{k}")
    elif x==3:
        name=input("enter name or id of the container")
        name1=input("name of the img")
        system(f"docker commit {name} {name1}")
    elif x==4:
        name=input("enter a new network name")
        name1=input("name of driver host null bridge")
        if name1=="host" or name1=="null":
            print("plz remove first there must be one ")
        else:
            system(f"docker network create --driver {name1} name")
    elif x==5:
        name=input("enter a new voltage name")
        system(f"docker volume create {name}")
    elif x==6:
        seeimg()
    elif x==7:
        seecon()
    elif x==8:
        rmcon()
    elif x==9:
        rmimg()
    elif x==10:
        break
        system.exit(0)
    elif x==11:
        attach()
    elif x==12:
        name=input("enter the network name")
        system(f"docker network rm -f {name}")
    elif x==13:
        name=input("enter the volume name")
        system(f"docker volume rm -f {name}")


THEME_COLOR = "#375362"
FONT=("Arial",15,"italic")
from tkinter import *

from quiz_brain import QuizBrain

class Quizinterface:
    def __init__(self,quizbrain:QuizBrain):
        self.window= Tk()
        self.score=0
        self.quiz=quizbrain
        #label Score
        self.set()
        self.label=Label(text=f"Score: {self.score}",bg=THEME_COLOR,fg="white",pady=20)
        self.label.grid(row=0,column=1)

        # Refresh
        # self.refresh_image=PhotoImage(file="images/rename.png")
        self.refresh=Button(highlightthickness=0,text="Refresh",command=self.refresh_operations)
        self.refresh.grid(row=0,column=0)

        #Canvas
        self.canvas = Canvas(width="300", height="250", highlightthickness=0,bg="white")
        self.question_text=self.canvas.create_text(150,125,text="Some text",fill=THEME_COLOR,
                                                   font=FONT,width=200)
        self.canvas.grid(row=1, column=0, columnspan=2,pady=50)

        #Button tick and cross
        self.tick_image = PhotoImage(file="images/true.png")
        self.correct = Button(image=self.tick_image, highlightthickness=0,command=self.trueAnswered)
        self.correct.grid(column=0, row=2,pady=50)
        cross_image = PhotoImage(file="images/false.png")
        self.wrong = Button(image=cross_image, highlightthickness=0,command=self.falseAnswered)
        self.wrong.grid(row=2, column=1,pady=50)

        self.get_next()
        self.window.mainloop()

    def set(self):
        self.window.title("Quiz App")
        self.window.config(bg=THEME_COLOR,padx=20, pady=20)

    def get_next(self):
        if self.quiz.still_has_questions():
            self.canvas.config(bg="white")
            self.qtext=self.quiz.next_question()
            self.canvas.itemconfig(self.question_text,text=self.qtext)

    def falseAnswered(self):
        is_right = self.quiz.check_answer("false")
        print(is_right)
        self.feedback(is_right)
        #self.get_next()

    def trueAnswered(self):
        is_right=self.quiz.check_answer("True")
        print(is_right)
        self.feedback(is_right)

    # def check(self,is_right):
    #     if is_right==True:
    #         self.score+=1
    #         print(self.score)
    #
    #         self.feedback()
    #     else:
    #         self.feedback(False)

    def feedback(self,is_right):
        if is_right:
            self.canvas.config(bg="green")
            self.label.config(text=f"Score: {self.quiz.score}")
        else:
            self.canvas.config(bg="red")
        self.window.after(1000,self.get_next)

    def refresh_operations(self):
        self.quiz.ref()

        self.label.config(text=f"Score:{self.quiz.score}")


class Programmer:
    """

    """
    def __init__(self, name: str, language: str, skills: int):
        self.name = name
        self.language = language
        self.skills = skills

    def watch_course(self, course_name, language, skills_earned) -> str:
        """
        check if player knows the language, so they can
        watch the course
        :param course_name:
        :param language:
        :param skills_earned:
        :return:
        """
        if language == self.language:
            self.skills += skills_earned
            return f'{self.name} watched {course_name}'
        return f'{self.name} does not know {language}'

    def change_language(self, new_language, skills_needed):
        if new_language == self.language:
            return f'{self.name} already knows {new_language}'
        if skills_needed > self.skills:
            return f'{self.name} needs {skills_needed - self.skills} more skills'
        old_language, self.language = self.language, new_language
        self.skills = 0
        return f'{self.name} switched from {old_language} to {new_language}'

programmer = Programmer("John", "Java", 50)
print(programmer.watch_course("Python Masterclass", "Python", 84))
print(programmer.change_language("Java", 30))
print(programmer.change_language("Python", 100))
print(programmer.watch_course("Java: zero to hero", "Java", 50))
print(programmer.change_language("Python", 100))
print(programmer.watch_course("Python Masterclass", "Python", 84))

Python-OOP-Oct2023/Exercises/01.First Steps in OOP/07.Programmer.py


# **************************************************************************
# *
# * Authors:     J.L. Vilas (jlvilas@cnb.csi.es) [1]
# *
# * [1] Centro Nacional de Biotecnologia, CSIC, Spain
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2 of the License, or
# * (at your option) any later version.
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# * 02111-1307  USA
# *
# *  All comments concerning this program package may be sent to the
# *  e-mail address 'scipion@cnb.csic.es'
# *
# *********************************************************************

from pyworkflow import BETA
from pyworkflow.protocol.params import PointerParam
from tomo.objects import Tomogram
import os
from pyworkflow.object import Set
from xmipptomo.protocols.protocol_crop_resize_base import XmippProtCropBase3D

SUFIXCROPPED = '_cropped.mrc'

class XmippProtCropTomograms(XmippProtCropBase3D):
    """
    Protocol to crop tomograms using xmipp_transform_window.
    The protocol allows to change the size of a tomogram/s, by removing the
    borders defined by the users
    """
    _label = 'crop tomograms'
    _devStatus = BETA

    # --------------------------- DEFINE param functions ------------------------
    def _defineParams(self, form):
        form.addSection(label='Input')

        form.addParam('inputSet',
                      PointerParam,
                      pointerClass='SetOfTomograms',
                      important=True,
                      label='Input set of tomograms',
                      help='Select a set of tomograms to be cropped.')

        self._defineParamsReSize2D(form)
        self._defineParamsReSize3D(form)

    # --------------------------- INSERT steps functions ------------------------
    def _insertAllSteps(self):
        for tomo in self.inputSet.get():
            self._insertFunctionStep(self.cropTomogramsStep, self.inputSet.get(), tomo.getObjId())
        self._insertFunctionStep('closeStreamStep')

    # --------------------------- STEP functions --------------------------------
    def cropTomogramsStep(self, tomoSet, tomId):
        '''
        This function resize the tomograms by means of xmipp_transform_window.
        The output is create in pseudo-streaming. pseudo because the input is
        not open, but the output is updated during the execution of the protocol
        '''
        ts = self.inputSet.get()[tomId]
        tsId = ts.getTsId()

        outputPath = self._getExtraPath(str(tsId))
        # Defining the output folder
        os.mkdir(outputPath)

        inputTomo = tomoSet[tomId].getFileName()
        outputTomo = self.outputTomoFileName(outputPath, tsId, SUFIXCROPPED)

        # Launching the xmipp command
        params = ' -i %s ' % inputTomo
        params += ' -o %s ' % outputTomo
        params += ' --corners %i %i %i %i %i %i ' %(self.xcrop0.get(), self.ycrop0.get(),
                                                 self.zcrop0.get(), self.xcropF.get(),
                                                 self.ycropF.get(), self.zcropF.get())
        params += ' --physical'
        self.runJob("xmipp_transform_window", params)

        # Creating the output in pseudostreaming
        outputresizedSetOfTomograms = self.getOutputSetOfTomograms()
        newTomogram = Tomogram()
        tomo = self.inputSet.get()[tomId]
        newTomogram.copyInfo(tomo)
        newTomogram.copyAttributes(tomo, '_origin')

        newTomogram.setLocation(outputTomo)

        newTomogram.setSamplingRate(self.inputSet.get().getSamplingRate())
        outputresizedSetOfTomograms.append(newTomogram)
        outputresizedSetOfTomograms.update(newTomogram)
        outputresizedSetOfTomograms.write()
        self._store()

    def outputTomoFileName(self, folder, tomId, ext):
        fnPath = os.path.join(folder, str(tomId) + ext)
        return fnPath

    def closeStreamStep(self):
        self.getOutputSetOfTomograms().setStreamState(Set.STREAM_CLOSED)
        self._store()

    def getOutputSetOfTomograms(self):
        '''
        This function defines the output of the protocol
        '''
        if hasattr(self, "outputSetOfTomograms"):
            self.outputSetOfTomograms.enableAppend()
        else:
            outputSetOfTomograms = self._createSetOfTomograms(suffix='cropped')
            outputSetOfTomograms.copyInfo(self.inputSet.get())
            outputSetOfTomograms.setSamplingRate(self.inputSet.get().getSamplingRate())
            outputSetOfTomograms.setStreamState(Set.STREAM_OPEN)
            self._defineOutputs(outputSetOfTomograms=outputSetOfTomograms)
            self._defineSourceRelation(self.inputSet, outputSetOfTomograms)
        return self.outputSetOfTomograms

    # --------------------------- INFO functions ----------------------------
    def _summary(self):
        summary = []
        if hasattr(self, 'outputSetOfTomograms'):
            summary.append("%d tomograms have been resized using the xmipp_transform_window program\n"
                           % self.outputSetOfTomograms.getSize())
        else:
            summary.append("Output not ready yet.")
        return summary

    def _methods(self):
        methods = []
        if hasattr(self, 'outputSetOfTomograms'):
            methods.append("%d tomograms have been resized using the xmipp_transform_window program\n"
                           % self.outputSetOfTomograms.getSize())
        else:
            methods.append("Output tomograms not ready yet.")
        return methods


import os
import cv2
import shutil

source_path = 'test_copy_image'
des_path = 'train_image_label'

def get_all_label_file_to_image_file():
    list_file = os.listdir(source_path)
    list_label = [file for file in list_file if file.endswith('.txt')]
    return list_label

def copy_image_according_to_label():
    label_name = get_all_label_file_to_image_file()
    print('There are {} label files'.format(len(label_name)))
    print(label_name)

    # copy files
    for name in label_name:
        # copy text file
        orig_label = os.path.join(source_path, name)
        des_label = os.path.join(des_path, name)
        print(des_label)
        shutil.copy(orig_label, des_label)

        # copy image file
        img_name = name.split('.')[0] + '.jpg'
        orig_img = os.path.join(source_path, img_name)
        #print(origin)
        des_img = os.path.join(des_path, img_name)
        #print(des)
        img = cv2.imread(orig_img)
        cv2.imwrite(des_img, img)

copy_image_according_to_label()


from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse

from ..filters.CRPFilter import CRPFilter
from ..forms.CRPForm import UpdateCRPForm, CRPTrackForm, AddCRPForm
from django.forms import modelformset_factory
from datetime import datetime, timedelta
from ..forms.ProductCenterForm import CapacitySchedulingFormCRP
from ..models.CRP import CRPTrack, CRP
from ..models.Finished import Finished
from ..models.OperationList import OperationList
from ..models.ProductCenter import ProductCenter, CapacityScheduling
from ..models.OperationSequence import OperationSequence
from django.contrib import messages

list_crp_props = {
    "title": "CRP",

}

post_crp_props = {
    "title": "Add CRP",

}

views_crp_props = {
    "title": "View CRP",

}

update_crp_props = {
    "title": "Update CRP",
    'btn_name': 'Update'
}

copy_crp_props = {
    "title": "Copy CRP",
    'btn_name': 'Copy'

}

def ListCRP(request):
    if request.method == "GET":
        crp_track = CRPTrack.objects.all()
        list_crp_props['crp_track'] = crp_track
        list_crp_props['filters'] = CRPFilter()
        return render(request, 'PP/planning/crp/list.html', context=list_crp_props)

def FilterCRP(request):
    if request.method == 'POST':
        filter = CRPFilter(request.POST, queryset=CRPTrack.objects.all())
        if filter.is_valid():
            if len(filter.qs.values()) != 0:
                return JsonResponse({
                    'CRPTrack': list(filter.qs.values()),
                    'mass': 'success',
                }, status=200)
            else:
                return JsonResponse({
                    'mass': 'error',
                }, status=200)
        else:
            return JsonResponse({
                'mass': 'error',
            })
    else:
        return JsonResponse({
            'mass': 'error',
        })

def PostCRP(request):
    if request.method == "POST":
        finish = request.POST.get('finished_no')
        order_ref = request.POST.get('order_ref')
        order_qty = request.POST.get('order_qty')

        if request.is_ajax():
            finish = Finished.objects.get(id=finish)
            opl = OperationList.objects.filter(id=finish.operations_list.id).values()
            opsec = OperationSequence.objects.filter(operation_list=finish.operations_list).values()
            crp = []
            for ops in opsec:
                pc = ProductCenter.objects.get(id=ops['production_center_id'])
                cs = CapacityScheduling.objects.filter(ProductCenterId=ops['production_center_id']).last()
                crp.append({
                    'operationSequence': ops['operationSequence'],
                    'productioncneter': pc.product_center_name,
                    'AvalStartDate': cs.Date,
                    'reqdcapunit': ops['reqdcapunit'],
                    'ReqdMcHrByUnit': ops['totaltime'],
                    'AvalStartTime': cs.EndTime,
                    'AvalMcHrOrDay': cs.BalMcOrHour,
                    'NoOfMCByResAval': int(pc.NoOfMByC) - int(cs.NoOfMCAlloctd),
                    'AvalCAPByDay': cs.BalanceCap,
                })

            crp_track_form = CRPTrackForm({'finished': finish,
                                           'operationlist': finish.operations_list.id,
                                           'product_description': finish.product_description,
                                           'order_ref': order_ref,
                                           'order_qty': order_qty
                                           })

            if crp_track_form.is_valid():
                crp_track_form = crp_track_form.save()
                return JsonResponse({
                    'mass': "success",
                    'operation_scheduling': list(opsec),
                    'crps': crp,
                    'CRPTrack': list(CRPTrack.objects.filter(id=crp_track_form.id).values())
                }, status=200)

        operationSequence = request.POST.getlist('operationSequence')
        productioncneter = request.POST.getlist('productioncneter')
        AvalStartDate = request.POST.getlist('AvalStartDate')
        StartDate = request.POST.getlist('StartDate')
        NoOfMCByResAval = request.POST.getlist('NoOfMCByResAval')
        AvalCAPByDay = request.POST.getlist('AvalCAPByDay')
        reqdcapunit = request.POST.getlist('reqdcapunit')
        ReqdCAPByDay = request.POST.getlist('ReqdCAPByDay')
        AvalMcHrOrDay = request.POST.getlist('AvalMcHrOrDay')
        ReqdMcHrByUnit = request.POST.getlist('ReqdMcHrByUnit')
        ReqdMcHour = request.POST.getlist('ReqdMcHour')
        AvalStartTime = request.POST.getlist('AvalStartTime')
        StartTime = request.POST.getlist('StartTime')
        EndTime = request.POST.getlist('EndTime')
        EndDate = request.POST.getlist('EndDate')
        NoOfMcByRes = request.POST.getlist('NoOfMcByRes')
        mc_id_no = request.POST.getlist('mc_id_no')
        crp_track = request.POST.getlist('crp_track')
        mass = False
        if len(operationSequence) != 0:
            for x in range(0, len(operationSequence)):
                crp = AddCRPForm({
                    'crp_track': CRPTrack.objects.get(id=crp_track[x]),
                    'operationSequence': operationSequence[x],
                    "productioncneter": productioncneter[x],
                    "reqdcapunit": reqdcapunit[x],
                    "ReqdMcHrByUnit": ReqdMcHrByUnit[x],
                    "AvalStartDate": AvalStartDate[x],
                    'AvalStartTime': AvalStartTime[x],
                    "NoOfMCByResAval": NoOfMCByResAval[x],
                    "AvalCAPByDay": AvalCAPByDay[x],
                    'AvalMcHrOrDay': AvalMcHrOrDay[x],
                    'StartDate': StartDate[x],
                    'ReqdCAPByDay': ReqdCAPByDay[x],
                    'ReqdMcHour': ReqdMcHour[x],
                    'StartTime': StartTime[x],
                    'EndTime': EndTime[x],
                    'EndDate': EndDate[x],
                    'NoOfMcByRes': NoOfMcByRes[x],
                    'mc_id_no': mc_id_no[x]
                })

                if crp.is_valid():
                    crp = crp.save()
                    crp_tracks = CRPTrack.objects.get(id=crp.crp_track)

                    BalanceCap = int(crp.AvalCAPByDay) - int(crp.ReqdCAPByDay)

                    cs = CapacitySchedulingFormCRP({
                        'ProductCenterId': ProductCenter.objects.get(product_center_name=crp.productioncneter),
                        'Date': crp.AvalStartDate,
                        'AvalCapOrDay': crp.AvalCAPByDay,
                        'CapALlloctdTo': crp_tracks.finished.id,
                        'AlloctdCap': crp.ReqdCAPByDay,
                        'BalanceCap': BalanceCap,
                        'AvalMcOrResHour': crp.AvalMcHrOrDay,
                        'ReqdMcOrResHour': crp.ReqdMcHour,
                        'BalMcOrHour': str(float(crp.AvalMcHrOrDay) - float(crp.ReqdMcHour)),
                        'StartTime': crp.StartTime,
                        'EndTime': crp.EndTime,
                        'NoOfMCAlloctd': crp.NoOfMcByRes,

                    })
                    if cs.is_valid():
                        cs.save()
                    if BalanceCap == 0:
                        AvalStartDates = datetime.strptime(str(crp.AvalStartDate), '%Y-%m-%d')
                        AvalStartDates = AvalStartDates + timedelta(days=1)
                        pc = ProductCenter.objects.get(product_center_name=crp.productioncneter)
                        csl = CapacityScheduling.objects.filter(ProductCenterId=pc.id).first()
                        cs = CapacitySchedulingFormCRP({
                            'ProductCenterId': ProductCenter.objects.get(product_center_name=crp.productioncneter),
                            'Date': AvalStartDates,
                            'AvalCapOrDay': csl.AvalCapOrDay,
                            'CapALlloctdTo': csl.CapALlloctdTo,
                            'AlloctdCap': csl.AlloctdCap,
                            'BalanceCap': csl.BalanceCap,
                            'AvalMcOrResHour': csl.AvalMcOrResHour,
                            'ReqdMcOrResHour': csl.ReqdMcOrResHour,
                            'BalMcOrHour': csl.BalMcOrHour,
                            'StartTime': csl.StartTime,
                            'EndTime': csl.EndTime,
                            'NoOfMCAlloctd': csl.NoOfMCAlloctd,
                        })
                        if cs.is_valid():
                            cs.save()
                    mass = True
                else:
                    mass = False
            if mass:
                messages.success(request, 'CRP Created Successfully.')
            return HttpResponseRedirect(reverse('productionplanning:CRP', args={crp_track[0]}))
        else:
            messages.error(request, 'CRP Not Created Successfully.')

        return render(request, 'PP/Planning/crp/general_data_form.html', context=post_crp_props)
    else:
        return render(request, 'PP/Planning/crp/general_data_form.html', context=post_crp_props)

def AddCRP(request, id):
    crp_track = CRPTrack.objects.get(id=id)
    crp = CRP.objects.filter(crp_track=crp_track.id)
    post_crp_props['crp_track'] = crp_track
    post_crp_props['crp'] = crp
    return render(request, 'PP/Planning/crp/add_crp.html', context=post_crp_props)

def ViewCRP(request, id):
    crp_track = CRPTrack.objects.get(id=id)
    crp = CRP.objects.filter(crp_track=crp_track.id)
    views_crp_props['crp_track'] = crp_track
    views_crp_props['crp'] = crp
    return render(request, 'PP/Planning/crp/views.html', context=views_crp_props)

def UpdateCRP(request, id):
    crp_track = CRPTrack.objects.get(id=id)
    crp = CRP.objects.filter(crp_track=crp_track.id)
    update_crp_props['crp_track'] = crp_track
    update_crp_props['crp'] = crp
    CRPFoemSet = modelformset_factory(CRP, form=UpdateCRPForm, extra=0)
    formset = CRPFoemSet(queryset=crp)
    update_crp_props['formset'] = formset
    if request.POST:
        formset = CRPFoemSet(request.POST, queryset=crp)
        if formset.has_changed():
            if formset.is_valid():
                formset.save()
                messages.success(request, 'CRP Update Successfully.')
                return HttpResponseRedirect(reverse('productionplanning:UpdateCRP', args={crp_track.id}))
            else:
                messages.error(request, 'CRP Form is not valid.')
                return HttpResponseRedirect(reverse('productionplanning:UpdateCRP', args={crp_track.id}))
        else:
            messages.error(request, 'Value is not Change.')
            return HttpResponseRedirect(reverse('productionplanning:UpdateCRP', args={crp_track.id}))
    else:
        return render(request, 'PP/Planning/crp/update_crp.html', context=update_crp_props)

def CopyCRP(request, id):
    crp_track = CRPTrack.objects.get(id=id)
    crp = CRP.objects.filter(crp_track=crp_track.id)
    copy_crp_props['crp_track'] = crp_track
    copy_crp_props['crp'] = crp
    CRPFoemSet = modelformset_factory(CRP, form=UpdateCRPForm, extra=0)
    formset = CRPFoemSet(queryset=crp)
    copy_crp_props['formset'] = formset
    if request.POST:
        mass = []
        crp_trackForm = CRPTrackForm(data={
            'finished': crp_track.finished,
            'operationlist': crp_track.operationlist,
            'product_description': crp_track.product_description,
            'order_ref': crp_track.order_ref,
            'order_qty': crp_track.order_qty,
        })
        if crp_trackForm.is_valid():
            crp_trackForm = crp_trackForm.save()
            for x in crp:
                dirs = {
                    'crp_track': CRPTrack.objects.get(id=crp_trackForm.id),
                    'operationSequence': x.operationSequence,
                    'productioncneter': x.productioncneter,
                    'AvalStartDate': x.AvalStartDate,
                    'StartDate': x.StartDate,
                    'reqdcapunit': x.reqdcapunit,
                    'ReqdMcHrByUnit': x.ReqdMcHrByUnit,
                    'AvalStartTime': x.AvalStartTime,
                    'AvalMcHrOrDay': x.AvalMcHrOrDay,
                    'NoOfMCByResAval': x.NoOfMCByResAval,
                    'AvalCAPByDay': x.AvalCAPByDay,
                    'ReqdCAPByDay': x.ReqdCAPByDay,
                    'ReqdMcHour': x.ReqdMcHour,
                    'StartTime': x.StartTime,
                    'EndTime': x.EndTime,
                    'EndDate': x.EndDate,
                    'NoOfMcByRes': x.NoOfMcByRes,
                    'mc_id_no': x.mc_id_no,
                }
                crp_form = UpdateCRPForm(data=dirs)
                print(2,crp_form.is_valid())
                if crp_form.is_valid():
                    crp_form = crp_form.save(commit=False)
                    crp_form.crp_track = CRPTrack.objects.get(id=crp_trackForm.id)
                    crp_form.save()
                    mass.append(True)
                else:
                    mass.append(False)
            if len(mass) == mass.count(True):
                messages.success(request, '{} to {} Copy Successfully.'.format(id, crp_trackForm.id))
                return redirect('/productionplanning/crp/')
            else:
                messages.error(request, 'Copy Not Successfully.')
                return redirect('/productionplanning/crp/')
        else:
            messages.error(request, "CRP Form isn't Valid.")
            return redirect('/productionplanning/crp/')

    else:
        return render(request, 'PP/Planning/crp/update_crp.html', context=copy_crp_props)

def DeleteCRP(request, id):
    crp = CRPTrack.objects.get(id=id)
    crp.delete()
    messages.error(request, '{} Delete Successfully.'.format(id))
    return redirect('/productionplanning/crp/')


class Task:
    def __init__(self, id, description):
        self.id = id
        self.description = description

class TaskList:
    def __init__(self, file_name):
        self.file_name = file_name
        self.tasks = []
        self.load_tasks()

    def load_tasks(self):
        try:
            with open(self.file_name, 'r') as f:
                for line in f:
                    id, description = line.strip().split('|')
                    self.tasks.append(Task(id, description))
        except FileNotFoundError:
            pass

    def save_tasks(self):
        with open(self.file_name, 'w') as f:
            for task in self.tasks:
                f.write(f"{task.id}|{task.description}\n")

    def create_task(self, description):
        id = len(self.tasks) + 1
        task = Task(id, description)
        self.tasks.append(task)
        self.save_tasks()
        return task

    def read_tasks(self):
        return self.tasks

    def update_task(self, id, description):
        for task in self.tasks:
            if task.id == id:
                task.description = description
                self.save_tasks()
                return task

    def delete_task(self, id):
        for i, task in enumerate(self.tasks):
            if task.id == id:
                del self.tasks[i]
                self.save_tasks()
                return

# Exemplo de uso:
task_list = TaskList('tasks.txt')

while True:
    # Imprime o menu de opções
    print('\nEscolha uma opção:')
    print('1. Ver tarefas')
    print('2. Adicionar tarefa')
    print('3. Atualizar tarefa')
    print('4. Remover tarefa')
    print('0. Sair')

    # Lê a opção escolhida pelo usuário
    option = input('> ')

    if option == '1':
        # Ler todas as tarefas
        tasks = task_list.read_tasks()
        for task in tasks:
            print(task.id, task.description)

    elif option == '2':
        # Criar uma nova tarefa
        description = input('Digite a descrição da tarefa: ')
        task = task_list.create_task(description)
        print(f'Tarefa {task.id} adicionada com sucesso!')

    elif option == '3':
        # Atualizar uma tarefa existente
        id = input('Digite o ID da tarefa que deseja atualizar: ')
        description = input('Digite a nova descrição da tarefa: ')
        task = task_list.update_task(int(id), description)
        if task:
            print(f'Tarefa {task.id} atualizada com sucesso!')
        else:
            print('Tarefa não encontrada')

    elif option == '4':
        # Remover uma tarefa existente
        id = input('Digite o ID da tarefa que deseja remover: ')
        task_list.delete_task(int(id))
        print(f'Tarefa {id} removida com sucesso!')

    elif option == '0':
        # Sai do programa
        break

    else:
        print('Opção inválida, tente novamente')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 31 11:56:58 2019

@author: saransh
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans,AgglomerativeClustering,DBSCAN
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn import metrics
from scipy.optimize import linear_sum_assignment

def purity_score(y_true, y_pred):
    contingency_matrix = metrics.cluster.contingency_matrix(y_true, y_pred)
    row_ind, col_ind = linear_sum_assignment(-contingency_matrix)
    return contingency_matrix[row_ind, col_ind].sum() / np.sum(contingency_matrix)

csv = pd.read_csv("Iris.csv")
datay = csv["Species"]
data = csv.drop(columns = ["Species"],axis = 1)
#pca = PCA(n_components=2).fit(data)
data = PCA(n_components=2).fit_transform(data)
data=pd.DataFrame(data)
print("_________________")
print(" ")
print("2D-Points After Reducing Dimensions ")
print("_________________")
plt.scatter(data.iloc[:,0],data.iloc[:,1],color="blue")
plt.show()

Kmean = KMeans(n_clusters=3)
labels = Kmean.fit_predict(data)
#labels = Kmean.predict(data)
print("_________________")
print(" ")
print("KMeans Clustering")
print("_________________")
plt.scatter(data.iloc[:,0],data.iloc[:,1],c=Kmean.labels_,cmap='viridis')
centers=Kmean.cluster_centers_
plt.scatter(centers[:,0],centers[:,1],s=100,c='black')
plt.show()
print("purity score for KMeans Clustering is -")
print(purity_score(pd.DataFrame(datay),pd.DataFrame(labels)))
print("_________________")

print(" ")
print(" ")
print(" ")

print("_________________")
print(" ")
print("Agglomerative Clustering")
print("_________________")
cluster = AgglomerativeClustering(n_clusters=3, affinity='euclidean', linkage='average')
labelag=cluster.fit_predict(data)
plt.scatter(data.iloc[:,0],data.iloc[:,1], c=cluster.labels_, cmap='rainbow')
plt.show()
'''
Kmean.fit(data)
labels = Kmean.predict(data)
print("_________________")
print(" ")
print("KMeans Clustering")
print("_________________")
plt.scatter(data.iloc[:,0],data.iloc[:,1],c=labels,cmap='viridis')
centers=Kmean.cluster_centers_
plt.scatter(centers[:,0],centers[:,1],s=100,c='black')
plt.show()
print("purity score for KMeans Clustering is -")
print(purity_score(pd.DataFrame(datay),pd.DataFrame(labels)))
print("_________________")

plt.show()
'''
print("purity score for Agglomerative Clustering is -")
print(purity_score(pd.DataFrame(datay),pd.DataFrame(labelag)))
print("_________________")

print(" ")

print(" ")

print("_________________")
print(" ")
print("DBSCAN")
print("_________________")

epsp=[0.05,0.5,0.95]
min_samplesp=[1,5,10,20]
ps=[]
arr = []
for i in epsp:
    for j in min_samplesp:
        db = DBSCAN(eps = i, min_samples = j)
        arr.append([i,j])
        labels1 = db.fit_predict(data)
        ps.append([purity_score(pd.DataFrame(datay),pd.DataFrame(labels1)),i,j])
psmax=max(ps)
ind = ps.index(psmax)
print('for eps = 0.05 and minpts = 1')
db = DBSCAN(eps = 0.05, min_samples = 1).fit(data)
labels1 = db.labels_
plt.scatter(data.iloc[:,0],data.iloc[:,1], c=db.labels_)
plt.show()

db = DBSCAN(eps = arr[ind][0], min_samples = arr[ind][1]).fit(data)
labels1 = db.labels_
plt.scatter(data.iloc[:,0],data.iloc[:,1], c=db.labels_, cmap='rainbow')
plt.show()

print("purity score for DBSAN is -")
print(purity_score(pd.DataFrame(datay),pd.DataFrame(labels1)))
print("_________________")


actor_name = input()
points_from_academy = float(input())
number_of_evaluators = int(input())
total_points = points_from_academy
total_evaluator_points = 0
difference = 0
is_nominated = False
for evaluator in range(number_of_evaluators):
    evaluator_name = input()
    evaluator_points = float(input())
    total_evaluator_points = len(evaluator_name) * evaluator_points / 2
    total_points += total_evaluator_points
    if total_points > 1250.5:
        is_nominated = True
        break
if is_nominated:
    print(f"Congratulations, {actor_name} got a nominee for leading role with {total_points:.1f}!")
if not is_nominated:
    difference = abs(total_points - 1250.5)
    print(f"Sorry, {actor_name} you need {difference:.1f} more!")


import logging
import warnings
from typing import List, Tuple

import numpy as np
import pandas as pd
from anndata import AnnData
from mudata import MuData
from pandas.api.types import is_numeric_dtype
from sklearn.neighbors import KNeighborsClassifier

from ..utils import check_transition_rule, get_views_from_structure
from .MultiViewAtlas import MultiViewAtlas, _harmonize_mdata_full

warnings.simplefilter(action="ignore", category=FutureWarning)
warnings.simplefilter(action="ignore", category=UserWarning)

# logger = logging.getLogger(__name__)
# logger.propagate = False
# ch = RichHandler(level=logging.INFO, show_path=False, show_time=False)
# formatter = logging.Formatter("%(message)s")
# ch.setFormatter(formatter)
# logger.addHandler(ch)

def load_query(
    mvatlas: MultiViewAtlas,
    adata_query: AnnData,
) -> MultiViewAtlas:
    """Load query data to full view of multi-view atlas

    Params:
    -------
        mvatlas:
            MultiViewAtlas object
        adata_query:
            AnnData of query data

    Returns:
    --------
        MultiViewAtlas object with mapped query cells in full view
    """
    # Define all current view - next view pairs for assignment
    view_pairs = mvatlas.get_view_pairs()

    # Check if query cells already in mdata
    if adata_query.obs_names.isin(mvatlas.mdata.obs_names).all():
        vdata_full = mvatlas.mdata["full"].copy()
    else:
        vdata_full = concatenate_query(mvatlas, adata_query, "full")
        # Check that at least one mapping from full view is possible with transition rules
        rules_from_full = view_pairs[view_pairs.depth == 0]["transition_rule"].unique()
        missing_rules = []
        for r in rules_from_full:
            try:
                if check_transition_rule(adata_query, r) is None:
                    continue
            except ValueError:
                missing_rules.append(r)
        if len(rules_from_full) == len(missing_rules):
            raise ValueError(
                f"""
                No mapping possible from full view. Please add info on rules {missing_rules} to query dataset
                """
            )

    mdata = mvatlas.mdata.copy()
    mdata.mod["full"] = vdata_full.copy()
    try:
        mdata.update()
    except KeyError:
        mdata.update()
    del mdata.obsm["view_assign"]
    mvatlas_mapped = MultiViewAtlas(mdata, rename_obsm=False)
    mvatlas_mapped.view_transition_rule = mvatlas.view_transition_rule.copy()

    _harmonize_mdata_full(mvatlas_mapped)
    return mvatlas_mapped

def split_query(
    mvatlas_mapped: MultiViewAtlas,
) -> MultiViewAtlas:
    """Assign query data to views in atlas, based on transition rules.

    Params:
    -------
        mvatlas:
            MultiViewAtlas object

    Returns:
    --------
        MultiViewAtlas object with mapped query cells
    """
    # Define all current view - next view pairs for assignment
    view_pairs = mvatlas_mapped.get_view_pairs()

    # Check that load_query was run
    try:
        if sum(mvatlas_mapped.mdata["full"].obs["dataset_group"] == "query") == 0:
            raise ValueError("No query cells in mdata - run load_query first")
    except KeyError:
        raise ValueError("No query cells in mdata - run load_query first")

    vdata_full = mvatlas_mapped.mdata["full"].copy()

    new_view_assign = pd.DataFrame()
    vdata_dict = {}
    vdata_dict["full"] = vdata_full.copy()
    for _, row in view_pairs.iterrows():
        depth = row["depth"]
        current_view = row["parent_view"]
        next_view = row["child_view"]
        try:
            n_query_current = sum(vdata_dict[current_view].obs["dataset_group"] == "query")
        except KeyError:
            n_query_current = 0
        try:
            n_query_next = sum(mvatlas_mapped.mdata[next_view].obs["dataset_group"] == "query")
        except KeyError:
            n_query_next = 0
        # if "dataset_group" in vdata_dict[current_view].obs:
        if n_query_current > 0:
            adata_query = vdata_dict[current_view][vdata_dict[current_view].obs["dataset_group"] == "query"].copy()
            logging.info(f"Assigning to {next_view} from {current_view} with rule {row['transition_rule']}")
            # print(adata_query)
            # print(vdata_dict[current_view])
            # print(mvatlas_mapped.mdata[current_view])
            if n_query_next > 0:
                logging.info(f"Query cells already in {next_view}")
                v_assign = mvatlas_mapped.mdata.obsm["view_assign"][[next_view]]
                vdata_dict[next_view] = mvatlas_mapped.mdata[next_view].copy()
            else:
                adata_query_concat = AnnData(obs=adata_query.obs, obsm=adata_query.obsm, obsp=adata_query.obsp)
                if depth > 0:
                    adata_query_concat = adata_query_concat[
                        new_view_assign.loc[adata_query_concat.obs_names, current_view] == 1
                    ].copy()
                v_assign, next_view_adata = map_next_view(
                    mvatlas_mapped, adata_query_concat, current_view=current_view, next_view=next_view
                )
                vdata_dict[next_view] = next_view_adata.copy()
        else:
            logging.info(f"No query cells in {current_view}")
            v_assign = mvatlas_mapped.mdata.obsm["view_assign"][[next_view]]
            vdata_dict[next_view] = mvatlas_mapped.mdata[next_view].copy()
        new_view_assign = pd.concat([new_view_assign, v_assign], 1)

    new_view_assign = new_view_assign.fillna(0)
    vdata_full.obsm["view_assign"] = new_view_assign.copy()
    vdata_full.uns["view_hierarchy"] = mvatlas_mapped.view_hierarchy
    vdata_dict["full"] = vdata_full
    mdata = MuData({v: vdata_dict[v] for v in get_views_from_structure(mvatlas_mapped.view_hierarchy)})
    mdata.mod["full"] = mdata.mod["full"][mdata.obs_names].copy()
    view_transition_rule = mvatlas_mapped.view_transition_rule.copy()
    # trans_rule = pd.Series(mvatlas.view_transition_rule.values.ravel()).dropna().unique()[0]
    mvatlas_mapped = MultiViewAtlas(mdata, rename_obsm=False, transition_rule=view_transition_rule)
    # mvatlas_mapped.view_transition_rule = view_transition_rule.copy()
    return mvatlas_mapped

def concatenate_query(
    mvatlas: MultiViewAtlas,
    adata_query: AnnData,
    view: str,
    batch_key: str = "dataset_group",
    batch_categories: List[str] = None,
):
    """Concatenate query data to atlas data"""
    if batch_categories is None:
        batch_categories = ["atlas", "query"]

    adata_atlas = mvatlas.mdata[view].copy()
    assert np.intersect1d(adata_atlas.obs_names, adata_query.obs_names).size == 0
    adata_atlas = adata_atlas.concatenate(
        adata_query, batch_key=batch_key, batch_categories=batch_categories, index_unique=None, uns_merge="unique"
    )
    return adata_atlas

def assign_from_similarity(Y_assign_atlas, X_similarity_atlas, X_similarity_query, v_assign, k=10):
    """Assign query cells to atlas views based on similarity to atlas cells.

    Similarity can be derived from metadata annotation or from latent space
    """
    if not isinstance(v_assign, pd.DataFrame):
        raise ValueError("v_assign must be a pandas DataFrame")
    if not v_assign.shape[1] == 1:
        raise ValueError("v_assign must have only one column")

    clf = KNeighborsClassifier(n_neighbors=k, metric="euclidean").fit(X_similarity_atlas, Y_assign_atlas)
    Y_assign_query = clf.predict(X_similarity_query)
    assign_predict = pd.DataFrame(Y_assign_query, columns=v_assign.columns)
    return assign_predict

def map_next_view(
    mvatlas: MultiViewAtlas,
    adata_query: AnnData,
    current_view: str,
    next_view: str,
    batch_key: str = "dataset_group",
    batch_categories: List[str] = None,
) -> Tuple[pd.DataFrame, AnnData]:
    """Assign query cells to next view based on similarity to atlas cells.

    Similarity is defined by the transition rule.
    """
    if batch_categories is None:
        batch_categories = ["atlas", "query"]

    # curr_view_adata = _concatenate_query(mvatlas, adata_query, current_view, batch_key=batch_key, batch_categories=batch_categories)
    curr_view_adata = mvatlas.mdata[current_view].copy()
    next_view_adata = mvatlas.mdata[next_view].copy()

    # Get similarity from transition rule
    if batch_key in curr_view_adata.obs.columns:
        v_assign = mvatlas.mdata.obsm["view_assign"].loc[mvatlas.mdata["full"].obs[batch_key] == batch_categories[0]][
            [next_view]
        ]
        curr_view_adata = curr_view_adata[curr_view_adata.obs[batch_key] == batch_categories[0]].copy()
        # next_view_adata = next_view_adata[next_view_adata.obs[batch_key] == batch_categories[0]].copy()
        # assert "dataset_group" not in next_view_adata.obs.columns
    else:
        v_assign = mvatlas.mdata.obsm["view_assign"].loc[mvatlas.mdata["full"].obs[batch_key] == batch_categories[0]][
            [next_view]
        ]
    transition_rule = mvatlas.view_transition_rule[current_view][next_view]
    if transition_rule is not None:
        try:
            check_transition_rule(adata_query, transition_rule)
        except ValueError:
            logging.warning(
                f"Could not check transition rule {transition_rule} for query data - skipping mapping from {current_view} to {next_view}"
            )
            v_assign_query = pd.DataFrame(0, columns=[next_view], index=adata_query.obs_names)
            v_assign = pd.concat([v_assign, v_assign_query], axis=0)
            return v_assign, next_view_adata
        # Split to next view based on transition rule
        # if transition is in obs
        if transition_rule in adata_query.obs.columns:
            if is_numeric_dtype(adata_query.obs[transition_rule]):
                X_similarity_atlas = curr_view_adata.obs[[transition_rule]].values
                X_similarity_query = adata_query.obs[[transition_rule]].values
            else:
                X_similarity_atlas = pd.get_dummies(curr_view_adata.obs[transition_rule])
                X_similarity_query = pd.get_dummies(adata_query.obs[transition_rule])

                # Check for missing levels
                missing_cols = [x for x in X_similarity_atlas.columns if x not in X_similarity_query.columns]
                if len(missing_cols) > 0:
                    X_similarity_query[missing_cols] = 0
                    X_similarity_query = X_similarity_query[X_similarity_atlas.columns].copy()

                X_similarity_atlas = X_similarity_atlas.values
                X_similarity_query = X_similarity_query.values

        if transition_rule in adata_query.obsm:
            X_similarity_atlas = curr_view_adata.obsm[transition_rule]
            X_similarity_query = adata_query.obsm[transition_rule]
        # X_similarity = curr_view_adata.obsm[transition_rule]
    else:
        raise ValueError(f"No transition rule defined for {current_view} -> {next_view}")

    # Get assignment to next view
    Y_assign_atlas = v_assign.loc[curr_view_adata.obs_names].values.ravel()

    v_assign_query = assign_from_similarity(Y_assign_atlas, X_similarity_atlas, X_similarity_query, v_assign)
    v_assign_query.index = adata_query.obs_names

    v_assign = pd.concat([v_assign, v_assign_query], axis=0)
    next_view_adata = concatenate_query(
        mvatlas,
        adata_query[v_assign_query[next_view] == 1],
        next_view,
        batch_key=batch_key,
        batch_categories=batch_categories,
    )

    return v_assign, next_view_adata


'''
Exercise 5

Take two lists, say for example these two:

  a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.

Extras:

1. Randomly generate two lists to test this
2. Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)
'''

#Using hash look up table to make the complexity to O(n+m)
from random import randint

def main():

    list_1 = [randint(0,20) for r in range(randint(10,20))]
    list_2 = [randint(0,20) for r in range(randint(10,20))]
    result = []
    D = {}
    for num in list_1:
        if num not in D:
            D[num] = ''
    for num in list_2:
        if (num in D) and (D[num] == ''):
            result.append(num)
            D[num] = ' '

    list_1.sort() #sort for human to check for mistake(O(nlogn)
    list_2.sort()
    result.sort()

    print('List 1: {}'.format(list_1))
    print('List 2: {}'.format(list_2))
    print('Result: {}'.format(result))

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
import math

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib import messages
# Create your views here.
from django.urls import reverse_lazy

from create_profile.forms import CreateFormsB
from create_profile.models import CreateNeighbour, CreateBusiness, LikeModel, LikeBusinesModel, AllCities#, \
    #Profession  # , LikeEndModelNe

def index(request):
    # Главная
    if request.user.is_authenticated:

        # при авторизации сообщение пользоваиелям у кого встречные лайки соседей
        all_likes = LikeModel.objects.filter(like_second=request.user).values('like_first')
        for all_likes_s in all_likes:
            # print('all_likes-Neighb')
            # print(all_likes)
            step_one = []
            step_two = []
            if len(all_likes) > 0:
                # print('шаг1 нашел')
                step_one = all_likes_s
                # шаг 2
                all_likes_two = LikeModel.objects.filter(like_first=request.user).values('like_second')
                if len(all_likes_two) > 0:
                    # print('шаг 2 нашел')
                    # print(all_likes_two)
                    step_two = all_likes_two
                    # ii = int(0)
                    # print('step_one :', step_one)
                    # print('step_two :', step_two)
                    for step_two_s in step_two:
                        if step_two_s['like_second'] == step_one['like_first']:

                            messages.success(request, 'Вас лайкнул пользователь: ' + step_two_s['like_second'])
                            email_second = LikeModel.objects.filter(like_second=step_two_s['like_second']).values('email_second')
                            messages.success(request, ' Напишите ему: ' + email_second[0]['email_second'])

        all_likes_b = LikeBusinesModel.objects.filter(like_second=request.user).values()
        for all_likes_s_b in all_likes_b:
            step_one_b = []
            step_two_b = []
            if len(all_likes_b) > 0:
                if len(all_likes_b) > 0:
                    step_one_b = all_likes_s_b
                    all_likes_b_two = LikeBusinesModel.objects.filter(like_first=request.user).values('like_second')
                    if len(all_likes_b_two) > 0:
                        step_two_b = all_likes_b_two

                        for all_likes_s_b_s in step_two_b:
                            if all_likes_s_b_s['like_second'] == step_one_b['like_first']:
                                messages.success(request, 'Вас лайкнул бизнес пользователь: ' + all_likes_s_b_s['like_second'])
                                email_second_b = LikeBusinesModel.objects.filter(like_second=all_likes_s_b_s['like_second']).values('email_second')
                                messages.success(request, 'Почта для связи: ' + email_second_b[0]['email_second'])

        return render(request, 'index.html',)
    else:
        return render(request, 'index.html', )

@login_required(login_url=reverse_lazy('login'))
def all_filter_search(request):
    # выводим все анкеты
    list_tmp_13 = 0

    allCities = AllCities.objects.all()
    catalog_filter = CreateNeighbour.objects.values_list('id',
                                                          'name',
                                                          'gender',
                                                          'gender_neighb',
                                                          # 'sel_city',
                                                          # 'sel_distr',
                                                          'presence_animals',
                                                          'presence_flat',
                                                          'attitude_animals',
                                                          'attitude_smok',
                                                          'about_me',
                                                          'image',
                                                          'user_neig',
                                                          'cities',
                                                          'regin',)

    tmp_append_goods = []
    tmp_categ_name = []
    tmp_categ_name_list = []
    # формируем масив лдя прорисовки в шблоне
    for all_goods_s in catalog_filter:
        tmp_append_goods.append(all_goods_s)
        for tmp_s in tmp_append_goods:

            p = CreateNeighbour(gender=tmp_s[2])
            gender = p.get_gender_display()

            p = CreateNeighbour(gender_neighb=tmp_s[3])
            gender_neighb = p.get_gender_neighb_display()

            # p = CreateNeighbour(sel_city=tmp_s[4])
            # sel_city = p.get_sel_city_display()
            #
            # p = CreateNeighbour(sel_distr=tmp_s[5])
            # sel_distr = p.get_sel_distr_display()

            p = CreateNeighbour(attitude_animals=tmp_s[6])
            attitude_animals = p.get_attitude_animals_display()

            p = CreateNeighbour(attitude_smok=tmp_s[7])
            attitude_smok = p.get_attitude_smok_display()

            cities_name = AllCities.objects.filter(name=tmp_s[11]).values('name')
            distr_name = AllCities.objects.filter(name=tmp_s[12]).values('name')
            # cities_b = p.get_cities_b_display()
            # print('allCities_name')
            #
            # print(cities_name[0]['name'])
            # print(distr_name[0]['name'])

            list_tmp = list(tmp_s)
            list_tmp[2] = gender
            list_tmp[3] = gender_neighb
            # list_tmp[4] = sel_city
            # list_tmp[5] = sel_distr
            list_tmp[6] = attitude_animals
            list_tmp[7] = attitude_smok

            list_tmp[11] = cities_name[0]['name']
            list_tmp[12] = distr_name[0]['name']
            user_like = LikeModel.objects.filter(first_id=tmp_s[10]).filter(second_id=request.user.id).values_list('id') # лайки в шаблоне
            flag = 0
            if len(user_like) > 0:
                flag = '1'
            else:
                flag = '0'
            list_tmp.append(flag)
            list_tmp = tuple(list_tmp)

            for list_tmp_s in [list_tmp]:
                tmp_categ_name_list = list_tmp_s
        tmp_categ_name.append(tmp_categ_name_list) # формируем массив со всеми анкетами
        # print('allCities')
        # print(allCities)

    return render(request, 'all_neighb.html', {'serxh_filer': tmp_categ_name, 'allCities': allCities,})

@login_required(login_url=reverse_lazy('login'))
def all_busines(request):
    # весь бизнес
    # формируем массив со всеми анкетами
    distinr = CreateBusiness.objects.order_by('category_bus').values('category_bus').distinct()
    print('distin254')
    print(distinr)
    allCities = AllCities.objects.all()
    form = CreateFormsB()
    search_filer = CreateBusiness.objects.values_list('name_bus',
                                                       # 'sel_city',
                                                       # 'sel_distr',
                                                       'category_bus',
                                                       'about_me',
                                                       'image',
                                                       'user_bus',
                                                       'id',
                                                       'cities',
                                                       'regin',)

    tmp_append_goods = []
    tmp_categ_name = []
    tmp_categ_name_list = []
    for all_goods_s in search_filer:
        tmp_append_goods.append(all_goods_s)
        for tmp_s in tmp_append_goods:

            # p = CreateBusiness(sel_city=tmp_s[1])
            # sel_city = p.get_sel_city_display()
            #
            # p = CreateBusiness(sel_distr=tmp_s[2])
            # sel_distr = p.get_sel_distr_display()

            # cities_name_b = AllCities.objects.filter(id=tmp_s[8]).values('name')
            # distr_name_b = AllCities.objects.filter(id=tmp_s[9]).values('name')
            # search_filer_pro = Profession.objects.filter(id=tmp_s[10]).values('name')
            # cities_b = p.get_cities_b_display()
            # print('search_filer_pro')
            # print(search_filer_pro[0]['name'])
            list_tmp = list(tmp_s)
            # list_tmp[1] = sel_city
            # list_tmp[2] = sel_distr
            # list_tmp[8] = cities_name_b[0]['name']
            # list_tmp[9] = distr_name_b[0]['name']
            # list_tmp[10] = search_filer_pro[0]['name']
            # list_tmp[11] = search_filer_pro[0]['name']
            # лайки
            user_like = LikeBusinesModel.objects.filter(first_id=tmp_s[4]).filter(second_id=request.user.id).values_list('id')
            flag = 0
            if len(user_like) > 0:
                flag = '1'
            else:
                flag = '0'
            list_tmp.append(flag)
            list_tmp = tuple(list_tmp)
            for list_tmp_s in [list_tmp]:
                tmp_categ_name_list = list_tmp_s

            # AllCities.cities_b.all()
        tmp_categ_name.append(tmp_categ_name_list)# формируем массив со всеми анкетами

    return render(request, 'all_busines.html', {'serxh_filer': tmp_categ_name, 'allCities': allCities, 'form': form, 'distinr': distinr})

def likes(request):
    # likes заносим в таблицу лайкующего и хозяйна анкеты
    test_user = User.objects.filter(id=request.POST.get('first')).values('username', 'email')
    nearly_final = LikeModel(like_first=test_user[0]['username'], email_first=test_user[0]['email'],
                             like_second=request.POST.get('second'), email_second=request.POST.get('email'),
                             first_id=request.POST.get('first'), second_id=request.POST.get('second_id'),
                             id_ancket=request.POST.get('id_ancket'),)
    nearly_final.save(force_insert=True)
    return redirect('/all_neighb/')

def likes_busines(request):
    # likes заносим в таблицу лайкующего и хозяйна анкеты
    test_user = User.objects.filter(id=request.POST.get('first')).values('username', 'email')
    nearly_final = LikeBusinesModel(like_first=test_user[0]['username'], email_first=test_user[0]['email'],
                                    like_second=request.POST.get('second'), email_second=request.POST.get('email'),
                                    first_id=request.POST.get('first'), second_id=request.POST.get('second_id'),
                                    id_ancket=request.POST.get('id_ancket'),)
    nearly_final.save(force_insert=True)
    return redirect('/all_busines/')

def statistics(request):
    # статистика

    count_us = User.objects.values('username', 'email')

    count_users = (len(count_us))
    all_likes = LikeModel.objects.values()
    count_stat = len(all_likes)/2
    all_likes_n = math.ceil(count_stat)
    all_likes_b = LikeBusinesModel.objects.values()
    count_stat = len(all_likes_b)/2
    all_likes_bus = math.ceil(count_stat)
    # for count_us_s in count_us:
    print(count_us[0]['username'])
    tmp =count_us[0]['username']
    all_likes_count = LikeModel.objects.filter(like_second=count_us[0]['username']).count()
    all_likes_count_two = LikeModel.objects.filter(like_first=count_us[0]['username']).count()

    if all_likes_count > 0 and all_likes_count_two > 0:
        # print('tmp')
        # print(tmp)
        all_likes_count_two_two = LikeModel.objects.filter(like_first=count_us[0]['username']).values()
        # print('all_likes_count_two_two ')
        # print(all_likes_count_two_two[0]['like_first'])
        # save_end_like = LikeEndModelNe(like_first=all_likes_count_two_two[0]['like_first'],
        #                                email_first=all_likes_count_two_two[0]['email_first'],
        #                                like_second=all_likes_count_two_two[0]['like_second'],
        #                                email_second=all_likes_count_two_two[0]['email_second'],)
        # print('save_end_like')
        # print(save_end_like)
        # save_end_like.save()
        # print(all_likes_count, all_likes_count_two)

    return render(request, 'statistics.html', {'count_users':count_users, 'all_likes_n': all_likes_n, 'all_likes_bus': all_likes_bus})

def tree_form(request):
    # по айди города получаем районы
    dict1 = {}
    # print(request.GET.get('id'))
    city_id = request.GET.get('id')
    all_child = AllCities.objects.filter(parent_id=city_id).values('name', 'id')
    # print('all_child')
    # print(all_child)
    dict1['data']=list(all_child)# словарь в словаре для передачи json
    # print('dict1')
    # print(dict1)
    return JsonResponse(dict1)

def tree_form_b(request):
    dict2 = {}
    print(request.GET.get('id'))
    city_id = request.GET.get('id')
    all_child = AllCities.objects.filter(parent_id=city_id).values('name', 'id')
    print('all_child_b-450')
    print(all_child)
    # return HttpResponse('1')

    dict2['data']=list(all_child)
    print('dict1_b-456')
    print(dict2)
    # return JsonResponse({'all_child': all_child, 'status': 'ok', 'dict1': dict1})
    return JsonResponse(dict2)
    # return HttpResponse({'all_child': all_child,})

def search_fetch(request):
    # по айди города, района и пол соседа получаем анкты
    print('distr-461')
    print(request.GET.get('id'))

    print('seacrprof464')
    print(request.GET.get('distr'))
    print(request.GET)
    cities_name = AllCities.objects.filter(id=request.GET.get('id')).values('name')
    distr_name = AllCities.objects.filter(id=request.GET.get('distr')).values('name')
    catalog_filter=CreateNeighbour.objects.filter(cities=cities_name[0]['name'],
                                                  regin=distr_name[0]['name'],
                                                  gender=request.GET.get('ender')).\
                                                                values_list('id',
                                                                             'name',
                                                                             'gender',
                                                                             'gender_neighb',
                                                                             # 'sel_city',
                                                                             # 'sel_distr',
                                                                             'presence_animals',
                                                                             'presence_flat',
                                                                             'attitude_animals',
                                                                             'attitude_smok',
                                                                             'about_me',
                                                                             'image',
                                                                             'user_neig',
                                                                             'cities',
                                                                             'regin',)
    print('catalog_filter')
    print(catalog_filter)
    tmp_append_goods = []
    tmp_categ_name = []
    tmp_categ_name_list = []
    # формируем масив лдя прорисовки в шблоне
    for all_goods_s in catalog_filter:
        tmp_append_goods.append(all_goods_s)
        for tmp_s in tmp_append_goods:

            p = CreateNeighbour(gender=tmp_s[2])
            gender = p.get_gender_display()

            p = CreateNeighbour(gender_neighb=tmp_s[3])
            gender_neighb = p.get_gender_neighb_display()

            # p = CreateNeighbour(sel_city=tmp_s[4])
            # sel_city = p.get_sel_city_display()
            #
            # p = CreateNeighbour(sel_distr=tmp_s[5])
            # sel_distr = p.get_sel_distr_display()

            p = CreateNeighbour(attitude_animals=tmp_s[4])
            attitude_animals = p.get_attitude_animals_display()

            p = CreateNeighbour(attitude_smok=tmp_s[5])
            attitude_smok = p.get_attitude_smok_display()

            # cities_name = AllCities.objects.filter(id=tmp_s[11]).values('name')
            # distr_name = AllCities.objects.filter(id=tmp_s[12]).values('name')

            list_tmp = list(tmp_s)
            list_tmp[2] = gender
            list_tmp[3] = gender_neighb
            # list_tmp[4] = sel_city
            # list_tmp[5] = sel_distr
            list_tmp[4] = attitude_animals
            list_tmp[5] = attitude_smok

            list_tmp[11] = cities_name[0]['name']
            list_tmp[12] = distr_name[0]['name']
            user_like = LikeModel.objects.filter(first_id=tmp_s[10]).filter(second_id=request.user.id).values_list('id') # лайки в шаблоне
            flag = 0
            if len(user_like) > 0:
                flag = '1'
            else:
                flag = '0'
            list_tmp.append(flag)
            list_tmp = tuple(list_tmp)

            for list_tmp_s in [list_tmp]:
                tmp_categ_name_list = list_tmp_s
        tmp_categ_name.append(tmp_categ_name_list) # формируем массив со всеми анкетами
        print('allCities')
        print(tmp_categ_name)
    return render(request, 'filtr_neig.html', {'filter_ne':tmp_categ_name})
    # return JsonResponse(dict1)

def search_fetch_b(request):
    # dict1 = {}

    # filter_ne= CreateNeighbour.objects.filter(cities_id=request.GET.get('id')).values()
    # print('filter_ne')
    # print(filter_ne)
    print('distr-513')
    print(request.GET.get('id'))

    print('seacrprof546')
    print(request.GET.get('distr'))
    print('seacrprof-548')
    print(request.GET.get('prof'))
    # dict1['data']=list(filter_ne)
    allCities = AllCities.objects.all()
    # catalog_filter = CreateNeighbour.objects. \
    # catalog_filter=CreateNeighbour.objects.filter(cities_id=request.GET.get('id'),districts_tree=request.GET.get('distr'),gender=request.GET.get('ender')). \, category_bus=request.GET.get('prof'))\
    cities_name = AllCities.objects.filter(id=request.GET.get('id')).values('name')
    distr_name = AllCities.objects.filter(id=request.GET.get('distr')).values('name')
    search_filer = CreateBusiness.objects.filter(cities=cities_name[0]['name'],
                                                 regin=distr_name[0]['name'],
                                                 category_bus=request.GET.get('prof')).values_list('name_bus',
                                                                                # 'sel_city',
                                                                                # 'sel_distr',
                                                                                'category_bus',
                                                                                'about_me',
                                                                                'image',
                                                                                'user_bus',
                                                                                'id',
                                                                                'cities',
                                                                                'regin',)

    print('search_filer-561')
    print(search_filer)
    tmp_append_goods = []
    tmp_categ_name = []
    tmp_categ_name_list = []
    for all_goods_s in search_filer:
        tmp_append_goods.append(all_goods_s)
        for tmp_s in tmp_append_goods:

            # p = CreateBusiness(sel_city=tmp_s[1])
            # sel_city = p.get_sel_city_display()
            #
            # p = CreateBusiness(sel_distr=tmp_s[2])
            # sel_distr = p.get_sel_distr_display()

            list_tmp = list(tmp_s)
            # list_tmp[1] = sel_city
            # list_tmp[2] = sel_distr
            user_like = LikeBusinesModel.objects.filter(first_id=tmp_s[4]).filter(second_id=request.user.id).values_list('id')
            flag = 0
            if len(user_like) > 0:
                flag = '1'
            else:
                flag = '0'
            list_tmp.append(flag)
            list_tmp = tuple(list_tmp)
            for list_tmp_s in [list_tmp]:
                tmp_categ_name_list = list_tmp_s
        tmp_categ_name.append(tmp_categ_name_list)# формируем массив со всеми анкетами
        print('tmp_categ_name-598')
        print(tmp_categ_name)
    return render(request, 'test_busines.html', {'serxh_filer': tmp_categ_name})
    # return JsonResponse(dict1)


# -*- coding: utf-8 -*-
"""
Chapter 02 script 02
"""

import numpy as np
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
#should see 2.0.0 or higher1.0
print(keras.__version__)
#should see 2.2.4 – tf

# the four different states of the XOR gate
training_data = np.array([[0,0],[0,1],[1,0],[1,1]], "float32")

# the four expected results in the same order
target_data = np.array([[0],[1],[1],[0]], "float32")

model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[2]))
model.add(keras.layers.Dense(16, activation = 'sigmoid'))
model.add(keras.layers.Dense(16, activation = 'sigmoid'))
model.add(keras.layers.Dense(1, activation = 'sigmoid'))

model.summary()

model.layers

hidden1 = model.layers[1]
hidden1.name

model.get_layer('dense') is hidden1

weights, biases = hidden1.get_weights()
print(weights)
print(weights.shape)

weights.shape

biases

biases.shape

model.compile(loss='mean_squared_error', optimizer='adam', metrics=['binary_accuracy'])

history = model.fit(training_data, target_data, epochs=750, verbose=2)

import pandas as pd
import matplotlib.pyplot as plt

pd.DataFrame(history.history).plot(figsize=(8, 5))
plt.grid(True)
plt.gca().set_ylim(0, 1)
plt.show()

print(model.predict(training_data).round())


#!/usr/bin/env python3

__requires__ = '''
plover>=4.0.0.dev2
setuptools>=30.3.0
'''

from setuptools import setup

from plover_build_utils.setup import BuildPy, BuildUi

BuildPy.build_dependencies.append('build_ui')
BuildUi.hooks = ['plover_build_utils.pyqt:fix_icons']
cmdclass = {
    'build_py': BuildPy,
    'build_ui': BuildUi,
}

setup(cmdclass=cmdclass)


from PyQt4.QtGui import QApplication, QFrame, QPalette, QLabel, QPixmap
from PyQt4.QtCore import Qt, QRect, QCoreApplication

class BareFrame(QFrame):

    def __init__(self, parent=None):
        super(BareFrame, self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setFrameShadow(QFrame.Plain)
        self.setFrameShape(QFrame.Box)
        self.setLineWidth(1)

    def setBGColor(self, color):
        pal = QCoreApplication.instance().palette()
        pal.setColor(QPalette.Window, color)
        self.setPalette(pal)

class CloseMark(QLabel):

    WIDTH  = 31
    HEIGHT = 31
    MARGIN = 10

    def __init__(self, pixmap, parent=None):
        super(CloseMark, self).__init__(parent)
        self.setPixmap(pixmap)
        self.toParentTopRight()

    def mousePressEvent(self, event):
        self.parent().close()

    def toParentTopRight(self):
        parent = self.parent()
        x = parent.width() - CloseMark.MARGIN - CloseMark.WIDTH
        y = CloseMark.MARGIN
        w = CloseMark.WIDTH
        h = CloseMark.HEIGHT
        self.setGeometry(QRect(x, y, w, h))

class Dashboard(BareFrame):

    SCALE  = .85

    def __init__(self, parent=None):
        from camelot.view.controls.busy_widget import BusyWidget
        from camelot.view.model_thread import get_model_thread
        super(Dashboard, self).__init__(parent)
        desktop = QCoreApplication.instance().desktop()
        self.resize(desktop.width() * Dashboard.SCALE, desktop.height() * Dashboard.SCALE)
        self.closemark = CloseMark(QPixmap('close-mark.png'), self)
        self.setBGColor(Qt.white)
        busy_widget = BusyWidget(self)
        busy_widget.setMinimumSize( desktop.width() * Dashboard.SCALE, desktop.height() * Dashboard.SCALE )
        #self.addPermanentWidget(busy_widget, 0)
        mt = get_model_thread()
        mt.thread_busy_signal.connect( busy_widget.set_busy )
        busy_widget.set_busy(mt.busy())

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    board = Dashboard()
    board.show()
    sys.exit(app.exec_())