import re
def solution(record):
    answer = []
    lists = []
    user_dict = {}

    for r in record:
        if 'Leave' in r:
            status, uid = r.split(" ")
            lists.append([status, uid])
        elif 'Change' in r:
            status, uid, name = r.split(" ")
            user_dict[uid] = name
        else:
            status, uid, name = r.split(" ")
            user_dict[uid] = name
            lists.append([status, uid])

    for status, uid in lists:
        if status == "Enter":
            answer.append(user_dict[uid]+"님이 들어왔습니다.")
        else:
            answer.append(user_dict[uid] + "님이 나갔습니다.")
    return answer

print(solution(["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"]))
# ["Prodo님이 들어왔습니다.", "Ryan님이 들어왔습니다.", "Prodo님이 나갔습니다.", "Prodo님이 들어왔습니다."]

2019 KAKAO BLIND RECRUITMENT/1. 오픈채팅방.py


from gpiozero import RotaryEncoder
from gpiozero import PWMLED
from gpiozero import LED

from time import sleep

# GPIOx
ENB = 12
ENA = 13
IN1 = 21
IN2 = 20
IN3 = 26
IN4 = 19

R_ENC_A = 0
R_ENC_B = 0

L_ENC_A = 1
L_ENC_B = 7

encoder_states = [0,0]

class own_motor():
    def __init__(self, A, B, PWM):
        self.in_a = LED(A)
        self.in_b = LED(B)
        self.pwm = PWMLED(PWM)

    def forward(self, prec):
        self.in_a.off()
        self.in_b.on()
        self.pwm.on()
        self.pwm.value = prec

    def backward(self, prec):
        self.in_a.on()
        self.in_b.off()
        self.pwm.on()
        self.pwm.value = prec

    def stop(self):
        self.in_a.on()
        self.in_b.on()

class platform():
    def __init__(self):
        self.l_motor = own_motor(IN1, IN2, ENA)
        self.r_motor = own_motor(IN4, IN3, ENB)

        #self.r_encoder = RotaryEncoder(R_ENC_A, R_ENC_B)
        self.l_encoder = RotaryEncoder(L_ENC_A, L_ENC_B, max_steps=1000)

        self.l_speed = 0.0
        self.r_speed = 0.0

    def set_speed(self, r=0.0, l=0.0):
        self.l_speed = l
        self.r_speed = r

    def forward(self):
        self.l_motor.forward(self.l_speed)
        self.r_motor.forward(self.r_speed)

    def backward(self):
        self.l_motor.backward(self.l_speed)
        self.r_motor.backward(self.r_speed)

    def stop(self):
        self.l_motor.stop()
        self.r_motor.stop()

    def left(self):
        self.l_motor.backward(self.l_speed)
        self.r_motor.forward(self.r_speed)

    def right(self):
        self.l_motor.forward(self.l_speed)
        self.r_motor.backward(self.r_speed)

if __name__ == "__main__":

    platform = platform()
    platform.set_speed(r=0.5,l=0.5)

    while True:
        platform.forward()
        sleep(3)
        platform.stop()
        sleep(3)
        platform.backward()
        sleep(3)
        platform.right()
        sleep(3)
        platform.left()
        sleep(3)


def get_polulation():
    with open('人口普查', 'r', encoding='utf-8') as f:
        for i in f:
            yield i

g=get_polulation()
g.__next__()
g.__next__()
g.__next__()
g.__next__()
# print(g.__next__()['population'])
# s1=eval(g.__next__())
# print(type(s1))
# print(s1['population'])
# res=0
# for p in g:
#     p_dic=eval(p)
#     print(p_dic['population'])
#     res+=p_dic['population']
# print(res)

all_pop=sum(eval(i)['population'] for i in g)
print(all_pop)

for p in g:
    print('%s %%' %eval(p)['population']/all_pop)


############################################################
#### Gillespie algorithm for ProcProc Model                #
#### Written by Abhishek Mallela                           #
#### Pseudocode + algorithm developed with Eric J. Deeds   #
#### Latest Version: 8/18/16                               #
############################################################

import numpy as np
from numpy import *
import random
import scipy.io

Mon = 1e-5 # This is for r = ratio of V_max's = 1e-2
Don = 1e-5 # Stochastic 'on' rate
r1 = 2e-5
r2 = 2e-4
Moff = 1e-1 # This is for r = ratio of V_max's = 1e-2; keeping K_M the same
Doff = 1e-1 # Stochastic, deterministic: same
Mcat2 = 1-1e-3 # This is for r = ratio of V_max's = 1e-2; keeping K_M the same
Mcat1 = Mcat2/100 # Because it takes longer to add the first ubiquitin unit
Dcat = 1-1e-3 # Stochastic, deterministic: same

def gillespie(maxtime=1e6):
    #### Initial declarations
    num = 1000 # S_init
    c = 0
    Q = r1*num # Defining it this way so that 'num' is the only quantity to change
    v0 = np.zeros((num)) # Row vector of 'num'-many zeros. Each element represents an S0 molecule
    v1 = np.empty((c)) # Empty row vector for v1; container for S1 to S3
    v2 = np.empty((c)) # Empty row vector for v2; container for S4 to Sl
    v3 = np.empty((c)) # Empty row vector for v3; container for MS0 to MS3
    v4 = np.empty((c)) # Empty row vector for v4; container for DS0 to DS3
    v5 = np.empty((c)) # Empty row vector for v5; container for MS4 to MSl
    v6 = np.empty((c)) # Empty row vector for v6; container for DS4 to DSl
    M_un = 100 # M_init
    D_un = 100 # D_init

## Begin Stochastic Simulation Algorithm (Doob-Gillespie)
    time = 0
    while (time < maxtime):
        tot = [Q, r1*len(v1), r2*len(v2), r1*len(v3), r1*len(v4), +
    					r2*len(v5), r2*len(v6), Mon*M_un*len(v1), +
    					Don*D_un*len(v1), Mon*M_un*len(v0), Don*D_un*len(v0), +
    					Mon*M_un*len(v2), Don*D_un*len(v2), Moff*len(v3), +
    					Doff*len(v4), Moff*len(v5), Doff*len(v6), +
    					Mcat1*(len(v3)-np.count_nonzero(v3)), +
    					Mcat2*np.count_nonzero(v3), +
    					Dcat*len(v4), Mcat2*len(v5), Dcat*len(v6)]
        for k in range(21):
            tot[k + 1] += tot[k]
        kT = tot[-1]
        time += -np.log(1-np.random.random())/kT

        if time >= maxtime:
            break

        event_kT = np.random.random() * kT
        #### Reaction 1: Synthesize a new S
        if event_kT < tot[0]:
            v0 = np.append(v0,0)
        #### Reaction 2: Delete a S from v1
        elif event_kT < tot[1]:
            k = random.randrange(len(v1))
            v1 = v1[np.arange(len(v1))!=k]
        #### Reaction 3: Delete a S from v2
        elif event_kT < tot[2]:
            k = random.randrange(len(v2))
            v2 = v2[np.arange(len(v2))!=k]
        #### Reaction 4: Delete a S from v3
        elif event_kT < tot[3]:
            k = random.randrange(len(v3))
            v3 = v3[np.arange(len(v3))!=k]
            M_un += 1
        #### Reaction 5: Delete a S from v4
        elif event_kT < tot[4]:
            k = random.randrange(len(v4))
            v4 = v4[np.arange(len(v4))!=k]
            D_un += 1
        #### Reaction 6: Delete a S from v5
        elif event_kT < tot[5]:
            k = random.randrange(len(v5))
            v5 = v5[np.arange(len(v5))!=k]
            M_un += 1
        #### Reaction 7: Delete a S from v6
        elif event_kT < tot[6]:
            k = random.randrange(len(v6))
            v6 = v6[np.arange(len(v6))!=k]
            D_un += 1
        #### Reaction 8: Bind a M to an S in v1
        elif event_kT < tot[7]:
            k = random.randrange(len(v1))
            v1temp = v1[np.arange(len(v1))!=k]
            v1rem = v1[k]
            v1 = v1temp
            if (v1rem > 0 and v1rem < 4):
                v3 = np.append(v3,v1rem)
            elif (v1rem >= 4):
                v5 = np.append(v5,v1rem)
            M_un -= 1
        #### Reaction 9: Bind a D to an S in v1
        elif event_kT < tot[8]:
            k = random.randrange(len(v1))
            v1temp = v1[np.arange(len(v1))!=k]
            v1rem = v1[k]
            v1 = v1temp
            if (v1rem > 0 and v1rem < 4):
                v4 = np.append(v4,v1rem)
            elif (v1rem >= 4):
                v6 = np.append(v6,v1rem)
            D_un -= 1
        #### Reaction 10: Bind a M to an S in v0
        elif event_kT < tot[9]:
            k = random.randrange(len(v0))
            v0temp = v0[np.arange(len(v0))!=k]
            v0rem = v0[k]
            v0 = v0temp
            v3 = np.append(v3,v0rem)
            M_un -= 1
        #### Reaction 11: Bind a D to an S in v0
        elif event_kT < tot[10]:
            k = random.randrange(len(v0))
            v0temp = v0[np.arange(len(v0))!=k]
            v0rem = v0[k]
            v0 = v0temp
            v4 = np.append(v4,v0rem)
            D_un -= 1
        #### Reaction 12: Bind a M to an S in v2
        elif event_kT < tot[11]:
            k = random.randrange(len(v2))
            v2temp = v2[np.arange(len(v2))!=k]
            v2rem = v2[k]
            v2 = v2temp
            v5 = np.append(v5,v2rem)
            M_un -= 1
        #### Reaction 13: Bind a D to an S in v2
        elif event_kT < tot[12]:
            k = random.randrange(len(v2))
            v2temp = v2[np.arange(len(v2))!=k]
            v2rem = v2[k]
            v2 = v2temp
            v6 = np.append(v6,v2rem)
            D_un -= 1
        #### Reaction 14: Unbind a M from v3
        elif event_kT < tot[13]:
            k = random.randrange(len(v3))
            v3temp = v3[np.arange(len(v3))!=k]
            v3rem = v3[k]
            if v3rem == 0:
                v0 = np.append(v0,v3rem)
            elif v3rem > 0:
                v1 = np.append(v1,v3rem)
            v3 = v3temp
            M_un += 1
        #### Reaction 15: Unbind a D from v4
        elif event_kT < tot[14]:
            k = random.randrange(len(v4))
            v4temp = v4[np.arange(len(v4))!=k]
            v4rem = v4[k]
            if v4rem == 0:
                v0 = np.append(v0,v4rem)
            elif v4rem > 0:
                v1 = np.append(v1,v4rem)
            v4 = v4temp
            D_un += 1
        #### Reaction 16: Unbind a M from v5
        elif event_kT < tot[15]:
            k = random.randrange(len(v5))
            v5temp = v5[np.arange(len(v5))!=k]
            v5rem = v5[k]
            v2 = np.append(v2,v5rem)
            v5 = v5temp
            M_un += 1
        #### Reaction 17: Unbind a D from v6
        elif event_kT < tot[16]:
            k = random.randrange(len(v6))
            v6temp = v6[np.arange(len(v6))!=k]
            v6rem = v6[k]
            v2 = np.append(v2,v6rem)
            v6 = v6temp
            D_un += 1
        #### Reaction 18: M catalysis for Mcat1 reaction in v3
        elif event_kT < tot[17]:
            k = random.randrange(len(v3))
            if v3[k] == 0:
                v3[k] += 1
        #### Reaction 19: M catalysis for Mcat2 reactions in v3
        elif event_kT < tot[18]:
            k = random.randrange(len(v3))
            if v3[k] == 1 or v3[k] == 2 or v3[k] == 3:
                v3[k] += 1
                if v3[k] > 3:
                    v5 = np.append(v5,v3[k])
                    v3 = v3[np.arange(len(v3))!=k]
        #### Reaction 20: D catalysis for v4
        elif event_kT < tot[19]:
            k = random.randrange(len(v4))
            v4[k] -= 1
            if v4[k] == 0:
                v4 = v4[np.arange(len(v4))!=k]
                v0 = np.append(v0,0)
        #### Reaction 21: M catalysis for v5
        elif event_kT < tot[20]:
            k = random.randrange(len(v5))
            v5[k] += 1
        #### Reaction 22: D catalysis for v6
        elif event_kT < tot[21]:
            k = random.randrange(len(v6))
            v6[k] -= 1
            if v6[k] == 3:
                v4 = np.append(v4,v6[k])
                v6 = v6[np.arange(len(v6))!=k]

    l0 = len(v0)
    l1 = len(v1)
    l2 = len(v2)
    l3 = len(v3)
    l4 = len(v4)
    l5 = len(v5)
    l6 = len(v6)
    l7 = max(v2)
    return l0, l1, l2, l3, l4, l5, l6, l7

if __name__ == '__main__':
    a = gillespie()
    scipy.io.savemat('ProcProc1.mat',dict(Smod=a[2]/10,Stot=sum(a)/10 - a[7]/10,lmax = a[7]))


import sys

input = sys.stdin.readline

N = int(input().rstrip())
sns = [[] for _ in range(51)]
for _ in range(N):
    sn = input().rstrip()
    total = 0
    for char in sn:
        if char.isdigit():
            total += int(char)
    sns[len(sn)].append([total, sn])
for i in range(1, 51):
    sns[i].sort()
    for sn in sns[i]:
        print(sn[1])


"""Webcam emotion recognition network test. Also doubles as data recorder."""
import os
import cv2
import click
import pandas as pd
# import numpy as np
from tensorflow.keras.models import load_model
from train import recall_m, precision_m, f1_m
from utils import preprocess_image, overlay_text, get_top_classes

@click.command()
@click.option('--data_path',
              default='data',
              help='Path to your data folder.')
@click.option('--model',
              default='models/best_model.h5',
              help='Path to your model file.')
@click.option('--n_top',
              default=3,
              help='How many of the resulting emotions to show.')
def main(**kwargs):
    """Load model, start webcam, run loop."""
    video_capture = cv2.VideoCapture(0)
    # variables for registering emotion recording
    emotions = ['neutral',
                'happy',
                'sad',
                'angry',
                'confused',
                'crosseyed']
    allowed_idx = list(range(len(emotions)))
    current_emotion = 0
    state = 'recording'  # recording | testing (network output)
    recording = False
    # some settings for printing on screen
    font = cv2.FONT_HERSHEY_SIMPLEX
    bottomLeftCornerOfText = (400, 450)
    fontScale = 0.7
    fontColor = (0, 255, 0)  # BGR because of opencv
    lineType = 2
    row_dy = 20
    # load the model with custom functions
    class_indices = {0: 'angry',
                     1: 'confused',
                     2: 'crosseyed',
                     3: 'happy',
                     4: 'neutral',
                     5: 'sad'}
    custom_objects = {'f1_m': f1_m,
                      'precision_m': precision_m,
                      'recall_m': recall_m}
    model = load_model(kwargs['model'],
                       custom_objects=custom_objects)

    # load previous data so we can add to it
    csv_path = os.path.join(kwargs['data_path'], 'all.csv')
    if os.path.exists(csv_path):
        df = pd.read_csv(csv_path, index_col=0)
    else:
        df = pd.DataFrame(columns=['path', 'emotion'])

    while True:
        ret, frame = video_capture.read()

        # record it if the user tells us to
        if state == 'recording' and recording:
            img_idx = df.index.max()
            if img_idx != img_idx:
                img_idx = 0
            else:
                img_idx += 1
            img_name = f'{emotions[current_emotion]}_{img_idx}.png'
            img_path = os.path.join(kwargs['data_path'], 'images', img_name)
            cv2.imwrite(img_path, frame)
            df = df.append(
                {'path': img_path, 'emotion': emotions[current_emotion]},
                ignore_index=True
            )

        emotion = emotions[current_emotion]
        if state == 'testing':
            # get the network output
            img = preprocess_image(frame)
            res = model.predict(img)
            top_res = get_top_classes(res, n=kwargs['n_top'])
            emotion = ''
            for sc_dict in top_res:
                emotion += str(round(sc_dict['score']*100, 2)) + '% '
                emotion += sc_dict['emotion'] + '\n'

        im2show = frame.copy()
        # display current emotion selected
        im2show = overlay_text(im2show, emotion, state,
                               recording, bottomLeftCornerOfText, font,
                               fontScale, fontColor, lineType, row_dy)
        cv2.imshow('Video', im2show)

        # control handling
        key = cv2.waitKey(1)
        if key & 0xFF == ord('q'):
            df.to_csv(csv_path)
            break
        elif key & 0xFF == ord('t'):
            if state == 'recording':
                state = 'testing'
            else:
                state = 'recording'
            print('Setting state to', state)
        elif key & 0xFF == ord('r'):
            if recording is True:
                recording = False
            else:
                recording = True
            print('Setting recording to', recording)
        # set emotion to record
        for idx in allowed_idx:
            if key & 0xFF == ord(str(idx)):
                print('Setting emotion recording to', emotions[idx])
                current_emotion = idx

    # When everything is done, release the capture
    video_capture.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
from uuid import UUID
from typing import List, Union

from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.backends.descriptor import BleakGATTDescriptor
from bleak.backends.dotnet.descriptor import BleakGATTDescriptorDotNet

# Import of BleakBridge to enable loading of winrt bindings
from BleakBridge import Bridge  # noqa: F401

from Windows.Devices.Bluetooth.GenericAttributeProfile import GattCharacteristic

# Python representation of <class 'Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties'>
# TODO: Formalize this to Enum for all backends.
_GattCharacteristicsPropertiesEnum = {
    None: ("None", "The characteristic doesn’t have any properties that apply"),
    1: ("Broadcast".lower(), "The characteristic supports broadcasting"),
    2: ("Read".lower(), "The characteristic is readable"),
    4: (
        "Write-Without-Response".lower(),
        "The characteristic supports Write Without Response",
    ),
    8: ("Write".lower(), "The characteristic is writable"),
    16: ("Notify".lower(), "The characteristic is notifiable"),
    32: ("Indicate".lower(), "The characteristic is indicatable"),
    64: (
        "Authenticated-Signed-Writes".lower(),
        "The characteristic supports signed writes",
    ),
    128: (
        "Extended-Properties".lower(),
        "The ExtendedProperties Descriptor is present",
    ),
    256: ("Reliable-Writes".lower(), "The characteristic supports reliable writes"),
    512: (
        "Writable-Auxiliaries".lower(),
        "The characteristic has writable auxiliaries",
    ),
}

class BleakGATTCharacteristicDotNet(BleakGATTCharacteristic):
    """GATT Characteristic implementation for the .NET backend"""

    def __init__(self, obj: GattCharacteristic):
        super().__init__(obj)
        self.__descriptors = [
            # BleakGATTDescriptorDotNet(d, self.uuid) for d in obj.GetAllDescriptors()
        ]
        self.__props = [
            _GattCharacteristicsPropertiesEnum[v][0]
            for v in [2 ** n for n in range(10)]
            if (self.obj.CharacteristicProperties & v)
        ]

    @property
    def service_uuid(self) -> str:
        """The uuid of the Service containing this characteristic"""
        return self.obj.Service.Uuid.ToString()

    @property
    def service_handle(self) -> int:
        """The integer handle of the Service containing this characteristic"""
        return int(self.obj.Service.AttributeHandle)

    @property
    def handle(self) -> int:
        """The handle of this characteristic"""
        return int(self.obj.AttributeHandle)

    @property
    def uuid(self) -> str:
        """The uuid of this characteristic"""
        return self.obj.Uuid.ToString()

    @property
    def properties(self) -> List:
        """Properties of this characteristic"""
        return self.__props

    @property
    def descriptors(self) -> List[BleakGATTDescriptorDotNet]:
        """List of descriptors for this service"""
        return self.__descriptors

    def get_descriptor(
        self, specifier: Union[int, str, UUID]
    ) -> Union[BleakGATTDescriptorDotNet, None]:
        """Get a descriptor by handle (int) or UUID (str or uuid.UUID)"""
        try:
            if isinstance(specifier, int):
                return next(filter(lambda x: x.handle == specifier, self.descriptors))
            else:
                return next(
                    filter(lambda x: x.uuid == str(specifier), self.descriptors)
                )
        except StopIteration:
            return None

    def add_descriptor(self, descriptor: BleakGATTDescriptor):
        """Add a :py:class:`~BleakGATTDescriptor` to the characteristic.

        Should not be used by end user, but rather by `bleak` itself.
        """
        self.__descriptors.append(descriptor)


# A - Darker and Darker
# https://atcoder.jp/contests/agc033/tasks/agc033_a

import numpy as np

H,W = map(int,input().split())
A = []
for i in range(H):
    A.append([0 if i == "#" else H + W for i in list(input())])
A = np.array(A)

for i in range(H-1):
  A[i+1, :] = np.minimum(A[i, :] + 1, A[i+1, :])
for i in range(H-1,0,-1):
  A[i-1,:] = np.minimum(A[i,:]+1,A[i-1,:])
for i in range(W-1):
  A[:,i+1] = np.minimum(A[:,i]+1,A[:,i+1])
for i in range(W-1,0,-1):
  A[:,i-1] = np.minimum(A[:,i]+1,A[:,i-1])
print(np.max(A))

"""
from collections import deque
H, W = map(int, input().split())
cs = []
q = deque()
s = set()
for h in range(H):
    cs.append(input())
    for w in range(W):
        if cs[h][w] == '#':
            s.add((h+1, w+1))
            q.append((h+1, w+1, 0))
vx = [0, 1, 0, -1]
vy = [1, 0, -1, 0]
ans = 0
# while len(s) < H * W:
# while len(q) > 0:
while q:
    y, x, n = q.popleft()
    for i in range(4):
        ny = y + vy[i]
        nx = x + vx[i]
        if ny >= 1 and ny <= H and nx >= 1 and nx <= W:
            if cs[ny-1][nx-1] == '.' and ((ny, nx) not in s):
                s.add((ny, nx))
                q.append((ny, nx, n+1))
                ans = max(ans, n+1)
print(ans)
"""

"""
H, W = map(int, input().split())
ans = 0
blk = []
for h in range(H):
    line = input()
    for w in range(W):
        if line[w] == '#':
            blk.append([h+1, w+1])
for h in range(H):
    for w in range(W):
        tmp = H + W
        if line[w] == '.':
            for y, x in blk:
                tmp = min(abs(h+1 - y) + abs(w+1 - x), tmp)
            ans = max(tmp, ans)
print(ans)
"""


import numpy as np
import random
import names
import copy
import sys
import time
from matplotlib import pyplot as plt
from matplotlib import animation

if len(sys.argv) < 4:
    print('---------------------------------')
    print('Need to get the parameters in the form of: ')
    print('number_of_cities(int) population_number_per_generation(int) mutation_rate(float, in percent) power_scoring(int)')
    print('For example: python this_script.py 15 100 80 2')
    print('---------------------------------')
    sys.exit()
else:
    num_cities=int(sys.argv[1])
    pop_number=int(sys.argv[2])
    mutation_rate=float(sys.argv[3])
    pow_score=int(sys.argv[4])

# Initialize random cities with random names

cities=[]
class City:
    def __init__(self,x,y,name):
        self.name=name
        self.x=x
        self.y=y

for i in range(num_cities):
    x=random.random()*100
    y=random.random()*100
    city=City(x,y,names.get_first_name())
    cities.append(city)

def dist_between(city1,city2):
    x_tmp=abs(city1.x-city2.x)
    y_tmp=abs(city1.y-city2.y)
    return np.sqrt(pow(x_tmp,2)+pow(y_tmp,2))

def crossover(ADN1,ADN2):
    cur_parrent=copy.copy(ADN1.list_cities),copy.copy(ADN2.list_cities)
    curr=0
    child=[]
    while len(child)<num_cities:
        if len(cur_parrent[curr])==1:
            child.append(cur_parrent[(curr+1)%2].pop(0))
            return ADN(child)
        i_ind=cur_parrent[curr].pop(0)
        j_ind=cur_parrent[curr].pop(0)
        child.append(i_ind)
        child.append(j_ind)
        cur_parrent[(curr+1)%2].remove(i_ind)
        cur_parrent[(curr+1)%2].remove(j_ind)
        curr=(curr+1)%2
    return ADN(child)

def get_tot_dist(cities_list):
    tot_dist=0
    for i in range(len(cities_list)-1):
        tot_dist+=dist_between(cities_list[i],cities_list[i+1])
    return tot_dist

def random_shuffle(array):
    res=[]
    l=len(array)
    while len(res)!=l:
        res.append(array.pop(random.randint(0,len(array)-1)))
    return res

class ADN:
    def __init__(self,cities):
        self.list_cities=cities
        self.fitness=0
        self.score=0

    def __str__(self):
        res=''
        for city in self.list_cities:
            res+=str(city.name)+'-->'
        return res[:-3]

    def mutate(self,mut_rate):
        if random.random() <= mut_rate/100:
            i= random.randint(0,len(self.list_cities)-1)
            j= random.randint(0,len(self.list_cities)-1)
            temp=self.list_cities[i]
            self.list_cities[i]=self.list_cities[j]
            self.list_cities[j]=temp

class Population:

    def __init__(self,N,mut_rate,popopow):
        self.N=N
        self.mut_rate=mut_rate
        self.pop=[]
        self.popopow=popopow

        for i in range(N):
            ind=ADN(random_shuffle(copy.copy(cities)))
            self.pop.append(ind)
        self.evaluate_fitness()

    def evaluate_fitness(self):
        sum_score=0
        for ind in self.pop:
            ind.score=get_tot_dist(ind.list_cities)
            sum_score+=1/pow(ind.score,self.popopow)
        for ind in self.pop:
            ind.fitness=1/pow(ind.score,self.popopow)/sum_score

    def pick(self):
        index=0
        selector=random.random()
        while selector > 0:
            selector-=self.pop[index].fitness
            index+=1
        index-=1
        return self.pop[index]

    def next_gen(self):
        new_pop=[]
        for i in range(self.N):
            parent1=self.pick()
            parent2=self.pick()
            child=crossover(parent1,parent2)
            child.mutate(self.mut_rate)
            new_pop.append(child)
        self.pop=new_pop

    def evaluate(self):
        best_fit=0
        best_ind=self.pop[0]
        for ind in self.pop:
            if ind.fitness > best_fit:
                best_fit= ind.fitness
                best_ind=ind
        return best_ind

    def overall_score(self):
        sum_score=0
        for ind in self.pop:
            sum_score+=ind.score
        return sum_score/pop_number

    def __call__(self):
        #make the next_generation and return the best ind of the new gen
        self.next_gen()
        self.evaluate_fitness()
        return self.evaluate(),self.overall_score()

# Genetic algorythm
pop=Population(pop_number,mutation_rate,pow_score)

# print the infos
fig=plt.figure(1)
ax = plt.axes(xlim=(0, 200), ylim=(0, 100))
plt.xticks([]), plt.yticks([])

line, = ax.plot([], [], marker="o",lw=2,color="green")
line2, = ax.plot([], [], marker="o", lw=2,color="red")

def frames():
    best_dist=float('inf')
    best_path=None
    gen=1
    while True:
        best_ind=pop()[0]
        best_score=best_ind.score
        oa_score=pop()[1]
        if (best_ind.score) < best_dist:
            best_dist=best_ind.score
            best_path=best_ind
        # print(best_score)
        gen+=1
        yield best_ind,best_path,oa_score,gen

def animate(args):
    x=[]
    y=[]
    x2=[]
    y2=[]
    for city in args[0].list_cities:
        x.append(city.x)
        y.append(city.y)
    for city in args[1].list_cities:
        x2.append(city.x+100)
        y2.append(city.y)
    line.set_data(x, y)
    line2.set_data(x2, y2)
    fig.suptitle('Current best (green): '+str(int(args[0].score))+'\n    Best of all (red): '+str(int(args[1].score)))
    return line,line2

anim = animation.FuncAnimation(fig, animate, frames=frames, interval=1)

# fig2=plt.figure(2)

# x=[]
# y=[]
# y2=[]

# def animate2(args):
#     x.append(args[3])
#     y.append(args[2])
#     y2.append(args[0].score)
#     plt.plot(x, y, color='g')
#     plt.plot(x, y2, color='orange')

# anim2 = animation.FuncAnimation(fig2, animate2, frames=frames, interval=1)

plt.show()


from flask import Flask, request, render_template
import numpy as np
import pandas as pd
import os
from tensorflow import keras
from keras.models import load_model
from keras.preprocessing import image
from werkzeug.utils import secure_filename
import random

app = Flask(__name__)

model = load_model('model.h5')
model.load_weights('model_weights.h5')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload')
def upload():
    return render_template('upload.html')

@app.route('/result', methods = ["POST"])
def result():
    name = request.form["fname"]
    sample_image = request.files['img']

    sample_image.save(secure_filename(sample_image.filename))

    img = image.load_img(sample_image.filename, target_size=(150, 150))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)

    images = np.vstack([x])
    classes = model.predict(images, batch_size=10)

    v = int(np.argmax(classes, axis = -1))
    k = float(np.max(classes, axis = -1))

    d = {0: 'Choroidal Neovascularization (CNV)', 1: 'Diabetic Macular Edema (DME)', 2: 'Drusen', 3: 'Normal'}

    if(v == 3):
        s = "The given retina is healthy with a confidence of {0:.2f}%".format((k*100)-random.randint(5,15))
    else:
        s = "The given retina has {0} with a confidence of {1:.2f}%".format(d[v], (k*100)-random.randint(5,15))

    return render_template('faq.html', n1 = name, s1 = s, p = v)

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


import unittest
import sys
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
from linear_algebra.vector import Vector
from linear_algebra.matrix import Matrix
from colorama import Fore

class TestVector(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print("\n[Exercice 04] Norm")
        print("----------------------------------------------------------------------")

    def setUp(self):
        print(Fore.YELLOW)
        print(self.shortDescription())
        print(Fore.RESET)
    def test_norm_1(self):
        """test manhattan norm
        """
        u = Vector([0., 0., 0.])
        norm = u.norm_1()
        self.assertEqual(norm, 0.0)
        print(f"u = {u.__str__()}\nmanhattan norm = {norm}\n")

        u = Vector([1., 2., 3.])
        norm = u.norm_1()
        self.assertEqual(norm, 6.0)
        print(f"u = {u.__str__()}\nmanhattan norm = {norm}\n")

        u = Vector([-1., -2.])
        norm = u.norm_1()
        self.assertEqual(norm, 3.0)
        print(f"u = {u.__str__()}\nmanhattan norm = {norm}\n")

        u = Vector([-1,-2,3,4,5])
        norm = u.norm_1()
        self.assertEqual(norm, 15.0)
        print(f"u = {u.__str__()}\nmanhattan norm = {norm}\n")
    def test_norm(self):
        """test euclidian norm
        """
        u = Vector([0., 0., 0.])
        norm = u.norm()
        self.assertEqual(norm, 0.0)
        print(f"u = {u.__str__()}\neuclidian norm = {norm}\n")

        u = Vector([1., 2., 3.])
        norm = u.norm()
        self.assertEqual(norm, 3.7416573867739413)
        print(f"u = {u.__str__()}\neuclidian norm = {norm}\n")

        u = Vector([-1., -2.])
        norm = u.norm()
        self.assertEqual(norm, 2.23606797749979)
        print(f"u = {u.__str__()}\neuclidian norm = {norm}\n")

    def test_norm_inf(self):
        """test infinity norm
        """
        u = Vector([0., 0., 0.])
        norm = u.norm_inf()
        self.assertEqual(norm, 0.0)
        print(f"u = {u.__str__()}\nsupremum norm = {norm}\n")

        u = Vector([1., 2., 3.])
        norm = u.norm_inf()
        self.assertEqual(norm, 3.0)
        print(f"u = {u.__str__()}\nsupremum norm = {norm}\n")

        u = Vector([-1., -2.])
        norm = u.norm_inf()
        self.assertEqual(norm, 2.0)
        print(f"u = {u.__str__()}\nsupremum norm = {norm}\n")


#!/usr/bin/env python

import struct
import io
import sys
import numpy as np

def evaluaFuncBool(char1,char2,char3,char4,char5):
    c_0 = (( char1 + char2 ) ^ ( char3 ^ char4 ) ^ char5);
    c_1 = (( char1 & char2 ) ^ ( char3 + char4 ) ^ char5);
    c_2 = (( char1 ^ char2 ) + ( char3 + char4 ) ^ char5);
    c_3 = (( char1 ^ char2 ) ^ ( char3 + char4 ) ^ char5);
    c_4 = (( char1 & char2 ) + ( char3 + char4 ) + char5);
    c_5 = (( char1 & char2 ) + ( char3 + char4 ) ^ char5);
    c_6 = (( char1 ^ char2 ) ^ ( char3 + char4 ) ^ char5);
    c_7 = (( char1 | char2 ) ^ ( char3 + char4 ) ^ char5);
    c_8 = (( char1 | char2 ) | ( char3 + char4 ) ^ char5);
    c_9 = (( char1 + char2 ) + ( char3 + char4 ) ^ char5);
    c_a = (( char1 + char2 ) & ( char3 + char4 ) ^ char5);
    c_b = (( char1 ^ char2 ) + ( char3 ^ char4 ) ^ char5);
    c_c = (( char1 | char2 ) ^ ( char3 ^ char4 ) ^ char5);
    c_d = (( char1 + char2 ) + ( char3 ^ char4 ) ^ char5);
    c_e = (( char1 + char2 ) ^ ( char3 + char4 ) ^ char5);
    c_f = (( char1 + char2 ) & ( char3 + char4 ) + char5);
    return c_0+c_1+c_2+c_3+c_4+c_5+c_6+c_7+c_8+c_9+c_a+c_b+c_c+c_d+c_e+c_f;

def conv(x):
    return np.uint64(x);

def rotate(x,o):
    o %= 64;
    x = conv(x);
    o = conv(o);
    return np.int64(x>>o);

def pad(data):
    length = len(data);
    tail = length % 64;
    if (64 - tail >= 9):
        padding = 64 - tail;
    else:
        padding = 128 - tail;

    pad = [np.int64(0) for i in range(padding)];
    pad[0] = np.int64(-0x80);
    bits = length * 8;
    for i in range(8):
        pad[padding - 1 - i] = ((bits >> (8 * i)) & 0xFF);

    out = [np.int64(0) for i in range(length+padding)];
    for i in range(length):
        out[i] = np.int64(data[i]);
    for i in range(padding):
        out[length+i] = pad[i];

    return out;

def longToBytes(l):
    result = [0 for i in range(8)];
    for i in range(7,-1,-1):
        result[i] = l & 0xFF;
        l >>= 8;
    return result;

class Azrael(object):

    def __init__(self):
        # Initial digest variables
        self._IV = (
            np.int64(0x6a09e667bb67ae85),
            np.int64(0x3c6ef372a54ff53a),
            np.int64(0x510e527f9b05688c),
            np.int64(0x1f83d9ab5be0cd19),
            np.int64(0x428a2f9871374491),
            np.int64(-0x4A3F0430164A245B),
            np.int64(0x3956c25b59f111f1),
            np.int64(-0x6DC07D5B54E3A12B),
            np.int64(-0x27F85567ED7CA4FF),
            np.int64(0x243185be550c7dc3),
        )

    def getHashEval(self,input):

        input = pad(input);
        length = len(input);

        char = [self._IV[0],self._IV[1],self._IV[2],self._IV[3],self._IV[4]];
        carrier = [self._IV[5],self._IV[6],self._IV[7],self._IV[8],self._IV[9]];

        a =2;
        b =3;
        c =4;
        d =5;

        char[0] += input[length-2];
        char[1] += input[length-1];
        char[2] += input[0];
        char[3] += input[1];
        char[4] += input[2];
        carrier[4] += rotate( carrier[3], d);
        carrier[3] += rotate( carrier[2], c);
        carrier[2] += rotate( carrier[1], b);
        carrier[1] += rotate( carrier[0], a);
        carrier[0] += evaluaFuncBool( char[0],char[1],char[2],char[3],char[4]);

        for i in range(1,length-1):
            char[0] += carrier[0];
            char[1] += char[2];
            char[2] += char[3];
            char[3] += input[i+1];
            char[4] += carrier[1];
            carrier[4] += rotate( carrier[3], (8*(i+3)+d));
            carrier[3] += rotate( carrier[2], (8*(i+2)+c));
            carrier[2] += rotate( carrier[1], (8*(i+1)+b));
            carrier[1] += rotate( carrier[0], (8*i+a));
            carrier[0] += evaluaFuncBool( char[0],char[1],char[2],char[3],char[4]);

        char[0] += carrier[0];
        char[1] += char[2];
        char[2] += char[3];
        char[3] += input[0];
        char[4] += carrier[1];
        carrier[4] += rotate( carrier[3],(32+d) );
        carrier[3] += rotate( carrier[2],(24+c) );
        carrier[2] += rotate( carrier[1],(16+b) );
        carrier[1] += rotate( carrier[0],(8+a) );
        carrier[0] += evaluaFuncBool( char[0],char[1],char[2],char[3],char[4]);

        carrier[0] += evaluaFuncBool( carrier[0],carrier[0],carrier[0],carrier[0],carrier[0]) + self._IV[0];
        carrier[1] += evaluaFuncBool( carrier[1],carrier[1],carrier[1],carrier[1],carrier[1]) + self._IV[1];
        carrier[2] += evaluaFuncBool( carrier[2],carrier[2],carrier[2],carrier[2],carrier[2]) + self._IV[2];
        carrier[3] += evaluaFuncBool( carrier[3],carrier[3],carrier[3],carrier[3],carrier[3]) + self._IV[3];
        carrier[4] += evaluaFuncBool( carrier[4],carrier[4],carrier[4],carrier[4],carrier[4]) + self._IV[3];

        mask1 = np.int64(0xffffffff);
        mask2 = np.int64(-0x1);

        hash = np.int64(0);
        hash = ((carrier[0] << 48) & mask2 ) | \
            (((carrier[0]+carrier[1]) << 32) & mask2 ) | \
            (((carrier[0]+carrier[1]+carrier[2]) << 16) & mask1) | \
            ((carrier[2]+carrier[3]+carrier[4]) & mask1);

        hash += evaluaFuncBool( hash,hash,hash,hash,hash) + self._IV[2];
        hash += evaluaFuncBool( hash,hash,hash,hash,hash) + self._IV[7];
        hash += length + 5 + 1 + 2;

        return longToBytes(hash);

def main():
    azrael = Azrael();
    output = azrael.getHashEval( bytearray(b'') );
    hex = ''.join('{:02x}'.format(i) for i in output);
    print(hex);

if __name__ == "__main__":
    main()


from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.shortcuts import redirect, render
from django.db.models import Q
from .models import Like, Skin
from .forms import SkinCreateForm

# Create your views here.
def index(request):
    query = request.GET.get('query')
    skinid = request.GET.get('skinid')

    if query:
        skins = Skin.objects.filter(
            Q(name__icontains=query) |
            Q(author__username__icontains=query) |
            Q(motif__icontains=query)
        )
    elif skinid:
        skins = Skin.objects.filter(
            skin_id=skinid
        )
    else:
        skins = Skin.objects.all()
    context = {
        'skins': skins,
        'current_user': request.user
    }

    return render(request, 'skins/index.html', context)

def detail(request, pk):
    skin = Skin.objects.get(pk=pk)
    likes_count = Like.objects.filter(skin=skin).count()
    is_author = skin.author == request.user
    context = {
        'skin': skin,
        'current_user': request.user,
        'likes_count': likes_count,
        'is_author': is_author,
    }
    return render(request, 'skins/detail.html', context)

@login_required
@transaction.atomic
def like(request, pk):
    skin = Skin.objects.get(pk=pk)
    if request.method == 'POST':
        try:
            like = Like.objects.get(user=request.user, skin=skin)
            like.delete()
            skin.like_count -= 1
            skin.save()
            return redirect('skins_detail', pk)
        except Like.DoesNotExist:
            Like.objects.create(user=request.user, skin=skin)
            skin.like_count += 1
            skin.save()
            return redirect('skins_detail', pk)

@login_required
def create(request):
    if request.method == 'POST':
        form = SkinCreateForm(request.POST, request.FILES)
        if form.is_valid():
            Skin.objects.create(author=request.user, **form.cleaned_data)
            return redirect('skins_index')
    else:
        form = SkinCreateForm()
        context = {
            'form': form,
            'current_user': request.user
        }
    return render(request, 'skins/create.html', context)

@login_required
def delete(request, pk):
    skin = Skin.objects.get(pk=pk)
    user = request.user
    if request.method == 'POST':
        if skin.author == user:
            skin.delete()
            print('success')
            return redirect('skins_index')
        else:
            print('no')
            return redirect('skins_index')
    else:
        print('not delete')
        return redirect('skins_index')


from aiogram.filters.callback_data import CallbackData
from enum import Enum

#  Values are shortened to minimize the size of the callback data.
class WalletAction(Enum):
    choose_action = "c_a"
    replenish = "rplnsh"
    get_amount = "g_a"
    check_paylink_status = "c_p_s"
    history = "hstr"
    history_document = "hstr_d"

class WalletCallbackData(CallbackData, prefix="wllt"):  # prefix="wallet"
    action: WalletAction | None = None
    amount: float | None = None
    order_id: str | None = None


import _kmeans
import numpy as np
import pytest
import cv2

def trans2image(labels, img, k):

    h, w = img.shape[0], img.shape[1]
    output = np.zeros((h, w, 3))
    for cls in range(k):
        idxs = np.where(labels == cls)[0]

        mean_color = 0.0
        for idx in idxs:
            y = idx // w
            x = idx % w
            #print(idx)
            mean_color += (img[y][x] / len(idxs))

        #print(mean_color.shape)
        for idx in idxs:
            y = idx // w
            x = idx % w
            output[y, x, :] = mean_color

    return output.astype(np.uint8)

def test_unit():
    k = 2
    gamma_c=0.6
    gamma_s=0.4
    max_iter=20
    thresh=0.001
    nthreads=4

    c = _kmeans.kmeans(k, gamma_c, gamma_s, max_iter, thresh, nthreads)
    c.set_verbose(True)

    assert c.k_cluster == k
    assert c.gamma_c == gamma_c
    assert c.gamma_s == gamma_s
    assert c.max_iter == max_iter
    assert c.nthreads == nthreads
    assert c.thresh == thresh

    # print(c.k_cluster)
    # print(c.gamma_c)
    # print(c.gamma_s)
    # print(c.max_iter)
    # print(c.nthreads)
    # print(c.thresh)

    #print("---------------------------------------")

    img = cv2.imread("./test.png")
    c.predict(img)
    #c.savefig("image1_result.png")

    result = c.get_results()
    assert result.shape[0] == img.shape[0] * img.shape[1]

    #print(result)
    output = trans2image(result, img, k)
    #print((output - img).sum())
    assert (np.abs(output - img)).sum() == 0.0

if __name__ == "__main__":
    test_unit()


from odoo import api, models, tools

class MailAlias(models.Model):
    _inherit = "mail.alias"

    @api.model
    @tools.ormcache()
    def get_aliases(self):
        aliases = {
            x["display_name"]
            for x in self.search_read([("alias_name", "!=", False)], ["display_name"])
        }
        IrConfigParamObj = self.env["ir.config_parameter"].sudo()
        catchall = "{}@{}".format(
            IrConfigParamObj.get_param("mail.catchall.alias"),
            IrConfigParamObj.get_param("mail.catchall.domain"),
        )
        aliases.add(catchall)
        return aliases

    @api.model_create_multi
    def create(self, vals_list):
        res = super().create(vals_list)
        self.clear_caches()
        return res

    def write(self, vals):
        res = super().write(vals)
        if "alias_name" in vals:
            self.clear_caches()
        return res

    def unlink(self):
        res = super().unlink()
        self.clear_caches()
        return res


'''
filter(func,interable)
功能：过滤数据
     把interable中每个元素拿到func函数中进行处理
        若函数返回Ture则保留，若返回False则丢弃
参数：
    func：自定义或内置函数
    interable：可迭代数据

返回值：保留下来的数据组成的迭代器
'''

#需求一  保留所有偶数 丢弃所有技术
list1 = [1,2,3,4,5,6,7,8,9]

#普通方法
oushu=[]
for i in list1:
    if i % 2 == 0:
        oushu.append(i)
print(oushu)

#使用filter过滤
def func(n):
    '''
    定义一个函数，判断n是基数还是偶数，基数返回False，偶数返回Ture
    :param n:
    :return:
    '''
    if n % 2 == 0:
        return True
    else:
        return False

res = filter(func,list1)     #使用filter函数过滤list1中数字
print(list(res),type(res))

#使用匿名函数优化
res1 = filter(lambda x:True if x%2==0 else False,list1)
print(list(res1))


from django.contrib import admin

# Register your models here.
from .models import Profesor
from .models import Universidad
from .models import Unidad,User
from .models import Config_pagina
from django.core.mail import send_mail

class UniversidadAdmin(admin.ModelAdmin):
    list_display = ('nombre', 'ciudad', 'provincia','logo')
    search_fields = ['nombre', 'ciudad', 'provincia']

class UnidadAdmin(admin.ModelAdmin):
    list_display = ('nombre','universidad')
    search_fields = ['nombre']

class ProfesorAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('nombre', 'apellido', 'apodo')
        }),
        ('Detalle', {
            'classes': ('collapse',),
            'fields': ('foto', 'linkedin', 'confirmado_flag', 'universidad', 'unidad','user')
        }),
    )

    def save_model(self,request,obj,form,change):
        user_id = int(request.POST['user'])
        user = User.objects.get(id=user_id)
        flag = request.POST['confirmado_flag']
        if flag == '1':
            send_mail('Recomendacion de Profesor', 'Su recomendacion fue acptada, ya puede calificar', 'carlosrodriguez.upe@gmail.com', [user.email])
            super(Profesor, obj).save()
        elif flag == '2':
            super(Profesor, obj).save()
        else:
            super(Profesor, obj).delete()
            send_mail('Recomendacion de Profesor', 'Su recomendacion sue rechazada', 'carlosrodriguez.upe@gmail.com', ['carlosrodriguez.upe@gmail.com'])
        #super(Profesor, obj).save()

class Config_paginaAdmin(admin.ModelAdmin):
    list_display = ('paginacion', 'top', 'recientes', 'populares')

admin.site.register(Universidad, UniversidadAdmin)
admin.site.register(Unidad, UnidadAdmin)
admin.site.register(Profesor, ProfesorAdmin)
admin.site.register(Config_pagina, Config_paginaAdmin)


from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.events import EVENT_JOB_EXECUTED,EVENT_JOB_ERROR
import datetime

from . import jobs
def start():

    scheduler = BackgroundScheduler()

    default_update_job = scheduler.add_job(jobs.default_update_job, 'interval', hours = 7)

    default_delete_job = scheduler.add_job(jobs.default_delete_job, 'interval', hours = 7)

    scheduler.add_listener(jobs.my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)

    scheduler.start()

def initial_job():
    now = datetime.datetime.now()
    now_plus_1 = now + datetime.timedelta(minutes=1)
    initscheduler = BackgroundScheduler()
    initscheduler.add_job(jobs.default_update_job,'date', run_date=now_plus_1)
    initscheduler.start()
    print("INITIAL JOB CALLED")


from numpy import argsort
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import xavier_normal_

from layers import LightGCNLayer, StackGCN, FactorizationMachine
from utils import get_norm_adj_mat
from .basemodel import BaseModel

class GraphCTR1(BaseModel):
    def __init__(self, args, dataset, inter_mat, user_feat_mat, item_feat_mat):
        super(GraphCTR1, self).__init__(args, dataset, user_feat_mat, item_feat_mat)

        # load parameters
        self.n_layers = args.n_layers
        self.dropout = args.dropout

        # define layer
        self.lightgcn = LightGCNLayer(self.n_users, self.n_items, self.embedding_size)

        self.user_GCNLayer = StackGCN(user_feat_mat.shape[1], self.embedding_size, self.n_layers)
        self.item_GCNLayer = StackGCN(item_feat_mat.shape[1], self.embedding_size, self.n_layers)

        self.u_attention = nn.Parameter(torch.empty(size=(self.n_users, 1)))
        self.i_attention = nn.Parameter(torch.empty(size=(self.n_items, 1)))

        # get adj matrix
        self.adj, self.adj_u, self.adj_i= get_norm_adj_mat(inter_mat, self.n_users, self.n_items)
        self.adj = self.adj.to(self.args.device)
        self.adj_u = self.adj_u.to(self.args.device)
        self.adj_i = self.adj_i.to(self.args.device)

        # define loss
        self.loss = nn.BCELoss()
        self.sigmoid = nn.Sigmoid()

        # parameters initialization
        self._init_weights()

        # storage variables for full sort evaluation acceleration
        self.restore_user_e = None
        self.restore_item_e = None

    def _init_weights(self):
        xavier_normal_(self.u_attention.data)
        xavier_normal_(self.i_attention.data)

    def forward(self):
        user_lightgcn_embeddings, item_lightgcn_embeddings = self.lightgcn(self.n_layers, self.adj)
        user_feature_embeddings = self.user_GCNLayer(self.user_feat_mat, self.adj_u, dropout=self.dropout)
        item_feature_embeddings = self.item_GCNLayer(self.item_feat_mat, self.adj_i, dropout=self.dropout)

        user_embeddings = self.u_attention * user_lightgcn_embeddings + (1 - self.u_attention) * user_feature_embeddings
        item_embeddings = self.i_attention * item_lightgcn_embeddings + (1 - self.i_attention) * item_feature_embeddings

        return user_embeddings, item_embeddings

    def calculate_loss(self, interaction):
        # clear the storage variable when training
        if self.restore_user_e is not None or self.restore_item_e is not None:
            self.restore_user_e, self.restore_item_e = None, None
        user, item, label = interaction[0], interaction[1], interaction[2]
        user = user.to(self.args.device)
        item = item.to(self.args.device)
        label = label.to(self.args.device)

        # get enhanced embedding
        user_embeddings, item_embeddings = self.forward()
        u_embeddings = user_embeddings[user]
        i_embeddings = item_embeddings[item]

        # get loss
        logits = torch.mul(u_embeddings, i_embeddings).sum(dim=1)
        output = self.sigmoid(logits)
        loss = self.loss(output, label)
        return loss

    def predict(self, user, item):
        if self.restore_user_e is None or self.restore_item_e is None:
            self.restore_user_e, self.restore_item_e = self.forward()

        u_embeddings = self.restore_user_e[user]
        i_embeddings = self.restore_item_e[item]

        output = torch.mul(u_embeddings, i_embeddings).sum(dim=1)
        return output

class GraphCTR2(BaseModel):
    def __init__(self, args, dataset, inter_mat, user_feat_mat, item_feat_mat):
        super(GraphCTR2, self).__init__(args, dataset, user_feat_mat, item_feat_mat)

        # load parameters
        self.n_layers = args.n_layers
        self.dropout = args.dropout

        # define layer
        self.user_GCNLayer = StackGCN(user_feat_mat.shape[1], self.embedding_size, self.n_layers)
        self.item_GCNLayer = StackGCN(item_feat_mat.shape[1], self.embedding_size, self.n_layers)

        self.u_attention = nn.Parameter(torch.empty(size=(self.n_users, 1)))
        self.i_attention = nn.Parameter(torch.empty(size=(self.n_items, 1)))

        self.FM_layer = FactorizationMachine(self.n_users,
                                             self.n_items,
                                             u_input_features=user_feat_mat.shape[1],
                                             i_input_features=item_feat_mat.shape[1],
                                             embedding_size=self.embedding_size)

        # get adj matrix
        self.adj, self.adj_u, self.adj_i= get_norm_adj_mat(inter_mat, self.n_users, self.n_items)
        self.adj = self.adj.to(self.args.device)
        self.adj_u = self.adj_u.to(self.args.device)
        self.adj_i = self.adj_i.to(self.args.device)

        # define loss
        self.loss = nn.BCELoss()
        self.sigmoid = nn.Sigmoid()

        # parameters initialization
        self._init_weights()

        # storage variables for full sort evaluation acceleration
        self.restore_user_fm = None
        self.restore_item_fm = None
        self.restore_user_gcn = None
        self.restore_item_gcn = None

    def _init_weights(self):
        xavier_normal_(self.u_attention.data)
        xavier_normal_(self.i_attention.data)

    def get_embedding(self, user, item):
        # first_fm_embedding： batch_size * 4
        first_fm_embedding = self.FM_layer.get_first_embedding(user, item, self.user_feat_mat, self.item_feat_mat)
        # second_fm_embedding： batch_size * 4 * embedding_size
        second_fm_embedding = self.FM_layer.get_second_embedding(user, item, self.user_feat_mat, self.item_feat_mat)

        # mlp_input_embedding: batch_size * (4 * embedding_size)
        batch_size = second_fm_embedding.shape[0]
        input_embedding = second_fm_embedding.view(batch_size, -1)

        # split interaction and feature embedding
        user_inter_embedding = input_embedding[:, :self.embedding_size]
        item_inter_embedding = input_embedding[:, self.embedding_size: 2 * self.embedding_size]
        user_feat_embedding = input_embedding[:, 2 * self.embedding_size: 3 * self.embedding_size]
        item_feat_embedding = input_embedding[:, 3 * self.embedding_size:]

        user_lightgcn_embeddings, item_lightgcn_embeddings = self.get_lightgcn_embedding(user_inter_embedding, item_inter_embedding)
        user_feature_embeddings = self.user_GCNLayer(user_feat_embedding, self.adj_u, dropout=self.dropout)
        item_feature_embeddings = self.item_GCNLayer(item_feat_embedding, self.adj_i, dropout=self.dropout)

        user_embeddings = self.u_attention * user_lightgcn_embeddings + (1 - self.u_attention) * user_feature_embeddings
        item_embeddings = self.i_attention * item_lightgcn_embeddings + (1 - self.i_attention) * item_feature_embeddings
        return first_fm_embedding, second_fm_embedding, user_embeddings, item_embeddings

    def get_lightgcn_embedding(self, user_inter_embedding, item_inter_embedding):
        all_embeddings = torch.cat([user_inter_embedding, item_inter_embedding], dim=0)
        embeddings_list = [all_embeddings]
        for layer_idx in range(self.n_layers):
            all_embeddings = torch.sparse.mm(self.adj, all_embeddings)
            embeddings_list.append(all_embeddings)
        lightgcn_all_embeddings = torch.stack(embeddings_list, dim=1)
        lightgcn_all_embeddings = torch.mean(lightgcn_all_embeddings, dim=1)

        user_lightgcn_embeddings, item_lightgcn_embeddings = torch.split(lightgcn_all_embeddings,
                                                               [self.n_users, self.n_items])
        return user_lightgcn_embeddings, item_lightgcn_embeddings

    def forward(self, user, item):
        first_fm_embedding, second_fm_embedding, user_embeddings, item_embeddings = self.get_embedding(user, item)

        # fm output: batch_size * 1
        y_fm = self.FM_layer(first_fm_embedding, second_fm_embedding)

        u_embeddings = user_embeddings[user]
        i_embeddings = item_embeddings[item]

        # get loss
        logits = torch.mul(u_embeddings, i_embeddings).sum(dim=1)
        y_gcn = self.sigmoid(logits)

        y = self.sigmoid(y_fm + y_gcn)
        return y.squeeze(-1)

    def calculate_loss(self, interaction):
        # if self.restore_user_gcn is not None or self.restore_item_gcn is not None or \
        #     self.restore_user_fm is not None or self.restore_item_fm is not None:
        #     self.restore_user_gcn, self.restore_item_gcn = None, None
        #     self.restore_user_fm, self.restore_item_fm = None, None

        user, item, label = interaction[0], interaction[1], interaction[2]
        user = user.to(self.args.device)
        item = item.to(self.args.device)
        label = label.to(self.args.device)

        output = self.forward(user, item)
        loss = self.loss(output, label)
        return loss

    def predict(self, user, item):
        user = user.to(self.args.device)
        item = item.to(self.args.device)
        return self.forward(user, item)


import scipy
import torch
from torch import nn
from torch.nn import functional as F
from torchvision import models
import numpy as np
from scipy import linalg
from scipy.stats import entropy

class GANLoss(nn.Module):
    """
    GAN loss calculator

    Variants:
      - non_saturating
      - hinge
    """
    def __init__(self, loss_type):
        super(GANLoss, self).__init__()
        self.loss_type = loss_type

    def forward(self, fake_scores, real_scores=None):
        if real_scores is None:
            # TODO: calculate generator loss (2 points)
            if self.loss_type == 'non_saturating':
                loss = -fake_scores.sigmoid().log().mean()
            else:  # hinge loss
                loss = -fake_scores.mean()

        else:
            # TODO: calculate discriminator loss (2 points)
            if self.loss_type == 'non_saturating':
                loss = -(real_scores.sigmoid().log() + (1 - fake_scores.sigmoid()).log()).mean()
            else:  # hinge loss
                loss = (1 - real_scores).relu().mean() + (1 + fake_scores).relu().mean()

        return loss

class ValLoss(nn.Module):
    """
    Calculates FID and IS
    """
    def __init__(self):
        super().__init__()
        self.inception_v3 = models.inception_v3(pretrained=True)
        self.inception_v3.eval()

        for p in self.inception_v3.parameters():
            p.requires_grad = False

    @torch.no_grad()
    def _features(self, x: torch.Tensor) -> torch.Tensor:
        # Preprocess data
        x = F.interpolate(x, size=(299, 299), mode='bilinear')
        x = (x - 0.5) * 2

        # N x 3 x 299 x 299
        x = self.inception_v3.Conv2d_1a_3x3(x)
        # N x 32 x 149 x 149
        x = self.inception_v3.Conv2d_2a_3x3(x)
        # N x 32 x 147 x 147
        x = self.inception_v3.Conv2d_2b_3x3(x)
        # N x 64 x 147 x 147
        x = self.inception_v3.maxpool1(x)
        # N x 64 x 73 x 73
        x = self.inception_v3.Conv2d_3b_1x1(x)
        # N x 80 x 73 x 73
        x = self.inception_v3.Conv2d_4a_3x3(x)
        # N x 192 x 71 x 71
        x = self.inception_v3.maxpool2(x)
        # N x 192 x 35 x 35
        x = self.inception_v3.Mixed_5b(x)
        # N x 256 x 35 x 35
        x = self.inception_v3.Mixed_5c(x)
        # N x 288 x 35 x 35
        x = self.inception_v3.Mixed_5d(x)
        # N x 288 x 35 x 35
        x = self.inception_v3.Mixed_6a(x)
        # N x 768 x 17 x 17
        x = self.inception_v3.Mixed_6b(x)
        # N x 768 x 17 x 17
        x = self.inception_v3.Mixed_6c(x)
        # N x 768 x 17 x 17
        x = self.inception_v3.Mixed_6d(x)
        # N x 768 x 17 x 17
        x = self.inception_v3.Mixed_6e(x)
        # N x 768 x 17 x 17
        x = self.inception_v3.Mixed_7a(x)
        # N x 1280 x 8 x 8
        x = self.inception_v3.Mixed_7b(x)
        # N x 2048 x 8 x 8
        x = self.inception_v3.Mixed_7c(x)
        # Adaptive average pooling
        x = self.inception_v3.avgpool(x)
        # N x 2048 x 1 x 1
        x = self.inception_v3.dropout(x)
        # N x 2048 x 1 x 1
        x = torch.flatten(x, 1)

        return x

    @torch.no_grad()
    def _classifier(self, x: torch.Tensor) -> torch.Tensor:
        # N x 2048
        x = self.inception_v3.fc(x)
        # N x 1000 (num_classes)
        x = F.softmax(x, dim=1)

        return x

    def calc_data(self, real_inputs: list, fake_inputs: list):
        real_features = []
        for real_inputs_batch in real_inputs:
            real_features_batch = self._features(real_inputs_batch)
            real_features.append(real_features_batch.detach().cpu().numpy())
        real_features = np.concatenate(real_features)

        fake_features = []
        fake_probs = []

        for fake_inputs_batch in fake_inputs:
            fake_features_batch = self._features(fake_inputs_batch)
            fake_probs_batch = self._classifier(fake_features_batch)

            fake_features.append(fake_features_batch.detach().cpu().numpy())
            fake_probs.append(fake_probs_batch.detach().cpu().numpy())

        fake_features = np.concatenate(fake_features)
        fake_probs = np.concatenate(fake_probs)

        return real_features, fake_features, fake_probs

    # This method incorporates the algorithm from https://github.com/mseitzer/pytorch-fid/blob/master/src/pytorch_fid/fid_score.py.
    @staticmethod
    def calc_fid(real_features, fake_features):

        mu1 = real_features.mean(axis=0)
        mu2 = fake_features.mean(axis=0)

        sigma1 = np.cov(real_features, rowvar=False)
        sigma2 = np.cov(fake_features, rowvar=False)

        diff = mu1 - mu2

        # Product might be almost singular.
        covmean, _ = linalg.sqrtm(sigma1 @ sigma2, disp=False)

        if not np.isfinite(covmean).all():
            eps = 1e-6
            print(f'fid calculation produces singular product; adding {eps} to diagonal of cov estimates')
            offset = np.eye(sigma1.shape[0]) * eps
            covmean = linalg.sqrtm((sigma1 + offset) @ (sigma2 + offset))

        # Numerical error might give slight imaginary component.
        if np.iscomplexobj(covmean):
            covmean = covmean.real

        tr_covmean = np.trace(covmean)

        return diff @ diff + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean

    # This method incorporates the algorithm from https://github.com/sbarratt/inception-score-pytorch/blob/master/inception_score.py.
    @staticmethod
    def calc_is(fake_probs):

        # Compute the mean kl-div.
        py = np.mean(fake_probs, axis=0)
        scores = []
        for i in range(fake_probs.shape[0]):
            pyx = fake_probs[i, :]
            scores.append(entropy(pyx, py))
        return np.exp(np.mean(scores))

    def forward(self, real_images: list, fake_images: list) -> torch.Tensor:
        real_features, fake_features, fake_probs = self.calc_data(real_images, fake_images)

        fid = self.calc_fid(real_features, fake_features)

        inception_score = self.calc_is(fake_probs)

        return fid, inception_score


from app.models import App
from hashlib import sha256
from datetime import datetime, timedelta
from django.conf import settings
from django.core.files.storage import default_storage
from PIL import Image
import uuid

class GetFileServices:

    SIZE = {
        'xl': 1280,
        'lg': 960,
        'md': 720,
        'sm': 480,
        'xs': 240,
        'avatar': 120,
    }

    def __init__(self, file_type, folder_name, extension, size):
        self.file_type = file_type
        self.folder_name = folder_name
        self.extension = extension
        self.size = size
        self.error = None

    def is_valid(self):
        return self.error is None

    def is_exist_default(self):
        path_storage = settings.MEDIA_ROOT + '%s/%s/default.%s'%(self.file_type, self.folder_name, self.extension)
        if (not default_storage.exists(path_storage)):
            return False
        return True

    def is_valid_size(self):
        return ( self.SIZE.get(self.size, False)
            or self.size == 'default' )

    def get_file(self):
        if(self.file_type == 'files' or self.file_type == 'videos'):
            return self.get_default_file()

        if(self.file_type == 'images'):
            if(not self.is_valid_size()):
                self.error = 'Invalid size'
                return None

            if (self.size == 'default'):
                return self.get_default_file()
            else:
                return self.get_file_by_size()

    def get_default_file(self):
        path_url = '/media/%s/%s/default.%s' % (self.file_type, self.folder_name, self.extension)
        return path_url

    def get_file_by_size(self):
        if(not self.is_exist_default()):
            return self.get_default_file()

        path_url = '/media/%s/%s/%s.%s' % (
            self.file_type,
            self.folder_name,
            self.size,
            self.extension)
        path_storage = settings.MEDIA_ROOT + '%s/%s/%s.%s'%(
            self.file_type,
            self.folder_name,
            self.size,
            self.extension)

        if (not default_storage.exists(path_storage)):
            self.resize_and_save_image(path_storage)

        return path_url

    def resize_and_save_image(self, path_storage):
        default_path_storage = settings.MEDIA_ROOT + '%s/%s/default.%s'%(
                self.file_type,
                self.folder_name,
                self.extension)
        image = Image.open(default_path_storage)
        resize_image = self.resize_image(image, self.SIZE.get(self.size))
        resize_image.save(path_storage)

    def resize_image(self, image, newWidth):
        width, height = image.size
        newHeight = (int)(newWidth * height / width)
        resized_image = image.resize((newWidth, newHeight))
        return resized_image


import streamlit as st
import pandas as pd
from spellchecker import SpellChecker

# Load the cleaned dataset
df2 = pd.read_csv("C:/Users/Mi/Downloads/Job Analytics/finalcleandata.csv")

# Fill missing skill columns with empty strings and create lowercase versions for searching
df2['Skills1'] = df2['Skills1'].fillna("")
df2["lower_skills1"] = df2['Skills1'].str.lower()
df2["lower_skills2"] = df2['Skills2'].str.lower()
df2["lower_skills3"] = df2['Skills3'].str.lower()
df2["lower_skills4"] = df2['Skills4'].str.lower()
df2["lower_skills5"] = df2['Skills5'].str.lower()
df2["lower_skills6"] = df2['Skills6'].str.lower()
df2["lower_skills7"] = df2['Skills7'].str.lower()

# Streamlit configuration
st.set_page_config(
    page_title="Job Analytics",
    page_icon="ðŸ’¼",
)

# Frontend header
html_temp = """

Job Analytics

"""
st.markdown(html_temp, unsafe_allow_html=True)

# Description of the search feature
st.markdown("
 Our search feature displays the most prevalent experience level, top workplace, and popular classes for a particular skill, along with the total number of jobs related to that skill.
", unsafe_allow_html=True)

# Load skills from a dictionary
with open('C:/Users/Mi/Downloads/Job Analytics/dictionary.txt') as f:
    skills = f.read().splitlines()

# Create a case-insensitive spell checker
spell = SpellChecker(language=None, case_sensitive=False)
spell.word_frequency.load_words(skills)

# Text input for skill search
text_search = st.text_input("**Search Skills**", value="")

if text_search:
    corrected_input = spell.correction(text_search)
    st.write(f'Searching for jobs related to: {corrected_input}')

    # Create masks for skills in different columns
    m1 = df2["lower_skills1"].str.contains(corrected_input)
    m2 = df2["lower_skills2"].str.contains(corrected_input)
    m3 = df2["lower_skills3"].str.contains(corrected_input)
    m4 = df2["lower_skills4"].str.contains(corrected_input)
    m5 = df2["lower_skills5"].str.contains(corrected_input)
    m6 = df2["lower_skills6"].str.contains(corrected_input)
    m7 = df2["lower_skills7"].str.contains(corrected_input)

    # Combine masks to get the search results
    df_search = df2[m1 | m2 | m3 | m4 | m5 | m6 | m7]
    df_search = df_search.reset_index(drop=True)
    df_search.index += 1

    if corrected_input:
        col1, col2 = st.columns(2)
        with col1:
            st.markdown('
Most Common Experience Level :
', unsafe_allow_html=True)
            st.markdown('
Most Common Workplace :
', unsafe_allow_html=True)
            st.markdown('
Most Common Classes :
', unsafe_allow_html=True)
            st.markdown('
Total Number of Jobs Available :
', unsafe_allow_html=True)
        with col2:
            exp = df_search['Experience Category'].mode()[0]
            st.markdown(f'
{exp}
', unsafe_allow_html=True)

            loc = df_search['Locations'].mode()[0]
            st.markdown(f'
{loc}
', unsafe_allow_html=True)

            cls = df_search['Cluster'].mode()[0]
            st.markdown(f'
{cls}
', unsafe_allow_html=True)

            num_jobs = str(len(df_search))
            st.markdown(f'
{num_jobs}
', unsafe_allow_html=True)

# Display job details
st.markdown(
    """

    """,
    unsafe_allow_html=True,
)

if st.button("Job Details >>"):
    data = pd.concat([df_search['Company'], df_search['Designation'], df_search['Locations'].rename("Workplace"),df_search['HR_Name'].rename("HR Name"),df_search['Experience'],df_search['Link'].rename("Apply Link")], axis=1)
    st.write(data)

    # Card style for displaying job details
    card_style = """

    """
    st.markdown(card_style, unsafe_allow_html=True)

    # Loop through records and create job cards
    for index, row in data.iterrows():
        card = """

Company Name  :  {}

Designation    :  {}

Workplace      :  {}

HR Name        :  {}

Experience     :  {}

            Click Here to Apply

        """.format(row['Company'], row['Designation'], row['Workplace'], row['HR Name'], row['Experience'], link=row['Apply Link'])

        st.markdown(card, unsafe_allow_html=True)


from django.urls import path
from app.views.admin import AdminView
from app.views.users import UserView
from app.views.user_second_view import SecondUserView

# Admin
urlpatterns = [
    # API: Add an advisor
    path('admin/advisor/', AdminView.as_view(), name='admin-advisor'),
]

# Users
urlpatterns += [
    # API: Can register as a user
    path('user/register/', UserView.as_view(), name='user-register'),
    path('user/login/', SecondUserView.as_view({'post': 'user_login'}), name='login'),
    path('user/<int:user_id>/advisor/', SecondUserView.as_view({'get': 'get_list_advisor'}), name="get_list_advisor"),
    path("user/<int:user_id>/advisor/<int:advisor_id>/", SecondUserView.as_view({'post': 'calls_booking'}), name="calls_booking"),
    path("user/<int:user_id>/advisor/booking/", SecondUserView.as_view({'get': 'booked_calls'}), name="")
]


from typing import Optional, Tuple
from unicodedata import normalize as unicode_normalize

from ._phonetic import _Phonetic

__all__ = ['Waahlin']

class Waahlin(_Phonetic):
    """Wåhlin code.

    Wåhlin's first-letter coding is based on the description in
    :cite:`Erikson:1997`.

    .. versionadded:: 0.3.6
    """

    def __init__(self, encoder: Optional[_Phonetic] = None) -> None:
        """Initialize Waahlin instance.

        Parameters
        ----------
        encoder : _Phonetic
            An initialized phonetic algorithm object

        .. versionadded:: 0.4.0

        """
        self._encoder = encoder

    _transforms = {
        3: {'SCH': '*', 'STJ': '*', 'SKJ': '*'},
        2: {
            'AE': 'E',
            'CH': 'K',
            'DJ': 'J',
            'GJ': 'J',
            'HJ': 'J',
            'HV': 'V',
            'HW': 'V',
            'HR': 'R',
            'KJ': '+',
            'LJ': 'J',
            'PH': 'F',
            'QU': 'KV',
            'SJ': '*',
            'TJ': '+',
        },
        1: {'Q': 'K', 'W': 'V', 'Z': 'S', 'Ä': 'E'},
    }

    def _encode_next(self, word: str) -> Tuple[str, str]:
        if word[:3] == 'STI' and word[3:4] in {'E', 'Ä'}:
            code = '*'
            remainder = word[3:]
        elif word[:3] in self._transforms[3]:
            code = self._transforms[3][word[:3]]
            remainder = word[3:]
        elif word[:2] == 'HI' and word[2:3] in {
            'A',
            'E',
            'I',
            'O',
            'U',
            'Y',
            'Å',
            'Ä',
            'Ö',
        }:
            code = 'J'
            remainder = word[2:]
        elif word[:2] == 'SK' and word[2:3] in {'E', 'I', 'Y', 'Ä', 'Ö'}:
            code = '*'
            remainder = word[2:]
        elif word[:2] in self._transforms[2]:
            code = self._transforms[2][word[:2]]
            remainder = word[2:]
        elif word[:1] == 'C' and word[1:2] in {'E', 'I', 'Y', 'Ä'}:
            code = 'S'
            remainder = word[1:]
        elif word[:1] == 'G' and word[1:2] in {'E', 'I', 'Y', 'Ä', 'Ö'}:
            code = 'J'
            remainder = word[1:]
        elif word[:1] == 'I' and word[1:2] in {
            'A',
            'E',
            'I',
            'O',
            'U',
            'Y',
            'Å',
            'Ä',
            'Ö',
        }:
            code = 'J'
            remainder = word[1:]
        elif word[:1] == 'K' and word[1:2] in {'E', 'I', 'Y', 'Ä', 'Ö'}:
            code = '+'
            remainder = word[1:]
        elif word[:1] in self._transforms[1]:
            code = self._transforms[1][word[:1]]
            remainder = word[1:]
        else:
            code = word[:1]
            remainder = word[1:]

        return code, remainder

    def encode_alpha(self, word: str) -> str:
        """Return the alphabetic Wåhlin code for a word.

        Parameters
        ----------
        word : str
            The word to transform

        Returns
        -------
        str
            The alphabetic Wåhlin code value

        Examples
        --------
        >>> pe = Waahlin()
        >>> pe.encode_alpha('Christopher')
        'KRISTOFER'
        >>> pe.encode_alpha('Niall')
        'NJALL'
        >>> pe.encode_alpha('Smith')
        'SMITH'
        >>> pe.encode_alpha('Schmidt')
        'ŠMIDT'

        .. versionadded:: 0.4.0

        """
        return (
            self.encode(word, alphabetic=True)
            .replace('+', 'Ç')
            .replace('*', 'Š')
        )

    def encode(self, word: str, alphabetic: bool = False) -> str:
        """Return the Wåhlin code for a word.

        Parameters
        ----------
        word : str
            The word to transform
        alphabetic : bool
            If True, the encoder will apply its alphabetic form (.encode_alpha
            rather than .encode)

        Returns
        -------
        str
            The Wåhlin code value

        Examples
        --------
        >>> pe = Waahlin()
        >>> pe.encode('Christopher')
        'KRISTOFER'
        >>> pe.encode('Niall')
        'NJALL'
        >>> pe.encode('Smith')
        'SMITH'
        >>> pe.encode('Schmidt')
        '*MIDT'

        .. versionadded:: 0.4.0

        """
        # uppercase, normalize, decompose, and filter non-A-Z out
        word = unicode_normalize('NFC', word.upper())
        if not word:
            return ''

        if self._encoder is None:
            code = ''
            while word:
                part, word = self._encode_next(word)
                code += part
            return code

        code, word = self._encode_next(word)
        return code + (
            self._encoder.encode_alpha(word)
            if alphabetic
            else self._encoder.encode(word)
        )

if __name__ == '__main__':
    import doctest

    doctest.testmod()


__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"

from typing import Dict, Iterable, Optional

import numpy as np
import tensorflow as tf
from jina import DocumentArray, Executor, requests
from jina.logging.logger import JinaLogger

class ImageTFEncoder(Executor):
    """
    :class:`ImageTFEncoder` encodes ``Document`` content from a ndarray,
    potentially B x (Height x Width x Channel) into a ndarray of `B x D`.

    Where `B` is the batch size and `D` is the Dimension.

    The :class:`ImageTFEncoder` wraps the models from
    `tensorflow.keras.applications`.
    <https://www.tensorflow.org/api_docs/python/tf/keras/applications>`_
    """

    def __init__(
        self,
        model_name: str = 'MobileNetV2',
        img_shape: int = 336,
        pool_strategy: str = 'max',
        traversal_paths: Iterable[str] = ('r',),
        batch_size: int = 32,
        device: str = '/CPU:0',
        *args,
        **kwargs,
    ):
        """
        :param model_name: the name of the model. Supported models include
            ``DenseNet121``, ``DenseNet169``, ``DenseNet201``,
            ``InceptionResNetV2``, ``InceptionV3``, ``MobileNet``,
            ``MobileNetV2``, ``NASNetLarge``, ``NASNetMobile``,
            ``ResNet101``, ``ResNet152``, ``ResNet50``, ``ResNet101V2``,
            ``ResNet152V2``, ``ResNet50V2``, ``VGG16``, ``VGG19``,
            ``Xception`` and etc. A full list can be find at
            <https://www.tensorflow.org/api_docs/python/tf/keras/applications#functions>`_
        :param img_shape: The shape of the image to be encoded.
        :param pool_strategy: the pooling strategy. Options are:
            - `None`: Means that the output of the model will be the 4D tensor
                output of the last convolutional block.
            - `avg`: Means that global average pooling will be applied to the
                output of the last convolutional block, and thus the output of
                the model will be a 2D tensor.
            - `max`: Means that global max pooling will be applied.
        :param traversal_paths: traversal path of the Documents, (e.g. 'r', 'c')
        :param batch_size: size of each batch
        :param device: Device ('/CPU:0', '/GPU:0', '/GPU:X')
        """
        super().__init__(*args, **kwargs)
        self.model_name = model_name
        self.pool_strategy = pool_strategy
        self.img_shape = img_shape
        self.batch_size = batch_size
        self.traversal_paths = traversal_paths
        self.logger = JinaLogger(self.__class__.__name__)

        gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
        if 'GPU' in device:
            gpu_index = 0 if 'GPU:' not in device else int(device.split(':')[-1])
            if len(gpus) < gpu_index + 1:
                raise RuntimeError(f'Device {device} not found on your system!')
        self.device = tf.device(device)

        with self.device:
            model = getattr(tf.keras.applications, self.model_name)(
                input_shape=(self.img_shape, self.img_shape, 3),
                include_top=False,
                pooling=self.pool_strategy,
                weights='imagenet',
            )
            model.trainable = False
            self.model = model

    @requests
    def encode(
        self, docs: Optional[DocumentArray] = None, parameters: Dict = {}, **kwargs
    ):
        """
        Encode document 'blob' into one-dimentional vector and store it into `embedding`.

        :param docs: `DocumentArray` containing `Document`s with the `blob` of image data
            in the size of `Height x Width x 3`. The `dtype` of the `blob` must be `float32`.
            The `blob` must be preprocessed to `[0, 1]`. Check out the preprocessed module of
            different models at https://www.tensorflow.org/api_docs/python/tf/keras/applications#functions
        :param parameters: dictionary to define the `traversal_paths` and the `batch_size`.
            For example, `parameters={'traversal_paths': ['r'], 'batch_size': 10}` will
            override the `self.traversal_paths` and `self.batch_size`.
        """
        if docs:
            document_batches_generator = docs.traverse_flat(
                traversal_paths=parameters.get('traversal_paths', self.traversal_paths),
                filter_fn=lambda doc: doc.blob is not None,
            ).batch(
                batch_size=parameters.get('batch_size', self.batch_size),
            )
            self._create_embeddings(document_batches_generator)

    def _create_embeddings(self, document_batches_generator: Iterable):
        for document_batch in document_batches_generator:
            blob_batch = np.stack([d.blob for d in document_batch])
            with self.device:
                embedding_batch = self.model(blob_batch)
            for document, embedding in zip(document_batch, embedding_batch):
                document.embedding = np.array(embedding)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr  8 23:35:22 2020

@author: smrahman
"""

#right angle

import turtle

board = turtle.Turtle()

board.forward(100) # draw base

board.left(90)
board.forward(100)

board.left(135) # angle (180-135)=45
board.forward(141.42) #use pythagorus 141.42

turtle.done()


import os
import errno
import scipy.io
import numpy as np
import pandas as pd
from open_ephys.analysis import Session

def load_OE_data(chosen_rat, CFG, session_iterator):
    ## Outputs all extracted continuous ephys data packed in a dictionary and the keys are unique session identifiers

    # initialize lists and counter variable(s)
    directory_list = CFG['data_dirs']['OE']
    number_of_recordings_per_session_list = []  # stores number of recordings found in each directory
    continuous_ephys_data_list = []             # stores continuous data
    list_of_session_IDs = [] # stores unique session identifiers
    iChosenRec = int(-1)                        # counts the number of recordings per directory

    for iSessionPath in directory_list: # loop through all paths provided
        session = Session(iSessionPath) # use OE library to extract data from path into a structured python format
        number_of_recordings_per_session_list.append((len(session.recordnodes[0].recordings))) # store number of recordings to allow next looping operation

        for iRec in range(number_of_recordings_per_session_list[-1]):
            # skip recording99
            if 'recording99' in session.recordnodes[0].recordings[iRec].directory:
                continue
            file_list = os.listdir(session.recordnodes[0].recordings[iRec].directory)
            chosen_recording = 0
            for filename in file_list:
                if filename.endswith(".info"):
                    for iterator in session_iterator:
                        session_date = CFG['rat'][chosen_rat]['session_date'][iterator]
                        rat_name = str(chosen_rat).lower()
                        treadmill_speed = str(CFG['rat'][chosen_rat]['treadmill_speed'][iterator]).zfill(2)
                        treadmill_incline = str(CFG['rat'][chosen_rat]['treadmill_incline'][iterator]).zfill(2)
                        session_ID = f"{session_date}_{rat_name}_speed{treadmill_speed}_incline{treadmill_incline}"
                        if filename.__contains__(session_ID):
                            recording_info = filename.split('.')[0]
                            list_of_session_IDs.append(recording_info.lower())
                            chosen_recording = 1
                            break
            if chosen_recording:
                # increment to track the number of chosen recordings
                # create list of session dates for the ones that were extracted
                iChosenRec += 1
                continuous_ephys_data_list.append(session.recordnodes[0].recordings[iRec].continuous)
                continuous_ephys_data_list[iChosenRec][0].samples = np.array(continuous_ephys_data_list[iChosenRec][0].samples,dtype='float64')

                for iChannel in range(session.recordnodes[0].recordings[iRec].info['continuous'][0]['num_channels']):
                    # Multiply each recording samples by the measured "bit_volts" value.
                    # This converts from 16-bit number to uV for continuous channels and V for ADC channels
                    continuous_ephys_data_list[iChosenRec][0].samples[:,iChannel] = continuous_ephys_data_list[iChosenRec][0].samples[:,iChannel]*session.recordnodes[0].recordings[iRec].info['continuous'][0]['channels'][iChannel]['bit_volts']
                continuous_ephys_data_list[iChosenRec][0].samples = np.array(continuous_ephys_data_list[iChosenRec][0].samples,dtype='float32')
                # set_trace()
    ## section plots the SYNC channel and describes stats of intervals
    # signal = continuous_ephys_data_list[iChosenRec][0].samples[:,iChannel]
    # fsignal = iir_notch(signal, 30000)
    # dsignal = np.digitize(fsignal,[-5,2,5])-1# digitize
    # peak_idxs, _ = find_peaks(dsignal, height=0.9)
    # df_fs_minus_fo = pd.DataFrame(peak_idxs[1:] - peak_idxs[:-1])
    # print(f"Stats:\n")
    # step_stats = df_fs_minus_fo.describe()[0]

    # from IPython.display import display
    # display(step_stats)
    # plt.plot(np.arange(len(signal))/30000, signal/3.3,c=[0,.4,.9,.5])
    # plt.plot(np.arange(len(dsignal))/30000,dsignal,c='black')
    # plt.scatter(peak_idxs/30000, dsignal[peak_idxs],c='r')
    # plt.xlabel("Time (s)")
    # plt.title(r'Checking Peaks for SYNC')
    # plt.show()
    if len(list_of_session_IDs) == 0:
        raise FileNotFoundError(
        errno.ENOENT, os.strerror(errno.ENOENT), "No '.info' file matching your criteria was found. It could be wrong rat, speed, incline, etc.")

    if len(continuous_ephys_data_list)==1:
        continuous_ephys_data_list = continuous_ephys_data_list[0]
    else:
        # remove unnecessary extra list dimension and convert to numpy.ndarray
        continuous_ephys_data_list = np.squeeze(continuous_ephys_data_list).tolist()
    OE_data_dict = dict(zip(list_of_session_IDs,continuous_ephys_data_list))
    print("Loaded OpenEphys files: ", OE_data_dict.keys())
    return OE_data_dict

def load_anipose_data(chosen_rat, CFG, session_iterator):
    ## Input all desired data paths as a list to extract anipose data from
    # directory_list = [
    #     '/home/sean/hdd/GTE-BME/SNEL/data/anipose/session220603',
    #     '/home/sean/hdd/GTE-BME/SNEL/data/anipose/session220606',
    #     '/home/sean/hdd/GTE-BME/SNEL/data/anipose/session220608']
    ## Outputs all extracted dataframes, with unique file identifiers as dictionary keys

    # function definitions
    def _read_pose_3d_data(path_to_pose_3d_csv):
        # print(f"Reading Anipose file(s) into DataFrame: {path_to_pose_3d_csv.name}")
        return path_to_pose_3d_csv.name, pd.read_csv(path_to_pose_3d_csv)

    def _filter_csv_files(chosen_rat, CFG, session_iterator_copy, directory_name):
        for iSess in session_iterator_copy:
            # format inputs to avoid ambiguities
            session_date = CFG['rat'][chosen_rat]['session_date'][iSess]
            rat_name = str(chosen_rat).lower()
            treadmill_speed = str(CFG['rat'][chosen_rat]['treadmill_speed'][iSess]).zfill(2)
            treadmill_incline = str(CFG['rat'][chosen_rat]['treadmill_incline'][iSess]).zfill(2)
            session_ID = f"{session_date}_{rat_name}_speed{treadmill_speed}_incline{treadmill_incline}"
            file_list = os.listdir(directory_name)
            for filename in file_list:
                if filename.endswith(".csv"):
                    if filename.__contains__(session_ID):
                        with open(os.path.join(directory_name, filename), "r") as csv_file:
                            yield _read_pose_3d_data(csv_file)
                        break

    # initialize lists
    # date_list = []                  # stores dates of each session
    list_of_session_IDs = []        # stores unique session identifiers
    list_of_pose_3d_dataframes = [] # stores all dataframes
    directory_list = CFG['data_dirs']['anipose']
    session_iterator_copy = session_iterator.copy()
    for directory_path in directory_list:
        pose_3d_path = os.path.join(directory_path,"pose-3d/")
        # if directory_list[iDir][-1] != os.path.sep:
        #     session_folder_name = directory_list[iDir].split(os.path.sep)[-1] # extract the last foldername
        # else:
        #     session_folder_name = directory_list[iDir].split(os.path.sep)[-2] # extract the last foldername (ignoring front slash)
        # session_date = session_folder_name[-6:] # extract the date from folder name
        # date_list.append(session_date)
        file_list = os.listdir(pose_3d_path)
        csv_file_list = []
        [csv_file_list.append(file_list[iFile]) for iFile in range(len(file_list)) if file_list[iFile].endswith('.csv')]
        for (session_ID, df) in _filter_csv_files(chosen_rat, CFG, session_iterator_copy, pose_3d_path):
            # add date string to filename, apply lowercase, remove '.csv' suffix, then append to list
            list_of_session_IDs.append(session_ID.lower().split('/')[-1].split('.')[0])
            list_of_pose_3d_dataframes.append(df)
    anipose_data_dict = dict(zip(list_of_session_IDs,list_of_pose_3d_dataframes))
    print("Loaded Anipose files:   ", anipose_data_dict.keys())
    return anipose_data_dict

def load_KS_data(chosen_rat, CFG, session_iterator):
    session_IDs_dict = {} # stores .info Session IDs of each recording in order under directory keys
    data_dir_list = CFG['data_dirs']['KS']
    session_iterator_copy = session_iterator.copy()
    for data_dir in data_dir_list:
        recording_lengths_arr_list = []
        num_channels_list = []
        spikeClusters_arr = []
        spikeTimes_arr = []
        clusterIDs = []
        session_IDs_temp = []
        chosen_rec_idxs_list = []
        session = Session(data_dir) # copy over structure.oebin from recording folder to recording99 folder or errors
        clusterIDs_ephys_spikeTimes = {}
        cluster_id_ephys_data_dict = {}
        for iRec in range((len(session.recordnodes[0].recordings))): # loops through all individual recording folders
            # skip recording99
            if 'recording99' in session.recordnodes[0].recordings[iRec].directory:
                continue
            timestamps_file = session.recordnodes[0].recordings[iRec].directory + "/continuous/Acquisition_Board-100.Rhythm Data/timestamps.npy"
            if not os.path.exists(timestamps_file):
                timestamps_file = session.recordnodes[0].recordings[iRec].directory + "/continuous/Rhythm_FPGA-100.0/timestamps.npy"
            num_channels_list.append(session.recordnodes[0].recordings[iRec].info['continuous'][0]['num_channels'])
            recording_lengths_arr_list.append(len(np.load(timestamps_file)) * num_channels_list[-1])
            temp_dir = os.listdir(session.recordnodes[0].recordings[iRec].directory)
            if any(".info" in file for file in temp_dir): # checks if .info file exists
                session_ID = [i for i in temp_dir if ".info" in i][0]
                # checks and filters for session_ID to match desired settings
                for iterator in session_iterator_copy:
                    session_date = CFG['rat'][chosen_rat]['session_date'][iterator]
                    rat_name = str(chosen_rat).lower()
                    treadmill_speed = str(CFG['rat'][chosen_rat]['treadmill_speed'][iterator]).zfill(2)
                    treadmill_incline = str(CFG['rat'][chosen_rat]['treadmill_incline'][iterator]).zfill(2)
                    session_ID_CFG = f"{session_date}_{rat_name}_speed{treadmill_speed}_incline{treadmill_incline}"
                    if session_ID.__contains__(session_ID_CFG):
                        session_IDs_temp.append(session_ID.split('.')[0])
                        chosen_rec_idxs_list.append(iRec)
                        # remove the index value after a match so you don't waste search loops in the future
                        session_iterator_copy.remove(iterator)
                        break
                    else:
                        continue
            else:
                print(session.recordnodes[0].recordings[iRec].directory + "has no .info file")
                return
        if len(session_IDs_temp)==0:
            continue
        session_IDs_dict[data_dir] = session_IDs_temp # adds list of session IDs to dict under directory key

        # below divides each recording by the appropriate divisor
        # (divisor = number of channels in recording, which can be different by experimental error)
        recording_lengths_arr = np.array(recording_lengths_arr_list)/np.array(num_channels_list)
        concatenated_data_dir = os.path.abspath(os.path.join(session.recordnodes[0].recordings[-1].directory, os.pardir,'concatenated_data'))
        if not os.path.exists(concatenated_data_dir):
            concatenated_data_dir = session.recordnodes[0].recordings[-1].directory # folder which contains all session data combined
        print(f"Using {concatenated_data_dir} folder.")
        if "sorted0" in os.listdir(data_dir):
            kilosort_files = []
            kilosort_folder = os.path.join(data_dir,"sorted0")
            if "custom_merges" in os.listdir(kilosort_folder):
                # grab final merge output
                kilosort_files.append(os.path.join(kilosort_folder, "custom_merges/final_merge/custom_merge.mat"))
            else:
                # grab raw KS output
                kilosort_files.append(os.path.join(kilosort_folder, "spike_clusters.npy"))
                kilosort_files.append(os.path.join(kilosort_folder, "spike_times.npy"))
                if len(kilosort_files) != 2:
                    print("KiloSort Spike Times and/or Spike Clusters not found!")
                    return
        elif "KilosortResults" in os.listdir(concatenated_data_dir):
            kilosort_files = []
            kilosort_folder = concatenated_data_dir + "/KilosortResults"
            for root, dirs, files in os.walk(kilosort_folder):
                if "spike_clusters.npy" in files and "spike_times.npy" in files:
                    kilosort_files.append(os.path.join(root, "spike_clusters.npy"))
                    kilosort_files.append(os.path.join(root, "spike_times.npy"))
                    if len(kilosort_files) != 2:
                        print("KiloSort Spike Times and/or Spike Clusters not found!")
                        return
        else:
            print("No folder named 'KilosortResults' in " + concatenated_data_dir + " or sorted0 folder with custom_merge.mat")
            print("If above error statement does not contain 'recording99' please make a folder with same name which contains Kilosort Results folder")
            raise FileNotFoundError()
        if ".npy" in kilosort_files[0]:
            spikeClusters_arr = np.load(kilosort_files[0]).ravel()
            spikeTimes_arr = np.load(kilosort_files[1]).ravel()
            # spikeClusters_arr = np.concatenate(spikeClusters)
            # spikeTimes_arr = np.concatenate(spikeTimes)
        elif ".mat" in kilosort_files[0]:
            spikeData = scipy.io.loadmat(kilosort_files[0])
            spikeClusters_arr = np.concatenate(spikeData['I'])
            spikeTimes_arr = np.concatenate(spikeData['T'])
        clusterIDs = np.unique(spikeClusters_arr)
        spikeTimes_arr = np.int32(spikeTimes_arr)
        # print("spikeTimes_arr[0]: ",spikeTimes_arr[0])
        # print(16 * (spikeTimes_arr[-1] - spikeTimes_arr[0]))

        # take cumsum to use later for recording file index boundaries
        recording_len_cumsum = np.insert(recording_lengths_arr.cumsum(),0,0).astype(int)
        cluster_id_ephys_data_dict = dict.fromkeys(tuple(*session_IDs_dict.values()))
        for (session_ID, iChosen) in zip(session_IDs_dict[data_dir],chosen_rec_idxs_list):
            clusterIDs_ephys_spikeTimes = clusterIDs_ephys_spikeTimes.copy()
            for id in clusterIDs:
                clusterIDs_ephys_spikeTimes_id_all = spikeTimes_arr[np.where(spikeClusters_arr==id)]
                clusterIDs_ephys_spikeTimes[id] = clusterIDs_ephys_spikeTimes_id_all[
                    # filter time ranges to be within the chosen session, and subtract the lower bound index
                    np.where((clusterIDs_ephys_spikeTimes_id_all>recording_len_cumsum[iChosen]) &
                             (clusterIDs_ephys_spikeTimes_id_all<recording_len_cumsum[iChosen+1]))] - recording_len_cumsum[iChosen]
            cluster_id_ephys_data_dict[session_ID] = clusterIDs_ephys_spikeTimes
        print("Loaded KiloSort files:  ", cluster_id_ephys_data_dict.keys())

        ## NEED TO USE RECORDING LENGTH ARRAY TO DIVIDE UP CONCATENATED DATA INTO SESSIONS
        ## THEN MAKE DICTIONARY IN FORM OF SESSIONID -> CLUSTERID -> SPIKETIMES ARRAY (WITH RESPECT TO LENGTHS OF EACH RECORDING)
    return cluster_id_ephys_data_dict


import collections
import re

def process_lists(file):
    with open(file, "r") as f:
        content_list = f.read().splitlines()
        return list(map(str.rstrip, content_list))

def count_legal_language(text, language):
    if language == 'es':
        legal_tokens = process_lists(
            './data/vocab-lists/ES-legal-penal(UTF8).txt')
    else:
        return 0
    return sum(1 for word in legal_tokens for _ in
               re.finditer(r'\b%s\b' % re.escape(word), text, re.IGNORECASE))

def count_medical_language(text, language):
    if language == 'ca':
        medical_tokens = process_lists('./data/vocab-lists/CA-med(UTF8).txt')
    elif language == 'es':
        medical_tokens = process_lists('./data/vocab-lists/ES-med(UTF8).txt')
    else:
        return 0
    return sum(1 for word in medical_tokens for _ in
               re.finditer(r'\b%s\b' % re.escape(word), text, re.IGNORECASE))

def count_most_common(text, language):
    if language == 'ca':
        most_common_tokens = process_lists(
            './data/vocab-lists/CA-8000_tokens_mas_frec_(UTF8).txt')
    elif language == 'es':
        most_common_tokens = process_lists(
            './data/vocab-lists/ES-10000_tokens_mas_frec_(UTF8).txt')
    else:
        return 0

    text_words = collections.Counter(re.split(r'\W+', text.lower()))
    # 1K
    count_1k = sum(filter(None, (text_words.get(word) for word in
                                 most_common_tokens[:1000])))
    # count_1k = sum(1 for word in most_common_tokens[:1000] for _ in
    #                re.finditer(r'\b%s\b' % re.escape(word), text,
    #                            re.IGNORECASE))

    # 1k 5k
    count_1k_5k = sum(filter(None, (text_words.get(word) for word in
                                    most_common_tokens[1000:5000])))
    # 5k  ...
    count_5k_10k = sum(filter(None, (text_words.get(word) for word in
                                     most_common_tokens[5000:])))

    return count_1k, count_1k_5k, count_5k_10k