import json
from utils import is_name_in_list, find_by_name

USERFILE = 'users.json'
PRODUCTFILE = 'products.json'

def read_json(filename):
    """
        Читает json из filename и возвращает структуру данных
        @param {str} filename
        @return {json}
    """
    with open(filename, 'r') as jsonfile:
        content = jsonfile.read()
        return json.loads(content)

def write_json(filename, struct):
    """
        Записывает json в filename из struct
        @param {str} filename
        @param {object} struct
    """
    with open(filename, 'w+') as jsonfile:
        content = json.dumps(struct)
        jsonfile.write(content)

def update_json_list(filename, dict):
    struct = read_json(filename)

    if type(struct) != list:
        raise Exception('{0} is not a list'.format(filename))

    struct.append(dict)
    write_json(filename, struct)

def add_user(user):
    struct = read_json(USERFILE)
    name_of_list = user.kind + 's'
    list_of_users = struct.get(name_of_list, [])

    if is_name_in_list(user.name, list_of_users):
        raise Exception('User: {0.name} have been already added'.format(customer))

    list_of_users.append(user.value())
    struct[name_of_list] = list_of_users

    write_json(USERFILE, struct)

def update_product(product, add=False):
    products = read_json(PRODUCTFILE)

    if is_name_in_list(product.name, products):
        i = 0
        while i < len(products):
            p = products[i]
            if p['name'] == product.name:
                if add:
                    print(product)
                    new_qty = p.get('quantity', 1) + product.quantity
                else:
                    new_qty = p.get('quantity', 1) - product.quantity
                updated = products[i]
                updated['quantity'] = new_qty
                products[i] = updated
                break
            i += 1
    else:
        products.append(product.value())

    write_json(PRODUCTFILE, products)

def update_customer(customer):
    users = read_json(USERFILE)
    customers = users.get('customers', [])

    index = 0
    while index < len(customers):
        c = customers[index]
        if c.get('name') == customer.get('name'):
            customers[index] = customer
            break
        index += 1
    users['customers'] = customers

    write_json(USERFILE, users)


import os
import cv2
import face_recognition
import numpy as np

# Create a list to store known faces
known_faces = []

# Create a list to store the names of the known faces
known_face_names = []

# Loop through the folders in the dataset directory
for folder in os.listdir("dataset"):
    #Check if folder var is the .DS_Store file and ignore it
    if folder == ".DS_Store": continue

    # Get the path to the current folder
    folder_path = os.path.join("dataset", folder)

    # Get the name of the current folder (which is the name of the person)
    name = folder

    # Loop through the images in the current folder
    for file in os.listdir(folder_path):
        # Get the path to the current image
        image_path = os.path.join(folder_path, file)

        # Load the current image
        image = cv2.imread(image_path)

        # Get the face encodings for the current image
        face_encodings = face_recognition.face_encodings(image)

        # If a face is detected in the current image
        if len(face_encodings) > 0:
            # Add the face encoding to the list of known faces
            known_faces.append(face_encodings[0])

            # Add the name of the person to the list of known face names
            known_face_names.append(name)

# Load the input image
input_image = cv2.imread("input.jpg")

# Get the face encodings for the input image
face_encodings = face_recognition.face_encodings(input_image)

# If a face is detected in the input image
if len(face_encodings) > 0:
    # Compare the input face encoding with the known faces
    distances = face_recognition.face_distance(known_faces, face_encodings[0])

    #Find the index of the best match in distances
    best_match_index = np.argmin(distances)

    #If match is below tolerance threshold, print name of person
    if distances[best_match_index] <= 0.6:
        print("Match found:", known_face_names[best_match_index])
    else:
        print("No match found")

else:
    print("No face detected in the input image")


# 모양 만들기
import sys
from collections import deque

# 데이터 입력
n, m = map(int, sys.stdin.readline().split(' '))
matrix = [list(map(int, sys.stdin.readline().split(' '))) for _ in range(n)]

# 방문 정보 ([방문 여부, 구역 번호])
visited = [[[False, 0] for _ in range(m)] for _ in range(n)]

# 상, 우, 하, 좌 (시계방향)
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

# bfs (해당 구역의 크기를 구함)
def bfs(x, y, div_number):
  queue = deque()
  queue.append((x, y))
  visited[x][y] = [True, div_number]
  div_length = 1
  while(queue):
    visit_x, visit_y = queue.popleft()
    for p in range(4):
      if visit_x + dx[p] != -1 and visit_x + dx[p] < n and visit_y + dy[p] != -1 and visit_y + dy[p] < m:
        if not visited[visit_x + dx[p]][visit_y + dy[p]][0] and matrix[visit_x + dx[p]][visit_y + dy[p]] == 1:
          div_length += 1
          matrix[visit_x + dx[p]][visit_y + dy[p]] = div_length
          visited[visit_x + dx[p]][visit_y + dy[p]] = [True, div_number]
          queue.append((visit_x + dx[p], visit_y + dy[p]))
  return div_length

div_number = 1 # 구역 번호
div_length_list = {} # 구역별 크기 모음
# 구역별 크기를 구함
for i in range(n):
  for j in range(m):
    if matrix[i][j] == 1:
        div_length = bfs(i, j, div_number)
        div_length_list[div_number] = div_length
        div_number += 1

'''
  0인 곳에서 상하좌우로 방문하지 않은 구역이 존재하는지 확인 후
  방문하지 않은 구역의 크기를 더해 구역의 최대 크기를 구함
'''
result = 0 # 결과 값
for i in range(n):
  for j in range(m):
    if matrix[i][j] == 0:
      div_max_length = 1 # 구역의 최대 크기
      visited_div = [] # 방문한 구역
      for p in range(4):
        if i + dx[p] != -1 and i + dx[p] < n and j + dy[p] != -1 and j + dy[p] < m:
          if visited[i + dx[p]][j + dy[p]][1] not in visited_div and (visited[i + dx[p]][j + dy[p]][1] != 0):
            visited_div.append(visited[i + dx[p]][j + dy[p]][1]) # 해당 구역 방문 처리
            div_max_length += div_length_list[visited[i + dx[p]][j + dy[p]][1]] # 해당 구역의 크기를 최대 크기에 더함
      if div_max_length > result:
        result = div_max_length
print(result)


import torch
from torch.autograd import Variable

p = Variable(torch.DoubleTensor([0.59]), requires_grad=True)
k = 3
n = 5

# 伯努利概率P(5,3)
def f():
    return -3 * p.log() - 2 * (1 - p).log()

# for i in range(10000):
last_p = None
while True:
    y = f()
    y.backward()
    if last_p is not None and y.data[0] >= last_p:
        break
    last_p = y.data[0]
    p.data.sub_(1e-6 * p.grad.data[0])
    p.grad.data.zero_()
    p.data.clamp(min=0.0, max=1.0)

print(p.data[0])


from django.urls import path

from . import views

urlpatterns = [
     # Quiz lists
     path('', views.QuizList.as_view(), name="home"),
     path('most-viewed/', views.QuizListMostViewed.as_view(),
          name="most-viewed"),
     path('most-liked/', views.QuizListMostLiked.as_view(), name="most-liked"),
     path('user-quizzes/', views.QuizUserList.as_view(), name="user-quizzes"),

     # Quiz detail
     path('quiz/<slug:slug>/', views.QuizDetail.as_view(), name="quiz-detail"),

     # Quiz passing
     path(
          'quiz/<slug:slug>/passing/',
          views.QuestionList.as_view(
               template_name='quizapp/question_list.html',
               paginate_by=1
          ),
          name="question-list"
     ),
     path(
          'quiz/<slug:slug>/complete/',
          views.QuizComplete.as_view(),
          name="quiz-complete"
     ),

     # Manage questions
     path(
          'quiz/<slug:slug>/manage-questions/',
          views.QuestionList.as_view(
               template_name='quizapp/questions_manage.html',
               paginate_by=15
          ),
          name="manage-questions"
     ),

     # Create and delete a quiz
     path('create/quiz/', views.QuizCreate.as_view(), name="quiz-create"),
     path(
          'update/quiz/<slug:slug>/',
          views.QuizUpdate.as_view(),
          name="quiz-update"
     ),
]


import io
import torch
import torch.nn
import torch.nn.functional as F
import torch.utils.data
import torch.utils.data.sampler

def l2(output_emb):
    norm = torch.norm(output_emb, p=2, dim=1, keepdim=True).detach()
    output_norm = output_emb / norm
    return output_norm

x1 = torch.ones((32, 8))
x2 = -torch.ones((32, 8))

x1 = l2(x1)
x2 = l2(x2)

distances = 1. - F.cosine_similarity(x1, x2, dim=1, eps=1e-20)

output = torch.ones((6, 8))
output[2:,:] = -output[2:,:]

distances_batch = []
batch_size = output.size(0)
for i in range(batch_size):

    x1 = output[i, :].expand(batch_size, -1)
    x2 = output # whole batch
    # bug DIM
    distances = 1. - F.cosine_similarity(x1, x2, dim=1, eps=1e-20) # -1 .. 1
    # dot product ROUNDING PROBLEM IF 1.0 , need to be 1.00001
    # result = 0 .. 2.0
    distances_batch.append(distances)

dists = torch.stack(distances_batch)
print(distances)


# -*- coding: utf-8 -*-
"""
Created on Mon Feb  1 11:54:52 2016

@author: Алексей
"""

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  1 10:13:41 2016

@author: Алексей
"""

import numpy as np
from sklearn.cross_validation import KFold, cross_val_score
from sklearn.neighbors import KNeighborsRegressor
from sklearn import datasets
from sklearn import preprocessing

ds = datasets.load_boston()

#выделяем признаки
X = preprocessing.scale(ds.data)
Y = ds.target

param = np.linspace(1,10,num=200,endpoint=True)

#разбиваем блоки выборки
kf = KFold(len(Y),n_folds=5,shuffle=True,random_state=42)
scores = []

for p in param:
    clf = KNeighborsRegressor(n_neighbors=5,weights='distance',metric='minkowski',p=p)
    score = cross_val_score(clf,X,Y,scoring='mean_squared_error',cv=kf)
    scores.append(np.mean(score))
    print(str(p)+' : '+str(np.mean(score)))

print('Max: '+str(np.max(scores)))


from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic import DetailView
from django_tables2 import SingleTableView

from dnsapp.models import \
    ReverseZone, DNSARecord, DNSCNAMERecord, DNSMXRecord, Zone
from dnsapp.models.name_server import validate_host_name
from dnsapp.tables import \
    DNSARecordTable, DNSCNAMERecordTable, DNSMXRecordTable, ZoneTable
from dnsapp.utils.digg_pagination import DiggPaginator

def ip_view(request, ip=None, error_message=None):
    remote_ip = request.META['REMOTE_ADDR']
    if not ip:
        ip = remote_ip
    context = {'ip': ip}

    # Display error messages
    if error_message:
        context['error_message'] = error_message

    # Need zones list in remote IP configuration
    if ip == remote_ip:
        context['zones'] = [z.zone for z in Zone.objects.exclude_reverse()]

    try:
        record = DNSARecord.objects.get(ip=ip)
        context['record'] = record
        context['record_revzone'] = record.rev_zone
    except DNSARecord.DoesNotExist:
        try:
            context['record_revzone'] = ReverseZone.objects.get_by_ip(ip)
        except ReverseZone.DoesNotExist:
            pass
    return render_to_response('dnsapp/ip.html', context,
                              context_instance=RequestContext(request))

def set_remote_name(request):
    """Change the domain name of the remote IP address"""
    remote_ip = request.META['REMOTE_ADDR']
    if 'host' not in request.POST or 'zone' not in request.POST:
        return ip_view(request, remote_ip)
    newhost = request.POST['host'].strip()
    if newhost:
        # Validate new host value
        try:
            validate_host_name(newhost)
        except ValidationError:
            return ip_view(request, remote_ip, u"Invalid host name")

        # Add or modify record
        try:
            record = DNSARecord.objects.get(ip=remote_ip)
        except DNSARecord.DoesNotExist:
            record = DNSARecord(ip=remote_ip)

        record.host = newhost
        try:
            record.zone = Zone.objects.get(zone=request.POST['zone'])
        except Zone.DoesNotExist as e:
            return ip_view(request, remote_ip, str(e))

        try:
            record.fill_missing()
            record.full_clean()
            record.save()
        except (ValidationError, IntegrityError) as e:
            return ip_view(request, remote_ip, str(e))
    else:
        # Delete record
        try:
            record = DNSARecord.objects.get(ip=remote_ip)
            record.delete()
        except DNSARecord.DoesNotExist:
            pass

    return HttpResponseRedirect(reverse('dnsapp.views.ip_view'))

class ARecordListView(SingleTableView):
    model = DNSARecord
    table_class = DNSARecordTable
    table_pagination = {'klass': DiggPaginator}

class CNAMERecordListView(SingleTableView):
    model = DNSCNAMERecord
    table_class = DNSCNAMERecordTable
    table_pagination = {'klass': DiggPaginator}

class MXRecordListView(SingleTableView):
    model = DNSMXRecord
    table_class = DNSMXRecordTable
    table_pagination = {'klass': DiggPaginator}

class ZoneListView(SingleTableView):
    model = Zone
    table_class = ZoneTable
    table_pagination = {'klass': DiggPaginator}

class ZoneDetailView(DetailView):
    model = Zone

    def get_context_data(self, **kwargs):
        context = super(ZoneDetailView, self).get_context_data(**kwargs)
        context['mx_records'] = DNSMXRecord.objects.filter(zone=self.object)
        return context


# in-class coding for Monday, April 4

with open("/Users/alfredarsenault/Documents/GitHub/Spring_2021/Spring_2021_projects/Spring_2023.csv","r") as infile:
    #read the first two header lines in the file and throw them away
    infile.readline()
    infile.readline()
    # now we get to the real data

    data = infile.readlines()  #reads the REST of the file into a list

    #check to see what we have by printing
    for i in range(len(data)):
        data[i] = data[i].split(',')  #if this is .tsv: change this to .split("\t")
        for j in range(3,9):
            data[i][j] = int(data[i][j])

        #insert a new column 6 that is the total of the 3 project scores
        data[i].insert(6, data[i][3] + data[i][4] + data[i][5])

        #insert a new column 10 that is the total of the 3 test scores
        data[i].insert(10, data[i][7] + data[i][8] + data[i][9])

        #now append a letter grade to the end of each row
        total_points = data[i][6] + data[i][10]
        if total_points >= 576:
            grade = "A"
        elif total_points >= 512:
            grade = "B"
        else:
            grade = "C"
        data[i].append(grade)
        print(data[i])

    #Now, let's find all the students who got an A
    for i in range(len(data)):
        if data[i][-1] == "A":
            print(data[i][1], data[i][0])

    #find all the students who got a "C" and print out a warning notice
    for i in range(len(data)):
        if data[i][-1] == "C":
            print (data[i][1], data[i][0], " we have notified the coach \n You need to improve this grade")

    #    print(data[i])

#now we're going to try writing a .csv file

with open("/Users/alfredarsenault/PycharmProjects/results.csv","w") as outfile:
    for i in range(len(data)):
        for j in range(3,11):
            data[i][j] = str(data[i][j])
        newstring = ",".join(data[i])
        outfile.write(newstring + "\n")


import socket
import threading
import queue
import time
import select

class Server(threading.Thread):
    def __init__(self, host, port):
        # Main thread
        super().__init__(daemon=True, target=self.listen)

        # Socket variables
        self.host = host
        self.port = port
        self.buffer_size = 2048
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Variables for processing connections
        self.message_queues = {}
        self.connection_list = []
        self.login_list = {}

        self.lock = threading.RLock()

        # Socket setup
        self.shutdown = False
        try:
            self.sock.bind((str(self.host), int(self.port)))
            self.sock.listen(10)
            self.sock.setblocking(False)
        except socket.error:
            self.shutdown = True

        self.start()

        # Main loop
        while not self.shutdown:
            message = input()
            if message == 'quit':
                for sock in self.connection_list:
                    sock.close()
                self.shutdown = True
                self.sock.close()

                # End of __init__()

    def listen(self):
        print('Initiated listener thread')
        while True:
            with self.lock:
                try:
                    connection, address = self.sock.accept()
                except socket.error:
                    time.sleep(0.05)
                    continue

            connection.setblocking(False)
            if connection not in self.connection_list:
                self.connection_list.append(connection)

            self.message_queues[connection] = queue.Queue()
            ClientThread(self, connection, address)

class ClientThread(threading.Thread):
    def __init__(self, master, sock, address):
        super().__init__(daemon=True, target=self.run)
        self.master = master
        self.socket = sock
        self.address = address
        self.buffer_size = 2048
        self.login = ''
        self.inputs = []
        self.outputs = []
        self.start()
        print('New thread started for connection from ' + str(self.address))

    # In run we don't need to use locks, because sockets are accessed linearly
    def run(self):
        self.inputs = [self.socket]
        self.outputs = [self.socket]
        shutdown = False
        while self.inputs:
            try:
                read, write, exceptional = select.select(self.inputs, self.outputs, self.inputs)
            except select.error:
                self.client_disconnected()
                break

            if self.socket in read:
                try:
                    data = self.socket.recv(self.buffer_size)
                except socket.error:
                    if self.socket in self.inputs:
                        self.inputs.remove(self.socket)
                    if self.socket in self.outputs:
                        self.outputs.remove(self.socket)
                    self.client_disconnected()
                    break

                if data:
                    message = data.decode('utf-8')
                    message = message.split(';', 3)

                    # Processing data
                    # 1) new user logged in
                    if message[0] == 'login':
                        tmp_login = message[1]
                        while message[1] in self.master.login_list:
                            message[1] += '#'
                        if tmp_login != message[1]:
                            prompt = 'msg;server;' + message[1] + ';Login ' + tmp_login \
                                     + ' already in use. Your login changed to ' + message[1] + '\n'
                            self.master.message_queues[self.socket].put(prompt.encode('utf-8'))

                        self.login = message[1]
                        self.master.login_list[message[1]] = self.socket
                        print(message[1] + ' has logged in')

                        # Update list of active users, send it to clients
                        self.update_login_list()

                    # 2) user logged out
                    elif message[0] == 'logout':
                        print(message[1] + ' has logged out')

                        self.inputs.remove(self.socket)
                        self.outputs.remove(self.socket)
                        del self.master.message_queues[self.socket]
                        del self.master.login_list[self.login]
                        self.socket.close()
                        self.update_login_list()
                        break

                    # 3) Message from one user to another (msg;origin;target;message)
                    elif message[0] == 'msg' and message[2] != 'ALL':
                        msg = data.decode('utf-8') + '\n'
                        data = msg.encode('utf-8')
                        target = self.master.login_list[message[2]]
                        self.master.message_queues[target].put(data)

                    # 4) Message from one user to all users (msg;origin;all;message)
                    elif message[0] == 'msg':
                        msg = data.decode('utf-8') + '\n'
                        data = msg.encode('utf-8')
                        for connection, connection_queue in self.master.message_queues.items():
                            if connection != self.socket:
                                connection_queue.put(data)

                # Empty result in socket ready to be read from == closed connection
                elif not shutdown:
                    if self.socket in self.inputs:
                        self.inputs.remove(self.socket)
                    if self.socket in self.outputs:
                        self.outputs.remove(self.socket)
                    self.client_disconnected()
                    break

            if self.socket in write:
                if self.socket in self.master.message_queues:
                    if not self.master.message_queues[self.socket].empty():
                        data = self.master.message_queues[self.socket].get()
                        try:
                            self.socket.send(data)
                        except socket.error:
                            if self.socket in self.inputs:
                                self.inputs.remove(self.socket)
                            if self.socket in self.outputs:
                                self.outputs.remove(self.socket)
                            self.client_disconnected()
                            break

            if self.socket in exceptional:
                if self.socket in self.inputs:
                    self.inputs.remove(self.socket)
                if self.socket in self.outputs:
                    self.outputs.remove(self.socket)
                self.client_disconnected()

        # If exited from main run loop
        print('Closing client thread, connection' + str(self.address))

    def update_login_list(self):
        logins = 'login'
        for login in self.master.login_list:
            logins += ';' + login
        logins += ';ALL' + '\n'
        logins = logins.encode('utf-8')
        for connection, connection_queue in self.master.message_queues.items():
            connection_queue.put(logins)

    def client_disconnected(self):
        print(self.login + 'has disconnected.')
        if self.login in self.master.login_list:
            del self.master.login_list[self.login]
        if self.socket in self.master.connection_list:
            self.master.connection_list.remove(self.socket)
        if self.socket in self.master.message_queues:
            del self.master.message_queues[self.socket]
        self.socket.close()
        self.update_login_list()

# Create new server with (IP, port)
if __name__ == '__main__':
    server = Server('localhost', 8888)


import sys

sys.path.append('..')
sys.path.append('.')

import io
import numpy as np
import cv2
import torch
import base64
from io import BytesIO
import PIL

from models.viton import Viton, make_image
from models.keypoint import KeyPointPredictor
from models.segmentation import Segmentator
from models.posenet import DensePosePredictor
from models.segmentation import Segmentator
from network_utils.network_utils import CPDataset
from utils.utils import convert_image
from torchvision import transforms

from flask import Flask, jsonify, request
from scipy.ndimage.filters import gaussian_filter
from PIL import Image

app = Flask(__name__)

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

transform_1d = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])

def pipeline(img, cloth, cloth_mask):
    img_array = np.array(img)
    img_array = convert_image(img)
    img = Image.fromarray(convert_image(np.array(img)))
    img = transform(img)
    im_255 = cv2.resize(img_array, (255, 255), interpolation = cv2.INTER_AREA)
    dp = DensePosePredictor("./detectron2_repo/projects/DensePose/configs/densepose_rcnn_R_50_FPN_s1x.yaml",
                            "./checkpoint/densepose_rcnn_R_50_FPN_s1x.pkl")
    phead, body = dp.predict(im_255)
    body = cv2.resize(body, (192, 256), interpolation = cv2.INTER_AREA)
    body = Image.fromarray((body*255).astype(np.uint8))
    body = body.resize((192//16, 256//16), Image.BILINEAR)
    body = body.resize((192, 256), Image.BILINEAR)
    phead = cv2.resize(phead, (192, 256), interpolation = cv2.INTER_AREA)
    phead = torch.from_numpy(phead[np.newaxis,:,:])
    head = img * phead - (1 - phead)
    shape = transform_1d(body).type(torch.float32)

    key_model = KeyPointPredictor()
    pose_map, _ = key_model.predict(img_array)

    pose_map_corect = torch.zeros((18, 256, 192)) - 1
    pose_map_corect[0] = pose_map[0]
    pose_map_corect[1] = pose_map[17]
    pose_map_corect[2] = pose_map[6]
    pose_map_corect[3] = pose_map[8]
    pose_map_corect[4] = pose_map[10]
    pose_map_corect[5] = pose_map[5]
    pose_map_corect[6] = pose_map[7]
    pose_map_corect[7] = pose_map[9]
    pose_map_corect[8] = pose_map[12]
    pose_map_corect[11] = pose_map[11]
    pose_map_corect[14] = pose_map[2]
    pose_map_corect[15] = pose_map[1]
    pose_map_corect[16] = pose_map[4]
    pose_map_corect[17] = pose_map[3]
    pose_map = torch.tensor(pose_map_corect).type(torch.float32)

    viton = Viton(gmm_checkpoint_path='./checkpoint/gmm_train_new/gmm_final.pth',
                tom_checkpoint_path='./checkpoint/tom_train_new/tom_final.pth')
    shape = Image.open('./datasets/data/train/cloth/000003_1.jpg') # path to cloth
    shape = transform_1d(shape)
    res = viton.run_viton(head, pose_map, shape, cloth, cloth_mask)

    img_array[np.array(body) == -1] = 0
    cv2.imwrite("body.jpg", img_array)
    cv2.imwrite("body2.jpg", np.array(body))

    return encode((np.array(res[0].cpu().detach()).transpose(1, 2, 0) + 1) * 127.5)

def decode(byte64_str):
    bytes = BytesIO(base64.b64decode(byte64_str))
    pil_img = PIL.Image.open(bytes)
    return pil_img

def encode(img):
    pil_img = Image.fromarray(img.astype('uint8'))
    pil_img = pil_img.convert('RGB')
    buff = BytesIO()
    pil_img.save(buff, format="JPEG")
    return base64.b64encode(buff.getvalue()).decode("utf-8")

@app.route('/style/api/v1.0/segmentate', methods=['POST'])
def predict():
    if request.method == 'POST':
        file = request.values['file']
        cloth_id = int(request.values['cloth'])
        if cloth_id == 0:
            c = Image.open(
                '/home/tema/Projects/Course-work-3/datasets/viton_resize/train/cloth/000736_1.jpg')  # path to cloth
            c = transform(c)
            cm = Image.open(
                '/home/tema/Projects/Course-work-3/datasets/viton_resize/train/cloth-mask/000736_1.jpg')  # path to cloth-mask
            cm_array = np.array(cm)
            cm_array = (cm_array >= 128).astype(np.float32)
            cm = torch.from_numpy(cm_array)
            cm.unsqueeze_(0)

        img = decode(file)
        res = pipeline(img, c, cm)
    return encode(np.array(res[0].cpu().detach()).transpose(1,2,0) * 255)

if __name__ == '__main__':
    app.run(debug=True, port=5000)


import vcf
import os
import random
import argparse

parser = argparse.ArgumentParser(description = 'caculate heterozygous windows', add_help = False, usage = '\npython3 -i [input.vcf] -s [step and windows] -o [output.txt]')
required = parser.add_argument_group()
optional = parser.add_argument_group()
required.add_argument('-i', '--input', metavar = '[input_vcf]', help = 'input.vcf', required = True)
required.add_argument('-o', '--output', metavar = '[output]', help = 'output.txt', required = True)
required.add_argument('-s', '--step', metavar = '[step]', help = 'step',default=10000)
optional.add_argument('-h', '--help', action = 'help', help = 'help')
args = parser.parse_args()

samples_name=args.input[:-4]
#filter heterozygous
seed=random.randint(1,1000000)
vcf_reader0 = vcf.Reader(open(args.input, 'r'))
vcf_writer0 = vcf.Writer(open(args.input+str(seed)+'tmp.vcf', 'w'), vcf_reader0)
for record in vcf_reader0:
    gt=record.genotype(samples_name)['GT']
    if gt=='0|1' or gt=='1|0':
        vcf_writer0.write_record(record)
vcf_writer0.close()
#split chromosome

for i in range(1,10):
    vcf_reader1 = vcf.Reader(open(args.input+str(seed)+'tmp.vcf', 'r'))
    vcf_writer1 = vcf.Writer(open(args.input+str(seed)+'chr'+str(i)+'tmp.vcf', 'w'), vcf_reader1)
    for record in vcf_reader1:
        chr=record.CHROM
        gt=record.genotype(samples_name)['GT']
        #print(gt)
        if chr=='chr'+str(i) and gt=='0|1':
            vcf_writer1.write_record(record)
        if chr=='chr'+str(i) and gt=='1|0':
            vcf_writer1.write_record(record)
    vcf_writer1.close()

#caculate het
out=open(args.output,'w')
win=int(args.step)
step=int(args.step)
L=[32266151,33368013,41283659,32876879,48982865,27141800,31662302,30741539,30315542]
for i in range(1,10):
    for each in range(int((L[i-1])/step+1)):
        chr_test='chr'+str(i)
        start=each*step
        end=start+win
        #print(chr_test,start,end)
        count=0
        vcf_reader2 = vcf.Reader(open(args.input+str(seed)+'chr'+str(i)+'tmp.vcf', 'r'))
        for record in vcf_reader2:
            #print(record)
            chr=record.CHROM
            pos=int(record.POS)
            gt=record.genotype(samples_name)['GT']
            #print(pos)
            if not chr==chr_test:
                pass
            elif chr==chr_test and pos<start:
                pass
            elif chr==chr_test and pos>start and pos<end:
                if gt=='0|1' or gt=='1|0':
                    #print(record)
                    count+=1
            elif chr==chr_test and pos>end:
                break
        ll=chr_test+'\t'+str(start)+'\t'+str(end)+'\t'+str(count/step)+'\n'
        out.write(ll)
        #print(chr_test,start,end,count/10000)
out.close()

#delete tmp files
for i in range(1,10):
    pass
    cmd0='rm -f {}'.format(args.input+str(seed)+'tmp.vcf')
    cmd1='rm -f {}'.format(args.input+str(seed)+'chr'+str(i)+'tmp.vcf')
    os.system(cmd0)
    os.system(cmd1)


import numpy as np
import math as m
import cv2 as cv
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

from controllers import tracking_controller
from modules import image_module
from core import config
import glob
import time
import open3d as o3d

class Display:
    def __init__(self):
        self.W = 960
        self.H = 540

    def display_points2d(self, img, kpts, matches):
        if kpts != 0:
            for kpt in kpts:
                cv.circle(img, (int(kpt.pt[0]), int(kpt.pt[1])), radius=2, color=(0,255,0), thickness=-1)

        if matches != 0:
            for match in matches:
                (u1, v1) = np.int32(match[0].pt)
                (u2, v2) = np.int32(match[1].pt)
                cv.line(img, (u1, v1), (u2, v2), color=(0,0,255), thickness=1)
        return img

    def display_points3d(self, tripoints3d, pcd, visualizer):
        # open3d
        if tripoints3d is not None:
            pcd.clear()
            pcd.points = o3d.utility.Vector3dVector(tripoints3d)
            visualizer.remove_geometry(pcd)
            visualizer.add_geometry(pcd)
            visualizer.poll_events()
            visualizer.update_renderer()
            time.sleep(.2)

    def display_vid(self, img):
        cv.imshow("main", img)

class PointMap(object):
	def __init__(self):
		self.array = [0,0,0]

	def collect_points(self, tripoints):
		if len(tripoints) > 0:
			array_to_project = np.array([0,0,0])

			x_points = [pt for pt in tripoints[0]]
			y_points = [-pt for pt in tripoints[1]]
			z_points = [-pt for pt in tripoints[2]]

			for i in range(tripoints.shape[1]):
				curr_array = np.array([x_points[i], y_points[i], z_points[i]])
				array_to_project = np.vstack((array_to_project, curr_array))

			array_to_project = array_to_project[1:, :]

			return array_to_project

class TestingController:
    def __init__(self):
        self.orb = cv.ORB_create(nlevels=5, firstLevel=1, edgeThreshold=1,
                                  nfeatures=50, fastThreshold=config.FAST_THRESHOLD)
        self.BFMatcher = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=False)
        self.object_points = (0, 0, 0)
        # self._path = config.PROJECT_PATH + '/proyecto-modular/project/assets/video/calibracion.mp4'
        self.mtx = None
        self.dist = None

    def draw(self, img, corners, imgpts):
        corner = tuple(corners[0].ravel())
        img = cv.line(img, corner, tuple(imgpts[0].ravel()), (255, 0, 0), 5)
        img = cv.line(img, corner, tuple(imgpts[1].ravel()), (0, 255, 0), 5)
        img = cv.line(img, corner, tuple(imgpts[2].ravel()), (0, 0, 255), 5)
        return img

    def rotate(self, phi, theta, psi):
        phi = m.pi/2
        theta = m.pi/4
        psi = m.pi/2

        R = self.Rz(psi) * self.Ry(theta) * self.Rx(phi)
        return R

    def translate(self, x0, y0, z0, x1, y1, z1):
        difx = x1 - x0
        dify = y1 - y0
        difz = z1 - z0
        return np.array([x0 + difx, y0 + dify, z0 + difz])

    def run(self):
        #Obtenemos los keypoints del frame actual y el anterior
        kps_act, desc_act, img_act = self.obtenerKeypointsYDescriptors(2)
        kps_ant, desc_ant, img_ant = self.obtenerKeypointsYDescriptors(1)

        #Dibujamos los keypoints detectados
        img1 = cv.drawKeypoints(img_act, kps_act, 0, color=(0,255,0), flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
        img2 = cv.drawKeypoints(img_ant, kps_ant, 0, color=(0,255,0), flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # Mostramos las imagenes
        plt.imshow(img1)
        plt.show()
        plt.imshow(img2)
        plt.show()

        # Obtenemos los matches y filtramos los keypoints que necesitamos del frame actual y el anterior
        # recordando: query = actual; train = previo
        matches, matches_no_filtro = self.matchFeatures(desc_ant, desc_act)

        kp_xy_ant = []
        kp_xy_act = []
        for match in matches:
            kp_xy_ant.append(np.asarray(kps_ant[match[0].trainIdx].pt))
            kp_xy_act.append(np.asarray(kps_act[match[0].queryIdx].pt))

        kp_xy_ant = np.asarray(kp_xy_ant).T
        kp_xy_act = np.asarray(kp_xy_act).T

        plt.imshow(cv.drawMatchesKnn(img_ant,kps_ant,img_act,kps_act,matches,None))
        plt.show()

        # Angulos del dron euler
        R1 = self.rotate(0, 0, 0)
        # posiciones GPS (x, y, z) del dron
        T1 = self.translate(0, 0, 0, 0, 0, 0)

        R2 = self.rotate(0, 0, 0)
        T2 = self.translate(0, 0, 0, 10, 0, 0)

        projection_mtx1 = np.array(
            [[R1[0,0],R1[0,1],R1[0,2],T1[0]],
            [R1[1,0],R1[1,1],R1[1,2],T1[1]],
            [R1[2,0],R1[2,1],R1[2,2],T1[2]]]
        )
        projection_mtx2 = np.array(
            [[R2[0,0],R2[0,1],R2[0,2],T2[0]],
            [R2[1,0],R2[1,1],R2[1,2],T2[1]],
            [R2[2,0],R2[2,1],R2[2,2],T2[2]]]
        )

        # multiplicar por la intrinseca
        # self.K = np.array([[7.18856e+02, 0.0, 6.071928e+02],
        #                   [0.0, 7.18856e+02, 1.852157e+02],
        #                   [0.0, 0.0, 1.0]])
        # self.pp = np.array([self.K[0, 2], self.K[1, 2]])
        # self.focal = self.K[0, 0]

        points_in_4d = cv.triangulatePoints(
            projection_mtx1, projection_mtx2, kp_xy_ant, kp_xy_act)
        # Normalize points [x, y, z, 1]
        points_in_3d = points_in_4d / points_in_4d[3]

        # fig = plt.figure()
        # ax = fig.add_subplot(111, projection='3d')
        # # ax.scatter([p[0] for p in points_in_3d], [p[1] for p in points_in_3d], [p[2] for p in points_in_3d])
        # ax.scatter(points_in_3d[0], points_in_3d[1], points_in_3d[2])
        # # ax.scatter([item[0][0] for item in points_in_3d], [item[0][1]])

        print(points_in_3d)

        pmap = PointMap()
        display = Display()

        pcd = o3d.geometry.PointCloud()
        visualizer = o3d.visualization.Visualizer()
        visualizer.create_window(window_name="3D plot", width=960, height=540)

        xyz = pmap.collect_points(points_in_3d)

        display.display_points3d(xyz, pcd, visualizer)

    def Rx(self, theta):
        return np.matrix([[1, 0, 0],
                        [0, m.cos(theta), -m.sin(theta)],
                        [0, m.sin(theta), m.cos(theta)]])

    def Ry(self, theta):
        return np.matrix([[m.cos(theta), 0, m.sin(theta)],
                        [0, 1, 0],
                        [-m.sin(theta), 0, m.cos(theta)]])

    def Rz(self, theta):
        return np.matrix([[m.cos(theta), -m.sin(theta), 0],
                        [m.sin(theta), m.cos(theta), 0],
                        [0, 0, 1]])

    def obtenerKeypointsYDescriptors(self, numeroImagen):
        img = cv.imread(
            f"{config.PROJECT_PATH}/proyecto-modular/project/assets/photos/photo_mtrx{numeroImagen}.jpeg")
        img = image_module.resize_image(
            img, config.VIDEO_WITDH_RESIZE, config.VIDEO_HEIGHT_RESIZE)
        gray = image_module.process_image(img)

        # Find the chess board corners
        # _, kp = cv.findChessboardCorners(gray, (9, 6), None)
        kp, desc = self.orb.detectAndCompute(gray, None)
        return kp, desc, gray

    def matchFeatures(self, des_prev, desc_act):
        if des_prev is None or len(des_prev) < 2:
            return -1
        if desc_act is None or len(desc_act) < 2:
            return -1
        matches = self.BFMatcher.knnMatch(des_prev, desc_act, k=2)

        good_matches = []
        idx_of_des_from_f1, idx_of_des_from_f2 = [], []
        idx_set1, idx_set2 = set(), set()

        # for m, n in matches:
        #     if m.distance < 0.75 * n.distance:
        #         p1 = f1.kpus[m.queryIdx]
        #         p2 = f2.kpus[m.trainIdx]

        #         # ensure distance is within 32
        #         if m.distance < 32:
        #             if m.queryIdx not in idx_set1 and m.trainIdx not in idx_set2:
        #                 idx_of_des_from_f1.append(m.queryIdx)
        #                 idx_of_des_from_f2.append(m.trainIdx)
        #                 idx_set1.add(m.queryIdx)
        #                 idx_set2.add(m.trainIdx)

        #                 good_matches.append((p1, p2))

        # Apply ratio test
        goodMatches = []
        for m, n in matches:
            if m.distance < 0.70 * n.distance:
                goodMatches.append([m])
        return goodMatches, matches


score = [5,4,3,2,1]
t=sorted(score,reverse=True)
l=[]
for i in score:
       u=t.index(i)
       if u==0:
           l.append("Gold Medal")
       if u==1:
            l.append("Silver Medal")
       if u==2:
            l.append("Bronze Medal")
       if u>2:
            l.append(str(u+1))
print(l)


# Mapping class

import pandas as pd

class MAPPING():
  EXCELFILE = None
  EXCELFILE_NAME = ''
  EXCELFILE_DATA = None

  def __init__(self, excel_file_name="crazy_excel_mapping.xlsx"):
      self.EXCELFILE_NAME = excel_file_name
      self.EXCELFILE = pd.ExcelFile(self.EXCELFILE_NAME)
      self.EXCELFILE_DATA = self.getMappingList()

  def getMappingList(self):
      """Return mappings of subscriptionsname"""
      dfs = {sheet_name: self.EXCELFILE.parse(sheet_name) for sheet_name in self.EXCELFILE.sheet_names}
      ret = {'map_data':[]}
      array_1 = dfs['json_sub_info']['sub_short']
      array_2 = dfs['json_sub_info']['subscriptionname']
      array_3 = dfs['json_sub_info']['subscriptionid']

      length = len(array_1)
      # iterate of list with index
      # same as 'for i in range(len(list))'
      for i in range(length):
        ret_data = {'mic_sub_short': array_1[i], 'subscriptionname': array_2[i], 'subscriptionid': array_3[i]}
        ret['map_data'].append( ret_data )
      return ret

if __name__ == "__main__":
    qualys_mapping = MAPPING("crazy_excel_mapping.xlsx")
    foobar = qualys_mapping.getMappingList()
    #foobar['map_data']


import socket
import json

from miner import Miner

SOCKET_READ_LENGTH = 4096

class SgMiner(Miner):

    def _get_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:
            sock.connect((self._host, self._port))
        except:
            return { 'error': Miner.DOWN }

        return sock

    def _run_command(self, cmd, expect_multiple = False):
        payload = { 'command': cmd }

        sock = self._get_socket()

        if sock is None:
            return {}

        sock.send(
            json.dumps(payload)
        )

        try:
            resp = sock.recv(SOCKET_READ_LENGTH)

            while True:
                next_resp = sock.recv(SOCKET_READ_LENGTH)

                if not next_resp:
                    break
                else:
                    resp += next_resp
        except:
            return { 'error': Miner.BAD_RESPONSE }

        if expect_multiple:
            return json.loads(resp[:-1])[cmd.upper()]
        else:
            return json.loads(resp[:-1])[cmd.upper()][0]

    def host(self):
        host = self._run_command('version')

        if host.get('error'):
            return host

        return {
            'miner': host.get('Miner')
        }

    def config(self):
        config = self._run_command('config')

        if config.get('error'):
            return config

        return {
            'os': config.get('OS'),
            'pool_count': config.get('Pool Count'),
            'gpu_count': config.get('GPU Count')
        }

    def work_summary(self):
        summary = self._run_command('summary')

        if summary.get('error'):
            return summary

        return {
            'difficulty': summary.get('Difficulty Accepted'),
            'hash_rate_5s': summary.get('KHS 5s'),
            'hash_rate_avg': summary.get('KHS av'),
            'rejected_shares_percent': summary.get('Pool Rejected%'),
            'found_blocks': summary.get('Found Blocks'),
            'stale_shares_percent': summary.get('Pool Stale%'),
            'hardware_errors': summary.get('Hardware Errors'),
            'accepted_shares': summary.get('Accepted')
        }

    def gpus(self):
        devs_raw = self._run_command('devs',  expect_multiple = True)
        devs = []

        if devs_raw.get('error'):
            return devs_raw

        for dev in devs_raw:
            devs.append({
                'hash_rate_5s': dev.get('KHS 5s'),
                'temperature': dev.get('Temperature'),
                'clock_freq': dev.get('GPU Clock'),
                'status': dev.get('Status'),
                'fan_percent': dev.get('Fan Percent'),
                'accepted_shares': dev.get('Accepted'),
                'rejected_shares': dev.get('Rejected'),
                'raw_intensity': dev.get('RawIntensity')
            })

        return devs


from __future__ import unicode_literals

from django.db import migrations
from django.db import transaction
from devices.models import *;
from datetime import date, datetime
import os
import sys

@transaction.atomic
def insert_from_csv(apps, schema_editor):
    try:
        FILE_PATH = os.environ['DEVICE_FILE_PATH']
    except Exception:
        migrations_abs_path = os.path.dirname(os.path.realpath(__file__))
        FILE_PATH = '%s/devices.csv' % migrations_abs_path

    DeviceHistoric = apps.get_model("devices", "Device")
    ProjectHistoric = apps.get_model("devices", "Project")
    AssignmentHistoric = apps.get_model("devices", "Assignment")
    DeviceAssignmentHistoric = apps.get_model("devices", "DeviceAssignment")
    DeviceTypeHistoric = apps.get_model("devices", "DeviceType")
    DeviceBrandHistoric = apps.get_model("devices", "DeviceBrand")
    DeviceStatusHistoric = apps.get_model("devices", "DeviceStatus")

    FILE_COLUMNS = {'full_code': 0,
                    'device_type_name': 1,
                    'asset': 2,
                    'ownership': 3,
                    'serial_number': 4,
                    'device_type_code': 5,
                    'device_brand_name': 6,
                    'model': 7,
                    'purchase_date': 8,
                    'project_name': 9,
                    'device_status_name': 10,
                    'assignee': 11,
                    'assignment_date': 12,
                    'description': 16
                    }

    def has_lifetime(device_type):
        if device_type.life_time is None:
            return False
        return True

    def has_lifetime_and_life_has_not_begun(device):
        return has_lifetime(device.device_type) and device.life_start_date in (None, '')

    def assign(device, date=None):
        if has_lifetime_and_life_has_not_begun(device):
            device.life_start_date = date or datetime.date.today()

    def create_assignment(parts, device):
        project = ProjectHistoric.objects.get_or_create(name=get_column_value(parts, 'project_name').capitalize())[0]
        assignment_date = get_column_value(parts, 'assignment_date')
        if assignment_date not in (None, ''):
            assignment_date = datetime.strptime(assignment_date, "%m/%d/%Y").date()
        else:
            assignment_date = date.today()
        assignee_name = get_column_value(parts, 'assignee')
        assignment = AssignmentHistoric(assignee_name=assignee_name, project=project)
        assignment.save()

        assign(device, assignment_date)

        device.save()
        device_assignment = DeviceAssignmentHistoric(device=device, assignment=assignment, assignment_date=assignment_date)
        device_assignment.save()

    def is_code_device_valid(device):
        expected_code = device.generate_code()
        is_valid = expected_code == device.code
        return is_valid

    def print_log_device_does_not_migrate(device):
        sequence_with_format = '{0:04d}'.format(device.sequence)
        print('El dispositivo con código %s%s no se insertó, ya que su código %s debe ser %s' % (device.code, sequence_with_format, device.code, device.full_code()))

    def create_device(parts):
        device_data = {}
        full_code = get_column_value(parts, 'full_code')
        device_data['device_type'] = create_device_type(parts)
        device_data['device_brand'] = create_device_brand(parts)
        device_data['device_status'] = create_devices_status(parts)
        device_data['code'] = full_code[0:4]
        device_data['sequence'] = int(full_code[4:])
        device_data['asset'] = 1 if get_column_value(parts,'asset').lower() == 'si' else 0
        device_data['ownership'] = get_column_value(parts,'ownership').upper()
        device_data['serial_number'] = get_column_value(parts,'serial_number')
        device_data['description'] = get_column_value(parts,'description')

        if get_column_value(parts,'model') in (None, ''):
            device_data['model'] = device_data['serial_number']
        else:
            device_data['model'] = get_column_value(parts,'model')
        purchase_date = get_column_value(parts,'purchase_date')

        if purchase_date not in (None, ''):
            device_data['purchase_date'] = datetime.strptime(purchase_date, '%m/%d/%Y')
        device = DeviceHistoric(**device_data)

        return device

    def get_column_value(parts, name_column):
        return parts[FILE_COLUMNS[name_column]].strip()

    def create_device_type(parts):
        return DeviceTypeHistoric.objects.get_or_create(name=get_column_value(parts, 'device_type_name').capitalize(),
                                         code=get_column_value(parts, 'device_type_code').upper())[0]

    def create_device_brand(parts):
        return DeviceBrandHistoric.objects.get_or_create(name=get_column_value(parts, 'device_brand_name').capitalize())[0]

    def create_devices_status(parts):
        return DeviceStatusHistoric.objects.get_or_create(name=get_column_value(parts, 'device_status_name').capitalize())[0]

    def device_is_present(full_code):
        code = full_code[0:4]
        sequence = int(full_code[4:])
        device = DeviceHistoric.objects.filter(code=code, sequence=sequence)
        if device:
            print('El dispositivo con código %s no se insertó, ya está presente en la base de datos' % full_code)
            return True
        return False

    def parse_line(line):
        parts = line.split(",")
        full_code = get_column_value(parts,'full_code')
        if full_code in (None, '') or device_is_present(full_code):
            return
        device = create_device(parts)

        if device.device_status.name == DeviceStatus.ASIGNADO:
            create_assignment(parts, device)
        else:
            device.save()

    if 'test' in sys.argv:  # prevents running the migration when executing manage.py test
        return
    file = open(FILE_PATH, 'r')
    file.readline()
    for line in file:
        parse_line(line)
    file.close()

class Migration(migrations.Migration):

    dependencies = [
        ('devices', '0028_auto_20160608_2208'),
    ]
    operations = [
        migrations.RunPython(insert_from_csv),
    ]


from django import forms
from .models import Books

class Bookform(forms.ModelForm):

    class Meta:
        model = Books
        fields = ('title', 'author', 'date_published',
                  'number_of_pages', 'type_of_book')
        labels = {
            'date_published': 'Date Published (Format : yyyy-mm-dd)',
            'number_of_pages': 'Number of Pages',
            'type_of_book': 'Genres'
        }

    def __init__(self, *args, **kwargs):
        super(Bookform, self).__init__(*args, **kwargs)
        self.fields['type_of_book'].empty_label = 'Select'
        self.fields['date_published'].required = 'Select'


import numpy as np
import face_recognition as fr
import flask
import cv2

def facer(test_img):
    person = ""
    face_locations = []
    d = dict()
    d["name"] = person
    d["rect"] = face_locations
    encodings = np.load("newenc.npy")
    fl = fr.face_locations(test_img)
    if len(fl)>0:
        face_locations = fl[0]
        test_enc = fr.face_encodings(test_img)[0]

        for i in range(len(encodings)):
            result = fr.compare_faces([encodings[i,:].T], test_enc)
            if result[0] == True:
                if i == 0:
                    person = "Cayden P"
                    break
                elif i == 1:
                    person = "Jiten S"
                    break
                elif i == 3:
                    person = "Zhao Lu"
                    break
            else:
                person = ""

        d["name"] = person
        d["rect"] = face_locations

    return d

app = flask.Flask(__name__)

@app.route('/',methods=['GET','POST'])
def handle_request():
    imagefile = flask.request.files['image']
    image = np.asarray(bytearray(imagefile.read()),dtype=np.uint8)
    image = cv2.imdecode(image,cv2.IMREAD_COLOR)
    image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
    dic = facer(image)
    return dic

app.run(host="0.0.0.0",port=5000,debug=True)


import cv2

image = cv2.imread("entrada.jpg")

image[0, 0] = (255, 255, 0)
print(image[0,0])
print(image)

#CRIA UM RETANGULO AZUL DE ALTURA ENTRE 30 E 50 E POR TODA A LARGURA DA IMAGEM
image[30:50, :] = (255, 0, 0);#slicing -> altera vários pixels da imagem de uma vez só

#CRIA UM QUADRADO VERMELHO
image[100:150, 50:100] = (0, 0, 255)

#CRIA UMA RETANGULO AMARELO POR TODA A ALTURA DA IMAGEM
image[:, 200:220] = (0, 255, 255)

#CRIA UM RETANGULO VERDE DA LINHA 150 A 300 NAS COLUNAS 250 A 350
image[150:300, 250:350] = (0, 255, 0)

#CRIA UM QUADRADO CIANO DA LINHA 50 A 150 NAS COLUNAS 300 A 400
image[300:400, 50:150] = (255, 255, 0)

#CRIA UM QUADRADO BRANCO
image[250:350, 300:400] = (255, 255, 255)

#CRIA UM QUADRADO PRETO
image[70: 100, 300: 450] = (0,0,0)

cv2.imshow("Imagem alterada", image) #exibe a imagem após a execução do código acima com os retangulos coloridos incluídos pela técnica "slicing"
cv2.waitKey(0);
cv2.destroyAllWindows();


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.integrate import odeint, solve_ivp
from scipy import optimize
from mpl_toolkits.mplot3d import Axes3D

r = 1
x0 = 0
y0 = 2
tt = np.linspace(0, 70, 1000)
xx = np.linspace(-5, 5, 100)

def dxdt(t, x, r):
    return r-x**2

def dydt(t, y, r):
    return -4*y

def dSdt(t, S, epsilon, a):
    x, y = S
    return [
        y + a*x**2 - x**3,
        epsilon
    ]

sol = solve_ivp(
    dxdt, t_span=[min(tt), max(tt)],
    y0=[x0], t_eval=tt, args=(r,)
)

sol_y = solve_ivp(
    dydt, t_span=[min(tt), max(tt)],
    y0=[y0], t_eval=tt, args=(r,)
)

fig, axs = plt.subplots(3)
# Plot solutions to ode's
sol_plot = axs[0].plot(sol.t, sol.y[0, :], color='b', label='x(t)')
axs[0].plot(sol_y.t, sol_y.y[0, :], color='orange', label='y(t)')
axs[0].set_xlabel('time')
axs[0].set_ylabel(r'x', rotation=0)
axs[0].set_xlim([0, 2])
axs[0].set_ylim([-2, 2])
axs[0].grid()
axs[0].legend()

# Plot phase space of derivatives
phase_space = axs[1].plot(xx, dxdt(sol.t,xx,r), color='b', label='x')
axs[1].plot(xx, dydt(sol_y.t,xx,r), color='orange', label='y')
scat = axs[1].scatter([], [], c='black')

axs[1].grid()
axs[1].set_xlabel('x')
axs[1].set_ylabel(r'$\dot{x}$', rotation=0)
axs[1].set_ylim([-1.1,1.1])
axs[1].legend()

# Streamlines of X - Y space
w = 5
Y, X = np.mgrid[-w:w:1000j, -w:w:1000j]
U = dxdt(tt, X, r)
V = dydt(tt, Y, r)
stream = axs[2].streamplot(X, Y, U, V, density = 1)
axs[2].set_ylim([-1, 1])
axs[2].set_xlim([-1*w, w])
left_atractor_line = axs[2].axvline(-1*r, c='black', ls='--')
right_atractor_line = axs[2].axvline(r, c='black', ls='--')
axs[2].axhline(0, c='black')
left_atractor_scat = axs[2].scatter((-1 * r),0, facecolors='none', edgecolors='black')
right_atractor_scat = axs[2].scatter(r,0, c='black')
axs[2].set_aspect('equal', adjustable='box')

tot_frames = 40
def update(frame):

    delta = frame * (2.0 / (tot_frames))
    new_r = (r - delta)**3

    updated_sol = solve_ivp(
        dxdt, t_span=[min(tt), max(tt)],
        y0=[x0], t_eval=tt, args=(new_r,)
    )

    sol_plot[0].set_xdata(updated_sol.t)
    sol_plot[0].set_ydata(updated_sol.y[0, :])

    phase_space[0].set_ydata(dxdt(updated_sol.t,xx,new_r))

    U = dxdt(tt, X, new_r)
    V = dydt(tt, Y, new_r)
    axs[2].collections = [] # clear lines streamplot
    axs[2].patches = [] # clear arrowheads streamplot
    axs[2].streamplot(X, Y, U, V, color='blue', arrowsize=2, density=1)
    axs[2].axhline(0, c='black')

    if 0 <= new_r:
        sqrt_r = np.sqrt(new_r)
        scat.set_offsets([[sqrt_r,0], [(-1 * sqrt_r),0]])

        left_atractor_line.set_linestyle('--')
        right_atractor_line.set_linestyle('--')
        left_atractor_line.set_xdata(-1*sqrt_r)
        right_atractor_line.set_xdata(sqrt_r)

        axs[2].scatter((-1 * sqrt_r),0, facecolors='none', edgecolors='black')
        axs[2].scatter(sqrt_r,0, c='black')

    else:
        scat.set_offsets([None,None])
        left_atractor_line.set_linestyle('none')
        right_atractor_line.set_linestyle('none')

    print(f'frame: {frame}, new_r: {new_r}')
    return (
        sol_plot, phase_space, scat,
        left_atractor_line, right_atractor_line
    )

# TODO: use init_func for animation
ani = animation.FuncAnimation(fig=fig, func=update, frames=tot_frames, interval=50)
# ani.save('./animation.gif', writer='imagemagick', fps=60)
plt.show()


from day12_01 import create_pipes
from day12_01 import get_visitable_programs

def get_num_groups(lines):
    pipes = create_pipes(lines)
    groups = []
    grouped_programs = set()

    while len(grouped_programs) < len(pipes):
        ungrouped_programs = set(pipes.keys()).difference(grouped_programs)
        program = ungrouped_programs.pop()
        group = get_visitable_programs(pipes, program)
        groups.append(group)
        grouped_programs.update(set(group))

    return len(groups)

if __name__ == '__main__':
    with open('./data/input12.txt') as f:
        lines = [line.strip() for line in f.readlines()]
    print(get_num_groups(lines))


# Utility to rebroadcast a data manager stream to InfluxDB

import sys
import time

from influxdb import InfluxDBClient

class InfluxDBWriter(object):
    def __init__(self, address, dbase_name, batch_size=50, write_interval=2):
        self.client = InfluxDBClient(host=address)
        self.batch_size = batch_size
        self.dbase_name = dbase_name
        self.write_interval = write_interval
        if dbase_name not in self.client.get_list_database():
            self.client.create_database(dbase_name)
        self.client.switch_database(dbase_name)
        self.last_write = time.time()

    def run(self, data_gen):
        data = []
        for datum in data_gen():
            if datum is not None:
                data.append(datum)
            if len(data) > self.batch_size or datum is None or time.time() - self.last_write > self.write_interval:
                if data:
                    while True:
                        try:
                            self.client.write_points(data, time_precision='ms', database=self.dbase_name)
                            self.last_write = time.time()
                            break
                        except:
                            time.sleep(5.0)
                            sys.stderr.write("x")
                    sys.stderr.write(".")
                    data = []
        sys.stderr.write('\n')


import os

def read_text_file(filepath):
    results_array = [["---"],["time [ms]"], ["best road"], ["relative error [%]"]]

    with open(filepath, 'r') as txt_file:
        lines = txt_file.readlines()
        iterator = 1
        if len(lines)>15:
            iterator = int(len(lines)/12)
        print(len(lines))
        for line in lines[::iterator]:
            print(line)
            time, road, relative = line.strip().split("|")
            # print(results_array)
            results_array[0].append("---")
            results_array[1].append(time)
            results_array[2].append(road)
            results_array[3].append(relative)
            # time_array.append(time)
            # road_array.append(road)
            # relative_array.append(relative)
        # time, road, relative = lines[-1].strip().split("|")
        # results_array[0].append("---")
        # results_array[1].append(time)
        # results_array[2].append(road)
        # results_array[3].append(relative)
    with open(f"results.csv", 'a') as data_file:
        data_file.write(f"\n- **{filepath.split('.')[0]}**\n\n| ")

        for _ in range(len(results_array[0])-1):
            data_file.write(f"| ")
        data_file.write(f"|\n")
        for array in results_array:
            for element in array:
                data_file.write(f"|{element}")
            data_file.write(f"|\n")

        # data_file.write(f"{line}")
        # data_file.write(f"{lines[-1]}")

def create_table(files, title):
    pass

def main():
    path = "results"
    os.chdir(path)
    for folder in os.listdir():
        os.chdir(folder)
        os.chdir("data")
        previous = ""
        files = []
        for file in os.listdir():
            if file.endswith(".csv"):
                print(file)
                read_text_file(file)
        #         if previous == "":
        #             previous = int(file.split("-")[0])
        #     if file.endswith(".csv"):
        #         if previous == int(file.split("-")[0]):
        #             files.append(file)
        #             print(file)
        #         else:
        #             # print(files)
        #             # create_table(files)
        #             create_table(files, f"{folder}-{previous}")
        #             files = [file]
        #         # read_text_file(file, folder, previous)
        #         previous = int(file.split("-")[0])
        # create_table(files, f"{folder}-{previous}")
        # display_files(files, f"{folder}-{previous}")
                # read_text_file(file)
        os.chdir("../../")

if __name__ == '__main__':
    main()


import unittest

from DateTime.DateTime import DateTime

from Products.CMFFormController.ControllerState import ControllerState

from base import INTEGRATION_ANON_SURVEY_TESTING

class testAddDateQuestion(unittest.TestCase):
    """Ensure date question works correctly"""
    layer = INTEGRATION_ANON_SURVEY_TESTING

    def setUp(self):
        self.portal = self.layer['portal']

    def testCreateDateQuestion(self):
        s1 = getattr(self.portal, 's1')
        s1.invokeFactory('Survey Date Question', 'sdq1')
        assert 'sdq1' in s1.objectIds()

class testPostValidate(unittest.TestCase):
    """Ensure post validation works correctly"""
    layer = INTEGRATION_ANON_SURVEY_TESTING

    def setUp(self):
        self.portal = self.layer['portal']
        self.s1 = getattr(self.portal, 's1')
        self.s1.invokeFactory('Survey Date Question', 'sdq1')
        self.layer['request'].form['title'] = 'Date Question Title'
        self.layer['request'].form['showYMD'] = True
        self.layer['request'].form['showHM'] = True
        self.layer['request'].form['startingYear'] = '1970'
        self.layer['request'].form['endingYear'] = '2001'
        self.layer['request'].form['futureYears'] = ''

    def testFormValidates(self):
        """Test form validates correctly"""
        sdq1 = getattr(self.s1, 'sdq1')
        dummy_controller_state = ControllerState(
            id='base_edit',
            context=sdq1,
            button='submit',
            status='success',
            errors={},
            next_action=None,
        )
        controller = self.portal.portal_form_controller
        controller_state = controller.validate(
            dummy_controller_state,
            self.layer['request'],
            ['validate_base', ]
        )
        errors = controller_state.getErrors()
        errors = sdq1.post_validate(self.layer['request'], errors)
        assert errors == {}, \
            "Validation error raised: %s" % controller_state.getErrors()

    def testIntegers(self):
        """Test validation fails if an integer field is a string"""
        sdq1 = getattr(self.s1, 'sdq1')
        self.layer['request'].form['startingYear'] = 'string'
        self.layer['request'].form['endingYear'] = 'string'
        self.layer['request'].form['futureYears'] = 'string'
        dummy_controller_state = ControllerState(
            id='base_edit',
            context=sdq1,
            button='submit',
            status='success',
            errors={},
            next_action=None,
        )
        controller = self.portal.portal_form_controller
        controller_state = controller.validate(
            dummy_controller_state,
            self.layer['request'],
            ['validate_base', ]
        )
        errors = controller_state.getErrors()
        errors = sdq1.post_validate(self.layer['request'], errors)
        assert errors != {}, "Validation error not raised"
        assert 'startingYear' in errors
        assert 'endingYear' in errors
        assert 'futureYears' in errors

    def testQuestionField(self):
        """Test validation fails if ymd and hm both unselected"""
        sdq1 = getattr(self.s1, 'sdq1')
        self.layer['request'].form['showYMD'] = False
        self.layer['request'].form['showHM'] = False
        dummy_controller_state = ControllerState(
            id='base_edit',
            context=sdq1,
            button='submit',
            status='success',
            errors={},
            next_action=None,
        )
        controller = self.portal.portal_form_controller
        controller_state = controller.validate(
            dummy_controller_state,
            self.layer['request'],
            ['validate_base', ]
        )
        errors = controller_state.getErrors()
        errors = sdq1.post_validate(self.layer['request'], errors)
        assert errors != {}, "Validation error not raised"
        assert 'showYMD' in errors
        assert 'showHM' in errors

    def testEndYear(self):
        """Test validation fails if end year is before start year"""
        sdq1 = getattr(self.s1, 'sdq1')
        self.layer['request'].form['endingYear'] = '1969'
        dummy_controller_state = ControllerState(
            id='base_edit',
            context=sdq1,
            button='submit',
            status='success',
            errors={},
            next_action=None,
        )
        controller = self.portal.portal_form_controller
        controller_state = controller.validate(
            dummy_controller_state,
            self.layer['request'],
            ['validate_base', ]
        )
        errors = controller_state.getErrors()
        errors = sdq1.post_validate(self.layer['request'], errors)
        assert errors != {}, "Validation error not raised"
        assert 'endingYear' in errors

    def testFutureYear(self):
        """Test validation passes if future year, and no end year"""
        sdq1 = getattr(self.s1, 'sdq1')
        self.layer['request'].form['endingYear'] = ''
        self.layer['request'].form['futureYears'] = '5'
        dummy_controller_state = ControllerState(
            id='base_edit',
            context=sdq1,
            button='submit',
            status='success',
            errors={},
            next_action=None,
        )
        controller = self.portal.portal_form_controller
        controller_state = controller.validate(
            dummy_controller_state,
            self.layer['request'],
            ['validate_base', ]
        )
        errors = controller_state.getErrors()
        errors = sdq1.post_validate(self.layer['request'], errors)
        assert errors == {}, "Validation error raised: %s" % errors

class testDateQuestion(unittest.TestCase):
    """Ensure date question works correctly"""
    layer = INTEGRATION_ANON_SURVEY_TESTING

    def setUp(self):
        self.portal = self.layer['portal']
        self.s1 = getattr(self.portal, 's1')
        self.s1.invokeFactory('Survey Date Question', 'sdq1')

    def testAddAnswer(self):
        s1 = getattr(self, 's1')
        userid = s1.getSurveyId()
        assert userid == "test_user_1_", "Not default test user"
        questions = s1.getQuestions()
        now = DateTime()
        for question in questions:
            if question.portal_type == 'Survey Date Question':
                question.addAnswer(now)
                assert question.getAnswerFor(userid) == now, \
                    "Answer not saved correctly"
        answers = self.s1.getAnswersByUser(userid)
        self.assertEqual(len(answers), 1)

    def testValidationRequiredSplitDate(self):
        s1 = getattr(self, 's1')
        sdq1 = getattr(s1, 'sdq1')
        sdq1.setRequired(True)
        now = DateTime()
        now_value = str(now.year()) + \
            '/' + str(now.month()) + \
            '/' + str(now.day()) + \
            ' ' + str(now.hour()) + \
            ':' + str(now.minute()) + \
            ':00 GMT'
        self.layer['request'].form['sdq1_ampm'] = ''
        self.layer['request'].form['sdq1_day'] = str(now.day())
        self.layer['request'].form['sdq1_hour'] = str(now.hour())
        self.layer['request'].form['sdq1_minute'] = str(now.minute())
        self.layer['request'].form['sdq1_month'] = str(now.month())
        self.layer['request'].form['sdq1_year'] = str(now.year())
        dummy_controller_state = ControllerState(
            id='survey_view',
            context=s1,
            button='submit',
            status='success',
            errors={},
            next_action=None,
        )
        controller = self.portal.portal_form_controller
        controller_state = controller.validate(
            dummy_controller_state,
            self.layer['request'],
            ['validate_survey', ]
        )
        assert controller_state.getErrors() == {}, \
            "Validation error raised: %s" % controller_state.getErrors()
        userid = s1.getSurveyId()
        assert userid == "test_user_1_", "Not default test user"
        questions = s1.getQuestions()
        for question in questions:
            if question.portal_type == 'Survey Date Question':
                assert question.getAnswerFor(userid) == now_value, \
                    "Answer not saved correctly: %s" \
                    % question.getAnswerFor(userid)


from googletrans import Translator, constants
import speech_recognition as sr
r = sr.Recognizer()
t = Translator()
m = sr.Microphone()
with m as mic:
  r.adjust_for_ambient_noise(mic)
  print("Say something in English...")
  voice = r.listen(mic)
  print("Thank you for your input...")
  try:
    capture = r.recognize_google(voice) # By default, this will capture English words by the user. Changing arguments in "recognize_google" can change this.
    print("I think you said this: {}".format(capture))
  except Exception as e:
    print("Error: {}".format(e))
  output = translator.translate(capture, dest = "es") # This example uses "es" for Espanol, or Spanish. This can be changed.
  print("English: {} ===> Spanish: {}".format(output.origin, output.text))


import sqlalchemy

class NutrientDB:
    nutrient_norms = []
    def __init__(self, database):
        self.database = database
    #Male - 1; Female - 2
    #Возвращает все нутриенты и их значения из базы, в зависимости от пола
    #Также возвращает значение необходимой золы
    def get_all_nutrient_values_for_gender(self, gender):
        self.nutrient_norms = self.database.execute(sqlalchemy.text("select Nutrient_idNutrient, value from Nutrient_has_Gender where Nutrient_has_Gender.Gender_idGender=:idGender"), {'idGender': gender}).fetchall()
        mineral_sum=0
        for nutrient in self.nutrient_norms:
            #константы - айдишники минералов в базе
            if nutrient[0] in [14,15,16,17,20,21,23,24,25,28]:
                mineral_sum+=nutrient[1]
        return self.nutrient_norms, mineral_sum


from django.forms import ValidationError
from rest_framework.mixins import (
    CreateModelMixin
)
from rest_framework.viewsets import GenericViewSet

from utils.responses import success_response

from ..models import CustomUser
from ..serializers import CustomUserSerializer

from rest_framework import status
from rest_framework.response import Response

class CreateUserViewSet(
        GenericViewSet,  # generic view functionality
        CreateModelMixin # handles POSTs
    ):

    serializer_class = CustomUserSerializer
    queryset = CustomUser.objects.all()

    def perform_create(self, serializer):
        queryset = CustomUser.objects.filter(email=serializer.validated_data['email'])
        if queryset.exists():
            raise ValidationError('A user with this email has already signed up', code="invalid")
        serializer.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        user = CustomUser.objects.get(email=serializer.validated_data['email'])

        token = user.set_token()

        response = success_response({"token": token}, status=status.HTTP_201_CREATED, headers=headers)

        response = Response({
            'success': True,
            'data': {
                'token': token
            }
        }, status=status.HTTP_201_CREATED, headers=headers)

        response.set_cookie('auth_token', token)

        return response


import pygame
import sys
import time
import random
from pygame import *

width = 450
height = 450
black = (0,0,0)
white = (255,255,255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

playerWidth = 10
highScore = 0

pygame.init()
smallFont = pygame.font.SysFont(None, 25) # 25 = font size
bigFont = pygame.font.SysFont(None, 65) # 25 = font size

def clamp(n, min, max):
    if (n < min): return min
    if ( n > max): return max
    return n

def relocateDot():
    return round(random.uniform(0, width-playerWidth*dotSize)),round(random.uniform(0, height-playerWidth*dotSize))

def detectCollisions(x1, y1, w1, h1, x2, y2, w2, h2):
    if x1+w1>x2 and x2+w2>x1 and y1+h1>y2 and h2+y2>y1:return True
    else:return False

def message_to_screen(message, x, y, color, f):
    screen_message_text = f.render(message, True, color)
    screen.blit(screen_message_text, [x-screen_message_text.get_width()/2.0,y-screen_message_text.get_height()/2.0])

backgroundColour = white

fps = 23
# speed = 1
dotSize = 0.75

screen = pygame.display.set_mode((width,height)) # return a pygame.surface object
pygame.display.set_caption("snake_z")

gameExit = False
reset = True

clock = pygame.time.Clock()

x = width/2
y = height/2

x_change = playerWidth
y_change = 0

randomDotX,randomDotY =  relocateDot()
player = [clamp(x, 0, width-playerWidth), clamp(y, 0, height-playerWidth), playerWidth, playerWidth]

snake = []
snake.append([x,y, playerWidth, playerWidth])

topOfSnake = 0
delta = 2
endGameMessage = ""
while not gameExit:
    clock.tick(fps)

    while reset:
        screen.fill(backgroundColour)
        randomDotX,randomDotY =  relocateDot()

        message_to_screen(endGameMessage, width*0.5, height*0.35, black, smallFont)
        message_to_screen("snake_z", width*0.5, height*0.5, black, bigFont)
        message_to_screen("high score: " + str(highScore), width*0.5, height*0.65, black, smallFont)
        message_to_screen("press space to play", width*0.5, height*0.8, black, smallFont)
        message_to_screen("press esc to quit", width*0.5, height*0.85, black, smallFont)
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                gameExit = True
                reset = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                x = width/2
                y = height/2

                x_change = playerWidth
                y_change = 0

                reset = False
                # reset the snake
                x = width/2
                y = height/2
                sizeOfSnake = 1
                topOfSnake = 0
                snake = []
                snake.append([x,y, playerWidth, playerWidth])
                endGameMessage = ""

    for event in pygame.event.get():
        # print event
        if event.type == QUIT: gameExit = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            reset = True
        if event.type == pygame.KEYDOWN:
          if event.key == pygame.K_LEFT and x_change == 0:
              y_change = 0
              x_change = -playerWidth
          elif event.key == pygame.K_RIGHT and x_change == 0:
              y_change = 0
              x_change = playerWidth
          elif event.key == pygame.K_UP and y_change == 0:
              x_change = 0
              y_change = -playerWidth
          elif event.key == pygame.K_DOWN and y_change == 0:
              x_change = 0
              y_change = playerWidth

    screen.fill(backgroundColour)

    # make a dot appear
    dot = [randomDotX, randomDotY, playerWidth*dotSize, playerWidth*dotSize]
    pygame.draw.rect(screen, blue, dot)

    # move player around
    x += x_change
    y += y_change

    # check for hitting edge - if so, game over
    if (x <= 0 or x >= width or y <= 0 or y >= height) and not reset:
        if (len(snake)-1)*100 > highScore:  highScore = str((len(snake)-1)*100)
        reset = True
        endGameMessage = "You hit the death wall."

    snake[topOfSnake] = [clamp(x, 0, width-playerWidth), clamp(y, 0, height-playerWidth), playerWidth, playerWidth]
    count = 0
    for piece in snake:
        if count%2==0:
            pygame.draw.rect(screen, red, piece)
        else:
            pygame.draw.rect(screen, green, piece)
        count += 1

    # if colliding with a dot,make the snake bigger and generate a new dot
    # else check for collisions with yourself (if you're bigger than 4)
    if detectCollisions(snake[topOfSnake][0], snake[topOfSnake][1], snake[topOfSnake][2], snake[topOfSnake][3], dot[0], dot[1], dot[2], dot[3]):
        randomDotX,randomDotY =  relocateDot()
        snake.append([x,y, playerWidth, playerWidth])
    else:
        if len(snake) > 4:
            for i in range(0, len(snake)):
                k = (i+ len(snake))%len(snake)
                if k == topOfSnake or k+1 == topOfSnake: continue
                if detectCollisions(snake[topOfSnake][0], snake[topOfSnake][1], snake[topOfSnake][2]-delta, snake[topOfSnake][3]-delta, snake[k][0], snake[k][1], snake[k][2]-delta, snake[k][3]-delta):
                    # print 'Collision with self: '
                    endGameMessage = "You ran into yourself. Good job."

                    reset = True

    topOfSnake += 1
    if (topOfSnake >= len(snake)): topOfSnake = 0

    message_to_screen("Score: " + str((len(snake)-1)*100), width*0.5, 20, black, smallFont)

    pygame.display.update()

screen.fill(backgroundColour)
message_to_screen("You suck", width*0.5, height*0.75, black, smallFont)
pygame.display.update()
pygame.time.wait(2)
pygame.quit()
quit()


# -*- coding: utf-8 -*-
import os
import time
from collections import namedtuple

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from pylab import mpl
import matplotlib.font_manager as fm
import netron

from env import Env
from model import DQN, DQNCNN

np.random.seed(2)

# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
matplotlib.rcParams['axes.unicode_minus'] = False
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 加载 Times New Roman 字体
font_path = 'C:/Windows/Fonts/times.ttf'
prop = fm.FontProperties(fname=font_path, size=8)

Experience = namedtuple('Transition',
                        field_names=['cur_otherState', "cur_NeighborState",  # 状态
                                     'bandAction', 'aimAction', 'freqAction',  # 动作
                                     'reward',  # 奖励
                                     'next_otherState', 'next_NeighborState'])  # Define a transition tuple

GAMMA = 0.99
BATCH_SIZE = 32
REPLAY_SIZE = 1000
LEARNING_RATE = 1e-4
SYNC_TARGET_FRAMES = 100  # 更新目标网络频率

EPSILON_DECAY_LAST_FRAME = 150000
EPSILON_START = 0.8
EPSILON_FINAL = 0.01
EPSILON = 400000

RESET = 1000  # 重置游戏次数

BandNum = 5  # 带宽选择
FreqNum = 6  # 比率选择

momentum = 0.005

RESOURCE = [0.2, 0.4, 0.5, 0.6, 0.8, 0.9]

@torch.no_grad()
def play_step(env, epsilon, models):
    vehicles = env.vehicles
    old_otherState = []
    old_neighborState = []

    actionFreq = []
    actionBand = []
    actionAim = []
    # 贪心选择动作
    for i, model in enumerate(models):
        old_otherState.append(vehicles[i].self_state)
        old_neighborState.append(vehicles[i].neighbor_state)
        if np.random.random() < epsilon:
            # 随机动作
            actionBand.append(np.random.randint(0, 5))
            actionFreq.append(RESOURCE[np.random.randint(0, len(RESOURCE))])
            actionAim.append(np.random.randint(0, 7))  # local+mec+neighbor
        else:
            state_v = torch.tensor([vehicles[i].self_state], dtype=torch.float32)
            neighborState_v = torch.tensor([[vehicles[i].neighbor_state]], dtype=torch.float32)
            bandActionValue, aimActionValue, freqActionValue = model(state_v, neighborState_v)

            bandAction = np.array(bandActionValue, dtype=np.float32).reshape(-1)
            aimAction = np.array(aimActionValue, dtype=np.float32).reshape(-1)
            freqAction = np.array(freqActionValue, dtype=np.float32).reshape(-1)

            actionAim.append(np.argmax(aimAction))
            actionBand.append(np.argmax(bandAction))
            actionFreq.append(np.argmax(freqAction))
    # print("action:", action)
    _, _, otherState, neighborState, Reward, reward = env.step(actionBand, actionAim, actionFreq)
    # print("reward:", reward)

    for i, vehicle in enumerate(vehicles):
        exp = Experience(old_otherState[i], [old_neighborState[i]],
                         actionBand[i], actionAim[i], actionFreq[i],
                         reward[i],
                         otherState[i], [neighborState[i]])
        vehicle.buffer.append(exp)
    return round(Reward, 2)  # 返回总的平均奖励


import pandas as pd
from typing import List

class LogsPrep:

    def __init__(self,
                 logs_df: pd.DataFrame,
                 n_semester: int):
        """
        :param logs_df: logs dataframe from db
        :param n_semester: number of scoring semester
        """
        self.logs_df = logs_df
        self.n_semester = n_semester

    #------Берем логи за нужные семестры------#
    def _logs_for_sem(self) -> pd.DataFrame:
        logs_df = self.logs_df[self.logs_df['semester_num'] <=float(self.n_semester - 1)]

        return logs_df

    # Генерация фичей из логов
    def logs_prepare(self) -> pd.DataFrame:
        # Логи за все семестры не включая текущий
        logs_df = self._logs_for_sem()
        logs_df.fillna(0, inplace=True)
        # Логи за последний семестр
        logs_last = logs_df[logs_df['semester_num'] == float(self.n_semester - 1)]

        # Логи за все семестры кроме последнего
        if self.n_semester == 2: # Будем сравнивать с самим собой
            logs_except_last = logs_last.copy()
        else:
            logs_except_last = logs_df[logs_df['semester_num'] < float(self.n_semester - 1)]

        # Названия колонок с логами
        logs_cols = logs_df.columns[2:]

        # Словарик "средние по логам"
        agg_dict = dict.fromkeys(logs_cols, 'mean')

        # Берем среднее по логам за все семестры кроме последнего
        logs_except_last_agg = \
        (
            logs_except_last
            .groupby(by='ABIT_UID', as_index = False)
            .agg(agg_dict)
        )

        # Мерджим агг старых и новые
        new_logs_df = \
        (
            logs_except_last_agg
            .merge(logs_last, on='ABIT_UID', how = 'left')
        )

        #Отношение логов за последний семестр к среднему за предыдущие
        new_logs_df['logs_dynamic'] = new_logs_df['cnt_all_logs_y']/new_logs_df['cnt_all_logs_x'] - 1
        #Заполняем нулями для последующего сокращения размерности
        new_logs_df.fillna(0, inplace=True)

        return new_logs_df

    # Названия колонок с логами для последующего UMAP
    def get_column_names(self,
                         logs_df: pd.DataFrame) -> tuple:
        """
        Extract column names of dataframe according to filter
        :param logs_df: dataframe with logs
        return: tuple with lists
        """
        logs_columns_except_last = logs_df.filter(regex=f'_x').columns.tolist()
        logs_columns_last_sem = logs_df.filter(regex=f'_y').columns.tolist()

        return (logs_columns_except_last,logs_columns_last_sem)


#!/usr/bin/env python3

"""
Definitions of GB and Minimalist tree grammars and transducers.
"""

from tree import Tree
from treebdfa import TreeBDFA
import test_trees

#
# Simple SS-style grammar
#

qs = ['qS', 'qNP', 'qN', 'qVP', 'qV', 'qDet']
xs = ['S', 'NP', 'N', 'Det', 'VP', 'V']
fs = ['qNP', 'qVP', 'qS']
ts = [([], 'N', 'qN'),
      ([], 'V', 'qV'),
      ([], 'Det', 'qDet'),
      (['qDet', 'qN'], 'NP', 'qNP'),
      (['qV'], 'VP', 'qVP'),
      (['qV', 'qNP'], 'VP', 'qVP'),
      (['qNP', 'qVP'], 'S', 'qS')]
ss_grammar = TreeBDFA(qs, xs, fs, ts)

#
# GB-style X-bar grammar
#

qs = ["qXP"]
xs = []
fs = ["qXP"]

# Generate X-bar rules for each syntactic category
#   X' -> X
#   X' -> X YP
#   XP -> X'
#   XP -> ZP X'
# A single state "qXP" will be returned upon processing a phrase of any category.
#   In other words, subcategorization is not modeled.
ts = []
for z in "NAVPDIC":
    zbar = z + "'"
    zp = z + 'P'
    qz = 'q' + z
    qzbar = 'q' + z + "bar"
    QXP = "qXP"
    qs.extend([qz, qzbar])
    xs.extend([z, zbar, zp])
    ts.extend(
        [([], z, qz),
         ([qz], zbar, qzbar),
         ([qz, QXP], zbar, qzbar),
         ([qzbar], zp, QXP),
         ([QXP, qzbar], zp, QXP)])

gb_grammar = TreeBDFA(qs, xs, fs, ts)

#
# Minimalist-style ("bare phrase structure") X-bar grammar
#

qs = ["qXP"]
xs = []
fs = ["qXP"]

# Generate X-bar rules for each syntactic category
#   XP -> X YP
#   X' -> X YP
#   XP -> ZP X'
# A single state "qXP" will be returned upon processing a phrase of any category.
#   In other words, subcategorization is not modeled.
ts = []
for z in "NAVPDTC":
    zbar = z + "'"
    zp = z + 'P'
    qz = 'q' + z
    qzbar = 'q' + z + "bar"
    QXP = "qXP"
    qs.extend([qz, qzbar])
    xs.extend([z, zbar, zp])
    ts.extend(
        [([], zp, QXP),
         ([], z, qz),
         ([qz, QXP], zp, QXP),
         ([qz, QXP], zbar, qzbar),
         ([QXP, qzbar], zp, QXP)])

minimalist_grammar = TreeBDFA(qs, xs, fs, ts)

def test_simple():
    t1 = Tree.from_list(['S', ['NP', ['Det'], ['N']],
                         ['VP', ['V'], ['NP', ['Det'], ['N']]]])
    print(t1)
    print(ss_grammar.recognizes(t1))

def test_gb():
    # print(gb_grammar)
    t1 = test_trees.gb_np_n
    t2 = test_trees.gb_np_d_n
    t3 = test_trees.gb_simple_trans_clause
    for t in [t1, t2, t3]:
        print(t)
        print(gb_grammar.recognizes(t))

def test_minimalist():
    # print(minimalist_grammar)
    t1 = test_trees.min_dp_d
    t2 = test_trees.min_dp_d_n
    t3 = test_trees.min_simple_trans_clause
    for t in [t1, t2, t3]:
        print(t)
        print(minimalist_grammar.recognizes(t))

if __name__ == "__main__":
    test_gb()
    test_minimalist()


# -*- coding: utf-8 -*-
"""
Created on Thu Sep 16 15:41:01 2021

@author: adminlocal
"""
#read file of videos
#compute TT-svd and save it
import sys
chemin = ("C:/Users/adminlocal/Desktop/Code_n")
sys.path.append(chemin)
import pickle
from MPS_rand import  matrix_product_state, matrix_product_state_transposed
import numpy as np
import time

with open("C:/Users/adminlocal/Desktop/Code_n/Video_jumping_walking", 'rb') as pickle_file:
    content = pickle.load(pickle_file)

#s'assurer que la 2e dim = 240, 3e dim = 320
def process(list_tensor):
    list_T=[]
    for T in list_tensor:
        if (T.shape[1]== 240 and T.shape[2] == 320):
            list_T.append(T)

    return list_T

#unifier la première dimension des tenseurs
def min_dim1(list_tensor):
    lengths = []
    for T in list_tensor:
        lengths.append(T.shape[0])

    return np.min(lengths)

def unif_dim1(list_tensor, dim1):
    list_T=[]
    for T in list_tensor:
        T = T[:dim1,:]
        list_T.append(T)

    return list_T

def process_data_videos(file): # file: nom du fichier à lire, N_T_c: Nbr de données par classe
    """
    return (list_data, list_labels)video tensors and labels from file for example ''Video_jumping_walking'
    list_data = classe 0+ classe1
    """
    file = open(file, 'rb')
    data = pickle.load(file)
    T_c0 = data[0]
    T_c1 = data[1]

    file.close()

    list_T_c0 =process(T_c0)
    list_T_c1 =process(T_c1)

    N0, N1 = min_dim1(list_T_c0), min_dim1(list_T_c1)
    dim1 = min(N0, N1)

    list_T_c0, list_T_c1 = unif_dim1(list_T_c0, dim1), unif_dim1(list_T_c1, dim1)
    N_T_c0, N_T_c1 = len(list_T_c0), len(list_T_c1)
    N_T_c = min(N_T_c0, N_T_c1)

    list_data = list_T_c0[:N_T_c] + list_T_c1[:N_T_c]

    labels0 = [0]*N_T_c
    labels1 = [1]*N_T_c
    list_labels = labels0+ labels1
    print("N_T_c",N_T_c)

    return list_data, list_labels

def get_TT_svd(list_T, TT_ranks): # Returns a list of CP factors
    return [  matrix_product_state(T.astype('f'), TT_ranks, verbose=False, type_svd = 'partial_svd') for T in list_T]

def get_TT_svd_transposed(list_T, TT_ranks): # Returns a list of CP factors
    return [  matrix_product_state_transposed(T.astype('f'), TT_ranks, verbose=False, type_svd = 'partial_svd') for T in list_T]

def compute_TT_cores(list_data,TT_ranks):
    print("Get TT-svd")
    t0 = time.time()
    list_TT_cores =  get_TT_svd(list_data, TT_ranks)
    t1 = time.time()-t0
    return list_TT_cores, t1

def compute_TT_cores_transposed(list_data,TT_ranks):
    print("Get TT-svd with factors transposed")
    t0 = time.time()
    list_TT_cores =  get_TT_svd_transposed(list_data, TT_ranks)
    t1 = time.time()-t0
    return list_TT_cores, t1

    return list_TT_cores, t1

if __name__ == 'main':

    list_data, list_labels = process_data_videos("C:/Users/adminlocal/Desktop/Code_n/Video_jumping_walking")
    TT_ranks = [1,2,2,2,1]
    list_data_TT_cores =  get_TT_svd(list_data, TT_ranks)

"""
# open a file, where you ant to store the data
file = open('TT_factors', 'wb')# list [list_data_TT_cores, list_labels, TT_ranks]
data=[None]*3
data[0] = list_data_TT_cores
data[1] = list_labels
data[2] = TT_ranks
# dump information to that file
pickle.dump(data, file)
# dump information to that file
pickle.dump(list_data_TT_cores , file)
# close the file
file.close()
"""


#!/usr/bin/env python
#coding:utf-8

import os
import re
import sys
import json
import logging
import argparse
import collections

LOG = logging.getLogger(__name__)

__version__ = "1.1.0"
__author__ = ("Xingguo Zhang",)
__email__ = "113178210@qq.com"
__all__ = []

AMINO_ACID = {"Gly": "G", "Ala": "A", "Val": "V", "Leu":"L", "Ile": "I",
    "Pro": "P", "Phe": "F", "Tyr": "Y", "Trp": "W", "Ser": "S",
    "Thr": "T", "Cys": "C", "Met": "M", "Asn": "N", "Gln": "Q",
    "Asp": "D", "Glu":"E", "Lys": "K", "Arg": "R", "His": "H"}

def read_tsv(file, sep=None):
    """
    read tsv joined with sep
    :param file: file name
    :param sep: separator
    :return: list
    """
    LOG.info("reading message from %r" % file)

    for line in open(file):
        line = line.strip()

        if not line or line.startswith("#"):
            continue

        yield line.split(sep)

def supper(string):

    string = string[0].upper() + string[1::]

    return string

def note2norm(seqid, note, depth):

    note = note.strip().split()
    ref, alt = note[1].split('=>')
    vep = note[8]

    if vep in ["synonymous_variant", "missense_variant"]:
        pref, psite, palt = re.findall(r'[0-9]+|[a-z]+', note[10].lower())[1::]
        pref = AMINO_ACID[supper(pref)]
        palt = AMINO_ACID[supper(palt)]
        site = re.findall(r'[0-9]+|[A-Z]+', note[9])[0]
        gene = note[11]
        norm = "ID={id};REF={ref};ALT={alt};VEP={vep},{gene}:p.{psite}{pref}>{palt},\
{gene}:c.{site}{ref}>{alt};coverage={depth};".format(
            id=seqid, ref=ref, alt=alt, vep=vep, psite=psite,
            pref=pref, palt=palt, gene=gene, site=site, depth=depth)
    else:
        if vep=="intergenic_region":
            vep = "intergenic_variant"
        norm = "ID={id};REF={ref};ALT={alt};VEP={vep}".format(
            id=seqid, ref=ref, alt=alt, vep=vep)

    return norm

def filter_snp_gff(file, depth):

    data = collections.OrderedDict()

    for line in read_tsv(file, '\t'):
        note = line[8].strip().split()
        snps = note[0].split('=')[1].upper()

        if "note=snp" not in note:
            continue
        if ("synonymous_variant" in note) or ("missense_variant" in note) or ("intergenic_region" in note):
            line[1] = "snpEff:4.3"
            line[2] = snps
            data[line[3]] = line

    print("##gff-version 3")
    for line in read_tsv(depth, '\t'):
        if line[1] not in data:
            continue
        snps = data[line[1]]
        snps[-1] = note2norm(snps[0], snps[-1], line[2])
        print('\t'.join(snps))

    return 0

def add_help(parser):

    parser.add_argument('-i', '--input', metavar='FILE', type=str, required=True,
        help='Set the input file(snp.gff).')
    parser.add_argument('-d', '--depth', metavar='FILE', type=str, required=True,
        help='Input the coverage depth file for each site(depth.xls)')

    return parser

def main():

    logging.basicConfig(
        stream=sys.stderr,
        level=logging.INFO,
        format="[%(levelname)s] %(message)s"
    )
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
        description='''
name:
    filter_snp_gff.py  filter snp.

attention:
    filter_snp_gff.py -i snp.gff -d depth.xls >filter_snp.gff

version: %s
contact:  %s <%s>\
        ''' % (__version__, ' '.join(__author__), __email__))

    args = add_help(parser).parse_args()

    filter_snp_gff(args.input, args.depth)

if __name__ == "__main__":

    main()