# coding:utf-8
import sys
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
sys.path.append('../synthesize_blur')
import viz_flow as viz

data_dir = "./"

old_path = data_dir + "1.jpeg"
new_path = data_dir + "2.jpeg"

gap = [0, 100]

feature_params = dict(maxCorners=100000,
                      qualityLevel=0.001,
                      minDistance=10,
                      blockSize=7)

lk_params = dict(winSize=(15, 15),
                 maxLevel=3,
                 criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

def find_last(s, t):
        start = 0
        ret = -1
        while True:
            result = s.find(t, start)
            if result != -1:
                ret = result
            else:
                break
            start = result + 1
        return ret

def viz_lk(flow, path):
    H, W, _ = flow.shape
    f = np.abs(flow[:, :, 0]) + np.abs(flow[:, :, 1])
    f = (f - f.min()) / (f.max() - f.min()+1e-8)
    f *= 255
    f = cv2.GaussianBlur(f, (11, 11), 0)
    f = torch.FloatTensor(f).view(1, 1, H, W)
    f = F.max_pool2d(f, kernel_size=7, stride=7)
    f = f.squeeze().numpy()
    f = cv2.GaussianBlur(f, (5,5), 0)
    plt.imshow(f)
    plt.savefig(path)
    #plt.show()
    plt.clf()

    return f

def cal_lk(old_path, new_path):
    old_img = cv2.imread(old_path)
    H, W, _ = old_img.shape
    old_gray = cv2.cvtColor(old_img, cv2.COLOR_BGR2GRAY)
    new_img = cv2.imread(new_path)
    new_gray = cv2.cvtColor(new_img, cv2.COLOR_BGR2GRAY)
    print(old_img.shape)

    color = np.random.randint(0, 255, (100000, 3))
    mask = np.zeros_like(old_img)

    p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)
    p1, st, err = cv2.calcOpticalFlowPyrLK(
        old_gray, new_gray, p0, None, **lk_params)

    # select good points
    good_new = p1[st == 1]
    good_old = p0[st == 1]
    good = good_new - good_old

    flow = np.zeros((H, W, 2))
    for i, (new, old) in enumerate(zip(good_new, good_old)):
        a, b = new.ravel()
        c, d = old.ravel()
        gapx = abs(a-c)
        gapy = abs(b-d)
        if gapx >= gap[0] and gapy >= gap[0] and gapx <= gap[1] and gapy <= gap[1]:
            mask = cv2.line(mask, (a, b), (c, d), color[i].tolist(), 2)
            frame = cv2.circle(new_img, (a, b), 5, color[i].tolist(), -1)
            flow[int(d)-1, int(c)-1] = np.array((d-b, c-a))
    img = cv2.add(frame, mask)

    flag = find_last(new_path, '.')
    path = new_path[:flag] + '_flow.png'
    viz_lk(flow, path)

    # plot
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    #'''
    plt.subplot(221)
    plt.imshow(img)
    plt.subplot(222)
    plt.imshow(mask,  cmap=plt.cm.gray)
    plt.subplot(223)
    #'''

    good_x = good[:, 0]
    good_y = good[:, 1]
    good_x = good_x.clip(good_x.mean()-3*good_x.std(), good_x.mean()+3*good_x.std())
    good_y = good_y.clip(good_y.mean()-3*good_y.std(), good_y.mean()+3*good_y.std())
    n1, bins1, patches1 = plt.hist(
        good_x, bins=100, range=(good_x.min(), good_x.max()), density=False, facecolor='green', alpha=0.75)
    plt.subplot(224)
    n2, bins2, patches2 = plt.hist(
        good_y, bins=100, range=(good_y.min(), good_y.max()), density=False, facecolor='blue', alpha=0.75)
    plt.savefig(new_path[:flag] + '_total.png')
    #'''
    width = 0.02
    fig, ax = plt.subplots()
    n1 /= n1.sum()
    n2 /= n2.sum()

    rects1 = ax.bar(bins1[:-1], n1, width,
                    label="x displacement", lw=1, alpha=0.4, facecolor='orange')
    rects2 = ax.bar(bins2[:-1], n2, width,
                    label="y displacement", lw=1, alpha=0.4, facecolor='green')
    bin_min = min(bins1.min(), bins2.min())
    rects3 = ax.bar(bin_min, 0.3, width, lw=1, facecolor='blue', alpha=0.4, label='reference')
    plt.legend(loc="upper left")
    #'''
    #plt.show()
    plt.savefig(new_path[:flag] + '_hist.png')
    plt.clf()

def main(data_list):
    with open(data_list, 'r') as f:
        paths = f.readlines()
    count = 0
    for pair in paths:
        old_path, new_path = pair[:-1].split(' ')
        cal_lk(old_path, new_path)
        print(old_path)
        count += 1

if __name__ == '__main__':
    #data_list = './motion_trans.txt'
    data_list = './motion.txt'
    main(data_list)


"""
This file pretends to check the tables % available after the filter
"""

import pandas as pd
import os

def common_member(a, b):
    a_set = set(a)
    b_set = set(b)

    if (a_set & b_set):
        return a_set & b_set
    else:
        print("No common elements")

# Read the queries.txt tables

tables_q = pd.read_csv("experiments/data/benchmarks/table/queries.txt", sep="\t", header=None)
tables_q = tables_q.iloc[:,1].tolist()

tables_a = pd.read_csv("experiments/data/benchmarks/table/qrels.txt", sep="\t", header=None)
tables_a = tables_a.iloc[:,2].tolist()

tables_e = list(dict.fromkeys(tables_q + tables_a))

print("Total tables used in search experiment:", len(tables_e))

# Available tables after filter

tables_f = os.listdir("experiments/data/wikitables_clean")
print("Total wikitables after filter:", len(tables_f))
tables_f = list(map(lambda table: table.split(".")[0], tables_f))

tables_common = len(list(common_member(tables_e, tables_f)))

print("Total common tables:", tables_common,"-" , str(round(tables_common/len(tables_e) * 100, 2)) + "%")


import csv
import random
import numpy as np
from sklearn import preprocessing
import matplotlib.pyplot as plt
from keras.models import Sequential, Model
from keras.layers import Dense, LSTM, TimeDistributed, Conv2D, Flatten
from keras.optimizers import Adam
import utm

max_latitude = 330414.05273900216
max_longitude = 3463503.3311055717
min_latitude = 328787.97245886514
min_longitude = 3462203.7096695383

la_size = 16*2
lo_size = 13*2
la = (max_latitude - min_latitude)/la_size
lo = (max_longitude - min_longitude)/lo_size
print(lo)
print(la)

def coordinate_to_label(coordinate):
    la_label = int((coordinate[0] - min_latitude - 1e-12)/la)
    lo_label = int((coordinate[1] - min_longitude - 1e-12)/lo)
    tmp = np.zeros(la_size * lo_size, dtype=int)
    tmp[la_label + lo_label*la_size] = 1
    return tmp

def shuffle_train_test(X, Y, LEN, ratio):
    random.seed(1)
    random_list = random.sample(range(LEN), k=int(ratio*LEN))
    X_Train = []
    Y_Train = []
    X_Test = []
    Y_Test = []
    for i in range(LEN):
        if i in random_list:
            X_Test.append(X[i])
            Y_Test.append(Y[i])
        else:
            X_Train.append(X[i])
            Y_Train.append(Y[i])
    return np.array(X_Train), np.array(Y_Train), np.array(X_Test), np.array(Y_Test)

# lat, lon, 51 'R'
def check_validation(value_dict):
    validate_list = []
    validate_data = {
        'Latitude': value_dict['Latitude'],
        'Longitude': value_dict['Longitude'],
        'MRTime': value_dict['MRTime'],
        'TrajID': value_dict['TrajID']
    }
    if float(value_dict['Accuracy']) > 30:
        return False, validate_data

    for i in range(6):
        if value_dict['RNCID_' + str(i+1)] != '-999' and value_dict['CellID_' + str(i+1)] != '-999' and value_dict['Dbm_' + str(i+1)] != '-999' \
            and value_dict['AsuLevel_' + str(i+1)] != '-1' and value_dict['SignalLevel_' + str(i+1)] != '-1':

            validate_list.append(i)
            validate_data['RNCID_' + str(i+1)] = value_dict['RNCID_' + str(i+1)]
            validate_data['CellID_' + str(i+1)] = value_dict['CellID_' + str(i+1)]
            validate_data['Dbm_' + str(i+1)] = value_dict['Dbm_' + str(i+1)]
            validate_data['AsuLevel_' + str(i+1)] = value_dict['AsuLevel_' + str(i+1)]
            validate_data['SignalLevel_' + str(i+1)] = value_dict['SignalLevel_' + str(i+1)]

    if len(validate_list) < 3: # 我认为基站数量少于3，即理论上不可能得出手机坐标
        return False, validate_data
    else:
        for i in range(6):
            if i not in validate_list:
                np.random.seed(1)
                k = np.random.choice(validate_list)
                validate_data['RNCID_' + str(i+1)] = value_dict['RNCID_' + str(k+1)]
                validate_data['CellID_' + str(i+1)] = value_dict['CellID_' + str(k+1)]
                validate_data['Dbm_' + str(i+1)] = value_dict['Dbm_' + str(k+1)]
                validate_data['AsuLevel_' + str(i+1)] = value_dict['AsuLevel_' + str(k+1)]
                validate_data['SignalLevel_' + str(i+1)] = value_dict['SignalLevel_' + str(k+1)]
        return True, validate_data

# 按照轨迹ID进行切割
def cut_to_slices(X, Y, slice_length, LEN):
    tmp_count = 1
    tmp_X = []
    tmp_Y = []
    x_slice_list = []
    y_slice_list = []
    tmp_traj_label = int(X[0][1])
    for i in range(LEN):
        traj_id = int(X[i][1])
        if tmp_count == slice_length:
            if traj_id == tmp_traj_label:
                x_slice_list.append(X[i])
                y_slice_list.append(Y[i])
                tmp_X += x_slice_list
                tmp_Y += y_slice_list
                x_slice_list = []
                y_slice_list = []
                tmp_count = 1
                if (i+1) < LEN:
                    tmp_traj_label = int(X[i+1][1])
            else:
                x_slice_list.insert(0, X[i-slice_length])
                y_slice_list.insert(0, Y[i-slice_length])
                tmp_X += x_slice_list
                tmp_Y += y_slice_list
                x_slice_list = [X[i]]
                y_slice_list = [Y[i]]
                tmp_count = 2
                tmp_traj_label = traj_id
        else:
            if traj_id == tmp_traj_label:
                tmp_count += 1
                x_slice_list.append(X[i])
                y_slice_list.append(Y[i])
            else:
                x_slice_list = []
                y_slice_list = []
                for k in range(slice_length):
                    x_slice_list.append(X[i+k-slice_length])
                    y_slice_list.append(Y[i+k-slice_length])
                tmp_X += x_slice_list
                tmp_Y += y_slice_list
                x_slice_list = [X[i]]
                y_slice_list = [Y[i]]
                tmp_count = 2
                tmp_traj_label = traj_id
    return np.array(tmp_X), np.array(tmp_Y)

signal_tower_dict = {}
with open('../data/gongcan.csv', 'r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        coordinate = utm.from_latlon(float(row['Latitude']), float(row['Longitude']))[:2]
        signal_tower_dict[row['RNCID'] + '|' + row['CellID']] = coordinate

X = []
Y = []
features = 32
with open('../data/train_2g.csv', 'r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        validation, parsed_row = check_validation(row)
        if(not validation):
            continue
        coordinate = utm.from_latlon(float(parsed_row['Latitude']), float(parsed_row['Longitude']))[:2]
        Y.append([coordinate[0], coordinate[1]])
        mr_sample = np.zeros(features)
        mr_sample[0] = parsed_row['MRTime']
        mr_sample[1] = parsed_row['TrajID']
        for i in range(6):
            coordinate = signal_tower_dict[parsed_row['RNCID_' + str(i+1)] + '|' + parsed_row['CellID_' + str(i+1)]]
            mr_sample[i*5 + 2] = coordinate[0] # 转换成信号站的经纬度坐标
            mr_sample[i*5 + 3] = coordinate[1]
            mr_sample[i*5 + 4] = parsed_row['Dbm_' + str(i+1)]
            mr_sample[i*5 + 5] = parsed_row['AsuLevel_' + str(i+1)]
            mr_sample[i*5 + 6] = parsed_row['SignalLevel_' + str(i+1)]
        X.append(np.array(mr_sample))

LEN = len(X)
slice_length = 6

X = np.array(X).astype('float64')
Y = np.array(Y).astype('float64')

X, Y = cut_to_slices(X, Y, slice_length, LEN)
LEN = X.shape[0]

scalerX = preprocessing.StandardScaler()
X = scalerX.fit_transform(X)
X = X.reshape(round(LEN/slice_length), slice_length, features)
Y = Y.reshape(round(LEN/slice_length), slice_length, 2)

X_CNN, Y_CNN, X_LSTM, Y_LSTM = shuffle_train_test(X, Y, round(LEN/slice_length), 0.5)

X_CNN = X_CNN.reshape(X_CNN.shape[0]*X_CNN.shape[1], features)
X_LSTM = X_LSTM.reshape(X_LSTM.shape[0]*X_LSTM.shape[1], features)
Y_CNN = Y_CNN.reshape(Y_CNN.shape[0]*Y_CNN.shape[1], 2)
Y_LSTM = Y_LSTM.reshape(Y_LSTM.shape[0]*Y_LSTM.shape[1], 2)

X_CNN = np.delete(X_CNN, [1], axis=1) # 删除轨迹ID
X_LSTM = np.delete(X_LSTM, [1], axis=1)
X_CNN = np.delete(X_CNN, [0], axis=1) # CNN训练时，不需要时间戳
X_LSTM = np.delete(X_LSTM, [0], axis=1) # CNN训练时，不需要时间戳
X_CNN = X_CNN.reshape(X_CNN.shape[0], 6, 5)
X_LSTM = X_LSTM.reshape(X_LSTM.shape[0], 6, 5)
X_LSTM = X_LSTM[:, :, :, np.newaxis]
X_CNN = X_CNN[:, :, :, np.newaxis]

tmp_Y = []
for i in range(Y_CNN.shape[0]):
    tmp_Y.append(coordinate_to_label(Y_CNN[i]))
Y_CNN = np.array(tmp_Y)

adam_cnn = Adam(lr=2e-4, beta_1=0.9, beta_2=0.999, epsilon=None, decay=2e-9, amsgrad=False)
model_cnn = Sequential()

model_cnn.add(Conv2D(128, kernel_size=3, activation='relu', input_shape=(6, 5, 1)))
model_cnn.add(Conv2D(256, kernel_size=3, activation='relu'))
model_cnn.add(Flatten())
model_cnn.add(Dense(512, activation='relu'))
model_cnn.add(Dense(256, activation='relu'))
model_cnn.add(Dense(la_size*lo_size, activation='softmax'))

model_cnn.compile(optimizer=adam_cnn, loss='categorical_crossentropy', metrics=['accuracy'])
model_cnn.fit(X_CNN, Y_CNN, epochs=300, batch_size=64)
cnn_result = model_cnn.predict(X_LSTM)
print(cnn_result.shape) # 4710, 832

# def label_to_coordinate(label_list): # error!
#     label = np.argmax(label_list)
#     la_label = label % la_size
#     lo_label = (label - la_label) / la_size
#     return ((0.5+la_label)*la + min_latitude, (0.5+lo_label)*lo + min_longitude)

# def calcu_distance(true_latitude, true_longitude, pred_latitude, pred_longitude):
#     vector1 = np.array([true_latitude, true_longitude])
#     vector2 = np.array([pred_latitude, pred_longitude])
#     return np.sqrt(np.sum(np.square(vector1 - vector2)))

# error_list = []
# coordinate_result = []
# for i in range(cnn_result.shape[0]):
#     tmp = label_to_coordinate(cnn_result[i])
#     coordinate_result.append(tmp)
#     error = calcu_distance(Y_LSTM[i][0], Y_LSTM[i][1], tmp[0], tmp[1])
#     error_list.append(error)

# coordinate_result = np.array(coordinate_result)
# print(np.median(error_list)) # 这就是中位误差？
# print(np.mean(error_list)) # 这就是中位误差？

# plt.figure()
# plt.scatter(Y_LSTM[:,0], Y_LSTM[:,1], c='blue', s=5)
# plt.scatter(coordinate_result[:,0], coordinate_result[:,1], c='red', s=3)

# plt.show()

lstm_input = cnn_result
lstm_input = lstm_input.reshape(round(lstm_input.shape[0]/slice_length), slice_length, la_size*lo_size)
print(lstm_input.shape)

Y_LSTM = Y_LSTM.reshape(round(Y_LSTM.shape[0]/slice_length), slice_length, 2)
X_Train, Y_Train, X_Test, Y_Test = shuffle_train_test(lstm_input, Y_LSTM, lstm_input.shape[0], 0.1)

Y_Train = Y_Train.reshape(Y_Train.shape[0]*Y_Train.shape[1], 2)
tmp_Y = []
for i in range(Y_Train.shape[0]):
    tmp_Y.append(coordinate_to_label(Y_Train[i]))
Y_Train = np.array(tmp_Y)

Y_Train = Y_Train.reshape(round(Y_Train.shape[0]/slice_length), slice_length, la_size*lo_size)

adam_lstm = Adam(lr=5e-4, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-9, amsgrad=False)
model_lstm = Sequential()

model_lstm.add(LSTM(slice_length*20, input_shape=(X_Train.shape[1], X_Train.shape[2]), return_sequences=True))
model_lstm.add(TimeDistributed(Dense(2*la_size*lo_size, activation='relu')))
model_lstm.add(TimeDistributed(Dense(la_size*lo_size, activation='softmax')))
model_lstm.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer=adam_lstm)
model_lstm.fit(X_Train, Y_Train, epochs=100, batch_size=6)
lstm_result = model_lstm.predict(X_Test)
print(lstm_result.shape)
print(Y_Test.shape)

lstm_result = lstm_result.reshape(lstm_result.shape[0]*slice_length, lo_size*la_size)
Y_Test = Y_Test.reshape(Y_Test.shape[0]*slice_length, 2)

def label_to_coordinate(label_list): # error!
    label = np.argmax(label_list)
    # print(label)
    la_label = label % la_size
    lo_label = (label - la_label) / la_size
    return ((0.5+la_label)*la + min_latitude, (0.5+lo_label)*lo + min_longitude)

def calcu_distance(true_latitude, true_longitude, pred_latitude, pred_longitude):
    vector1 = np.array([true_latitude, true_longitude])
    vector2 = np.array([pred_latitude, pred_longitude])
    return np.sqrt(np.sum(np.square(vector1 - vector2)))

error_list = []
coordinate_result = []
error_dict = {
    '0': 0,
    '1': 0,
    '2': 0,
    '3': 0,
    '4': 0
}
for i in range(Y_Test.shape[0]):
    tmp = label_to_coordinate(lstm_result[i])
    coordinate_result.append(tmp)
    error = calcu_distance(Y_Test[i][0], Y_Test[i][1], tmp[0], tmp[1])
    if error <= 20:
        error_dict['0'] += 1
    elif error <= 40:
        error_dict['1'] += 1
    elif error <= 60:
        error_dict['2'] += 1
    elif error <= 80:
        error_dict['3'] += 1
    elif error <= 100:
        error_dict['4'] += 1
    error_list.append(error)

coordinate_result = np.array(coordinate_result)
error_list.sort()
print(np.median(error_list)) # 这就是中位误差？
print(np.mean(error_list)) # 这就是中位误差？
print(error_list[int(len(error_list)*0.9)]) # 90%误差

error_ratio = []
for i in range(5):
    if i > 0:
        error_dict[str(i)] += error_dict[str(i-1)]
    error_ratio.append(error_dict[str(i)]/len(error_list))

plt.figure('figure 1')
plt.scatter(Y_Test[:,0], Y_Test[:,1], c='blue', s=5)
plt.scatter(coordinate_result[:,0], coordinate_result[:,1], c='red', s=3)

plt.figure('figure 2')
plt.plot([20, 40, 60, 80, 100], error_ratio, marker='o')

plt.show()


# 2021.10.17
# 2966
# 찍기

a = ['A', 'B', 'C']
b = ['B', 'A', 'B', 'C']
c = ['C', 'C', 'A', 'A', 'B', 'B']
names = ['Adrian', 'Bruno', 'Goran']
results = [0, 0, 0]

n = int(input())
ans = input()
for i in range(n):
    if a[i % 3] == ans[i]:
        results[0] += 1
    if b[i % 4] == ans[i]:
        results[1] += 1
    if c[i % 6] == ans[i]:
        results[2] += 1

maxi = max(results)
print(maxi)
for i in range(3):
    if maxi == results[i]:
        print(names[i])


def convert(str1, str2):
    list1 = []
    list2 = []
    for i in range(0,len(str1)-1):
        list1.append(str1[i:i+2])
    for i in range(0,len(str2)-1):
        list2.append(str2[i:i+2])

    list1 = [i.lower() for i in list1 if i.isalpha()]
    list2 = [i.lower() for i in list2 if i.isalpha()]
    print(list1, list2)
    return list1,list2

def calculate(list1, list2):

    # A와 B가 공집합인 경우
    if not list1 and not list2:
        return 1

    # 중복되는 원소가 없는 경우
    elif len(list1) == len(set(list1)) and len(list2) == len(set(list2)):
        result1 = len(list(set(list1) & set(list2)))
        result2 = len(list(set(list1)|set(list2)))
        return result1 / result2

    # 중복되는 원소가 있는 경우
    else:
        dict1,dict2 = {},{}
        result1 = list(set(list1) & set(list2)) # 곱 원소 (only 1개)
        result2 = list(set(list1)|set(list2)) # 합 원소 (only 1개)
        len1 = len(result1)
        len2 = len(result2)

        for i in list1:
            if i in dict1:
                dict1[i] +=1
            else:
                dict1[i] = 1

        for i in list2:
            if i in dict2:
                dict2[i] +=1
            else:
                dict2[i] = 1

        for i in result1:
            if dict1[i]>1 or dict2[i]>1:
                len1 += min(dict1[i],dict2[i])-1
                continue

        for i in result2:
            if (i in list1) and (i not in list2):
                len2 += dict1[i]- 1
                continue
            elif (i in list2) and (i not in list1):
                len2 += dict2[i]- 1
                continue
            elif (i in list2) and (i in list1):
                len2 += max(dict1[i], dict2[i])-1
                continue
        return len1 / len2

def solution(str1, str2):
    list1,list2 = convert(str1, str2)
    similarity = calculate(list1,list2)
    return int(65536 * similarity)

프로그래머스/Level2/문제 해결 능력/뉴스 클러스터링.py


#Conversion function
def convert_bits(value, from_unit):
    #Dictionary to hold the conversion factors
    conversion_factors = {
        "bit": {
            "kbit": 1/1000,
            "kibibit": 1/1024,
            "kByte": 1/8000,
            "Kibibyte": 1/8192,
            "Mebibyte": 1/8589934592,
            "Mebibit": 1/1048576,
            "Mbit": 1/1000000
        }
    }
    #Checking if the input unit is valid or not
    if from_unit not in conversion_factors.keys():
        print("Invalid unit input")
        return
    #Iterating through the units
    for to_unit in conversion_factors[from_unit]:
        #Calculating the conversion
        quotient = value * conversion_factors[from_unit][to_unit]
        print(str(value) + " " + from_unit + " = " + str(quotient) + " " + to_unit)

#Taking input from user
value = int(input("Enter the value: "))
from_unit = input("Enter the unit (bit, kibibit, kByte, Kibibyte, Mebibyte, Mebibit, Mbit): ")

#Example usage
convert_bits(value, from_unit)


import os
import sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))

from definition import Node

def create_linked_list(array):
    """Creates a linked list from a list of items"""
    head = Node(value=array[0])
    current = head
    if len(array) > 1:
        for val in array[1:]:
            next_item = Node(value=val)
            current.next = next_item
            current = next_item
    return head


import random

def mod(a, m):
    """
    Взятие числа по модулю с бинарным поиском
    Бинарным поиском находится наибольшее частное от деления a / m,
    при котором (a - q * m) < m
    Тогда a - q * m = r (остаток)
    :param a: Число
    :type a: int
    :param m: Модуль
    :type m: int
    :return: Число по модулю
    :rtype: int
    """
    if m == 0:
        raise ValueError("Деление на 0!")
    if m == 1 or a == 0:
        return 0

    negative_dividend = False
    if a < 0:
        a = abs(a)
        negative_dividend = True

    negative_divisor = False
    if m < 0:
        m = abs(m)
        negative_divisor = True

    left = 0
    right = a
    while left < right:
        q = int((left + right) / 2)
        if a - q * m >= m:
            left = q + 1
        else:
            right = q
    res = a - left * m

    if negative_dividend and negative_divisor:
        return -res
    elif negative_dividend and not negative_divisor:
        return m - res
    elif not negative_dividend and negative_divisor:
        return res - m
    else:
        return res

def gcd(a, b):
    """
    НОД алгоритмом Евклида
    :param a: Первое число
    :type a: int
    :param b: Второе число
    :type b: int
    :return: НОД
    :rtype: int
    """
    if a == b == 0:
        raise ValueError("НОД(0, 0) не определен!")

    a = abs(a)
    b = abs(b)

    if a < b:
        a, b = b, a

    if b == 0:
        return a

    while b != 0:
        a, b = b, mod(a, b)
    return int(a)

def lcm(a, b):
    """
    Нахождение НОК с помощью НОД
    :param a: Первое число
    :type a: int
    :param b: Второе число
    :type b: int
    :return: НОК
    :rtype: int
    """
    if a == b == 0:
        raise ValueError("НОК(0, 0) не определен!")
    if a == 0 or b == 0:
        return 0

    a = abs(a)
    b = abs(b)

    res = int(a * (b / gcd(a, b)))
    return res

def fast_pow(a, b, m):
    """
    Быстрое возведение в степень по модулю
    Если показатель степени b делится на 2, то вызываем эту же функцию
    с показетелем степени b/2
    Если не делится, то с показателем b-1
    :param a: Основание степени
    :type a: int
    :param b: Показатель степени
    :type b: int
    :param m: Модуль
    :type m: int
    :return: Результат возведения в степень
    :rtype: int
    """
    if b < 0:
        raise ValueError(
            "Показатель степени должен быть натуральным числом или 0!")
    if b == 0:
        return 1
    if b == 1:
        return mod(a, m)

    a = mod(a, m)
    if mod(b, 2) == 0:
        res = fast_pow(a, int(b / 2), m)
        product = mod(res * res, m)
        return product
    else:
        res = fast_pow(a, b - 1, m)
        product = mod(a * res, m)
        return product

def prime_test_fermat(p, precision):
    """
    Тест Ферма на простоту числа
    :param p: Проверяемое число
    :type p: int
    :param precision: Количество чисел, которые будут использованы при проверке
    Чем больше чисел, тем больше точность
    :type precision: int
    :return: Является ли число простым?
    :rtype: bool
    """
    if p < 0:
        raise ValueError("Показатель степени должен быть натуральным числом!")
    if p == 2 or p == 3:
        return True
    if mod(p, 2) == 0:
        return False

    for i in range(precision):
        a = random.randint(2, p - 2)
        if gcd(a, p) != 1:
            continue
        if fast_pow(a, p - 1, p) != 1:
            return False
    return True

def carmichael_func(p, q):
    """
    Функция Кармайкла
    Для числа n = p * q, где p, q - простые, λ(n) = НОК(p - 1, q - 1)
    :param p: Первое простое число
    :type p: int
    :param q: Второе простое число
    :type q: int
    :return: Значение функции Кармайкла
    :rtype: int
    """
    lam = lcm(p - 1, q - 1)
    return lam

def ext_euclidean_alg(a, b):
    """
    Расширенный алгоритм Евклида
    :param a: Большее число
    :type a: int
    :param b: Меньшее число
    :type b: int
    :return: НОД, коэффициенты Безу
    :rtype: tuple
    """
    a = abs(a)
    b = abs(b)

    if a < b:
        a, b = b, a

    r_old, r = a, b
    x_old, x = 1, 0
    y_old, y = 0, 1

    while r != 0:
        q = int(r_old / r)
        r_old, r = r, r_old - q * r
        x_old, x = x, x_old - q * x
        y_old, y = y, y_old - q * y

    return r_old, x_old, y_old

def inverse_mod(a, m):
    """
    Нахождение обратного по модулю через расширенный алгоритм Евклида
    :param a: Число, к которому ищется обратное
    :type a: int
    :param m: Модуль
    :type m: int
    :return: Обратное
    :rtype: int
    """
    a = mod(a, m)
    d, x, y = ext_euclidean_alg(m, a)

    if d != 1:
        raise ValueError("НОД(a, m) ≠ 1, обратного значения не существует!")
    else:
        return mod(y, m)


from my_socket import *
# from myMath import *
import inspect
import myMath
from myMath import *
from my_inspect import *
import logging

def send_functions():
    global func_list
    global server

    func_info = []
    n = 0
    for f in func_list:
        func_info.append(';'.join([f['name'], f['info'], str(n)]))
        n += 1
    func_info = '\n'.join(func_info)
    server.send(func_info)

def send_objects():
    global vars_list
    global server

    obj_info = []
    n = 0
    for var in vars_list:
        obj_info.append(';'.join([str(var), str(type(var)), str(n)]))
        n += 1
    obj_info = '\n'.join(obj_info)
    server.send(obj_info)

def send_checked_objects():
    global server

    check_var_info_list = server.data.decode().split(':')[1].split('.')
    # as the message should be in the format of
    # co:index to check a preexisting var
    # and co:index.attribute to check an attribute that is an object
    # and co:index.name_of_list.index
    if len(check_var_info_list) == 1:
        check_preexisting_object(check_var_info_list)

    elif len(check_var_info_list) == 2:
        create_var_from_attribute(check_var_info_list)

    elif len(check_var_info_list) == 3:
        create_var_from_list_attribute(check_var_info_list)

def check_preexisting_object(check_var_info_list):
    global vars_list
    global server

    var_index = check_var_info_list[0]
    var = vars_list[int(var_index)]
    logging.debug("Checking %s" % (str(var)))
    # format: name;type;attr_name:type,value(s);attr_name:type,value(s)
    # type can be function, list, or any other type
    # if the type is a function, it will be added in the function view in unity
    var_name = str(var)
    var_type = str(type(var))
    var_attrs = []
    for key in var.__dict__:
        attr_name = key
        attr = var.__dict__[attr_name]
        if type(attr) == list:
            attr_type = 'list'
        else:
            attr_type = 'other'
        if attr == None:
            attr_values = "None"
        elif type(attr) == list:
            attr_values = ','.join([str(i) for i in attr])
        else:
            attr_values = str(attr)
        attr_info = "%s:%s,%s" % (attr_name, attr_type, attr_values)
        var_attrs.append(attr_info)
    for key in get_functions(var):
        attr_name = key
        attr_type = 'func'
        attr_values = key
        attr_info = "%s:%s,%s" % (attr_name, attr_type, attr_values)
        var_attrs.append(attr_info)

    var_attrs = ';'.join(var_attrs)
    var_info = "%s;%s;%s" % (var_name, var_type, var_attrs)
    print(var_info)
    server.send(var_info)

def create_var_from_attribute(check_var_info_list):
    global vars_list
    global server

    var_parent_index = check_var_info_list[0]
    var_parent = vars_list[int(var_parent_index)]
    attr_name = check_var_info_list[1]
    var = getattr(var_parent, attr_name)
    vars_list.append(var)
    server.send(str(len(vars_list)-1))

def create_var_from_list_attribute(check_var_info_list):
    global vars_list
    global server

    var_parent_index = check_var_info_list[0]
    var_parent = vars_list[int(var_parent_index)]
    list_name = check_var_info_list[1]
    var_list = getattr(var_parent, list_name)
    list_index = check_var_info_list[2]
    var = var_list[int(list_index)]
    vars_list.append(var)
    server.send(str(len(vars_list)-1))

def get_func_list():
    global func_list
    func_list = []
    for name, member in inspect.getmembers(myMath):
        # print(name, inspect.isclass(member), inspect.isfunction(member))
        if name.startswith("__"):
            continue
        elif inspect.isclass(member) or inspect.isfunction(member):
            #
            member_info = {
                'name': name,
                'func': member,
                'info': ' '.join(str(member.__doc__).strip().split('\n')),
            }

            func_list.append(member_info)
        vars_list.append(member)

def create_string():
    pass

def call_function():
    global server

    function_message = server.data.decode()[3:]
    function_info, parameters_index = function_message.split(":")
    function_info_list = function_info.split(".")
    logging.debug("Function Info: %s" % (function_info))
    logging.debug("Parameter Info: %s" % (parameters_index))

    if len(function_info_list) == 1:
        function_index = function_info_list[0]
        function = func_list[int(function_index)]['func']

    elif len(function_info_list) == 2:
        obj_index, function_name = function_info_list
        obj = vars_list[int(obj_index)]
        function = getattr(obj, function_name)

    logging.debug("function: %s" % (str(function)))

    if parameters_index != '':
        parameters_index_list = parameters_index.split(",")
        #     parameter_list = [vars_list[int(i)] for i in parameters_index_list]
        # except ValueError:
        parameter_list = []
        for p in parameters_index_list:
            try:
                parameter_list.append(vars_list[int(p)])
            except ValueError:
                parameter_list.append(p)
    else:
        parameter_list = []
    logging.debug("parameters: %s" % (', '.join([str(i) for i in parameter_list])))
    new_var = function(*parameter_list)
    if new_var != None:
        vars_list.append(new_var)
    server.send("success")

# func_list = [
#     {
#         'name': 'find inner conclusion',
#         'func': find_inner_conclusion,
#         'info': 'Takes two parameters: statement1 and statement2 and return a deduced statement if there is one.'
#     },
#     {
#         'name': 'find conclusion',
#         'func': find_conclusion,
#         'info': 'Takes two parameters: statement1 and statement2 and return a deduced statement if there is one.'
#     },
#     {
#         'name': 'Addition',
#         'func': Addition,
#         'info': 'Takes two parameters: a and b, returns a+b.'
#     },
#     {
#         'name': 'Multiplication',
#         'func': Multiplication,
#         'info': 'Takes two parameters: a and b, returns a*b.'
#     },
# ]

func_list = []
# vars_list = []

vars_list = [
    Variable('a'),
    Variable('b'),
    # Multiplication(vars_list[0], vars_list[1]),
]
t = Variable('t')
x = Substraction(t, Power(t, 2))
y = Substraction(t, Power(t, 3))
d = Derivative(y, x)
d.find_parametric_form(t)
d = d.equivalences[-1]
d.var1.general_prop_deduction()
d.var2.general_prop_deduction()
vars_list.extend([t, d, x, y])
logging.basicConfig(filename='example.log',level=logging.DEBUG)

server = socket_server('localhost', 50000)
server.accept_client()
logging.info('client accepted')
get_func_list()
while 1:
    try:
        server.receive_data()
        if server.data == b'get functions':
            logging.debug("Starting to send functions.")
            send_functions()
        elif server.data == b'get objects':
            logging.debug("Starting to send objects.")
            send_objects()
        elif server.data.decode().startswith("co:"):
            logging.debug("Starting to send checked objects.")
            send_checked_objects()
        elif server.data.decode().startswith("cf:"): # Call the function
            logging.debug("Starting to call a function.")
            call_function()
    except KeyboardInterrupt:
        server.close_client()


import sys
import os
import json
import threading

BASE_DIR = os.getcwd()+"/.."
EOF = ""

def setPlatformCfg(env):
    cfgPath = BASE_DIR+"/stays-platform/config.json"
    cfg = ""
    with open(cfgPath) as f:
        cfg = json.load(f)
    with open(cfgPath, "w") as f:
        cfg['env'] = env
        txt = json.dumps(cfg, indent=2) + EOF
        f.write(txt)

def setUiCfg(env):
    cfgPath = BASE_DIR+"/stays-ui/config.json"
    cfg = ""
    with open(cfgPath, 'r') as f:
        cfg = json.load(f)
    with open(cfgPath, "w") as f:
        cfg['env'] = env
        cfg['platform']['env'] = env
        txt = json.dumps(cfg, indent=2) + EOF
        f.write(txt)

def build():
    os.chdir(BASE_DIR)
    os.system("docker-compose build")

def tag(env, service):
    os.chdir(BASE_DIR)
    os.system("docker tag stays_"+service +
              " gcr.io/stays-"+env+"/stays-"+service)

def push(env, service):
    os.chdir(BASE_DIR)
    os.system("docker push gcr.io/stays-"+env+"/stays-"+service)

def deploy(env, service):
    os.chdir(BASE_DIR)
    os.system("gcloud run deploy stays-"+service +
              " --image gcr.io/stays-"+env+"/stays-"+service+" --project stays-"+env+" --region us-central1")

def fullDeploy(env, service):
    tag(env, service)
    push(env, service)
    deploy(env, service)

if __name__ == "__main__":
    if(len(sys.argv) < 1):
        print("Please specify environment")
        exit(-1)
    env = sys.argv[1]
    if env != "dev" and env != "prod":
        print("Invalid environment!")
        exit(-1)
    else:
        setPlatformCfg(env)
        setUiCfg(env)
        build()
        t1 = threading.Thread(target=fullDeploy, args=(env, "platform"))
        t2 = threading.Thread(target=fullDeploy, args=(env, "ui"))
        t1.start()
        t2.start()


from datetime import timedelta
from django.utils import timezone

from celery import shared_task

from django.contrib.auth.models import User
from .models import ReadingStatistics, ReadingSession

@shared_task
def update_reading_statistics():
    # Завдання Celery для оновлення статистики читання користувачів

    print("Завантаження даних...")

    # Отримуємо всіх користувачів
    users = User.objects.all()

    for user in users:
        now = timezone.now()  # Поточний час

        # Визначаємо дати для вибірки (7 та 30 днів назад)
        seven_days_ago = now - timedelta(days=7)
        thirty_days_ago = now - timedelta(days=30)

        # Фільтруємо сесії читання для користувача
        sessions = ReadingSession.objects.filter(user=user, end_time__isnull=False)

        # Фільтруємо сесії читання за останні 7 днів
        sessions_7_days = sessions.filter(end_time__gte=seven_days_ago, end_time__lte=now)

        # Фільтруємо сесії читання за останні 30 днів
        sessions_30_days = sessions.filter(end_time__gte=thirty_days_ago, end_time__lte=now)

        # Розраховуємо загальний час читання за 7 та 30 днів
        total_reading_7_days = sum(
            (session.end_time - session.start_time).total_seconds() / 3600 for session in sessions_7_days)
        total_reading_30_days = sum(
            (session.end_time - session.start_time).total_seconds() / 3600 for session in sessions_30_days)

        # Оновлюємо запис в моделі ReadingStatistics для користувача
        reading_statistics, created = ReadingStatistics.objects.get_or_create(user=user)
        reading_statistics.total_reading_7_days = total_reading_7_days
        reading_statistics.total_reading_30_days = total_reading_30_days
        reading_statistics.save()


import streamlit as st
from PIL import Image
from detection import process
import numpy as np
from torchdetect import process
import os

st.set_page_config(
    page_title="Image Detection",
    layout="wide",
    initial_sidebar_state="expanded"
 )
st.title('Tuberculosis Detection from sputum sample')
st.markdown("## inference using torch.hub")

uploaded_file = st.file_uploader(label="Choose a file", type=['jpg', 'jpeg','png'])

idebar = st.sidebar
conf_level = st.sidebar.slider("conf_level", min_value=0.0, max_value=1.0, value=0.55)
IoU = st.sidebar.slider("IoU", min_value=0.0, max_value=1.0, value=0.45)

if uploaded_file is not None:
    image = Image.open(uploaded_file).convert('RGB')

    col1, col2 = st.columns([0.5, 0.5])

    #Col 1
    with col1:
        st.markdown('
Input Image
', unsafe_allow_html=True)
        st.image(image,caption="Sputum sample")
        imgpath = os.path.join('data/uploads', uploaded_file.name)

        with open(imgpath, mode="wb") as f:
            f.write(uploaded_file.getbuffer())

    with col2:
        st.markdown('
Detected Image
', unsafe_allow_html=True)
        img,total,runtime = process(imgpath,conf_level,IoU)
        st.image(img,caption="Tuberculosis detected")
        st.markdown(f'
Bacteria detected : {total}
', unsafe_allow_html=True)
        st.markdown(f'
{runtime}
', unsafe_allow_html=True)

    # with col2:
    #     st.markdown('
Detected Image
', unsafe_allow_html=True)
    #     image_arr,total =  process(np.array(image))
    #     st.image(Image.fromarray(image_arr),caption="Tuberculosis detected")
    #     st.markdown(f'
Bacteria detected : {total}
', unsafe_allow_html=True)


import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

# input parameter
den = 8880.0
cp = 386.0
cond = 398.0
temp_bc = 100.0
temp_init = 0.0
lx = 1.0
nx = 101
tend = 20000.0
dt = 0.1
tout = 100.0

alpha = cond / (den * cp)
dx = lx / (nx - 1)
nt = int(tend / dt)
nout = int(tout / dt)

#initial condition
temp = np.full(nx, temp_init)
time = 0.0

temp_new = np.zeros(nx)

# Boundary condition
temp[0] = temp_bc # Dirichlet @ x=0
temp[nx-1] = temp[nx-2] # Neumann @ x=Lx

# graph data array
ims = []
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

gx = np.zeros(nx)
for i in range(nx):
    gx[i] = i * dx

# time loop
for n in range(1, nt+1):
    # FTCS
    for i in range(1, nx-1):
        temp_new[i] = temp[i] + dt * alpha * (temp[i+1] - 2.0 * temp[i] + temp[i-1]) / (dx * dx)

    # update
    for i in range(1, nx-1):
        temp[i] = temp_new[i]

    # Boundary condition
    temp[0] = temp_bc # Dirichlet @ x=0
    temp[nx-1] = temp[nx-2] # Neumann @ x=Lx

    time += dt

    if n % nout == 0:
        print('n: {0:7d}, time: {1:8.1f}, temp: {2:10.6f}'.format(n, time, temp[nx-1]))
        im_line = ax.plot(gx, temp, 'b')
        im_time = ax.text(0, 110, 'Time = {0:8.1f} [s]'.format(time))
        ims.append(im_line + [im_time])

# graph plot
ax.set_xlabel('x [m]')
ax.set_ylabel('Temperature [C]')
ax.grid()
anm = animation.ArtistAnimation(fig, ims, interval=50)
anm.save('animation.gif', writer='pillow')
plt.show()


from abc import ABC, abstractmethod
from dataclasses import dataclass
from functools import partial
from typing import Any, Dict, List, Optional, Tuple

import torch

from shap_e.models.nn.utils import sample_pmf
from shap_e.models.volume import Volume, VolumeRange
from shap_e.util.collections import AttrDict

from .model import NeRFModel, Query

def render_rays(
    rays: torch.Tensor,
    parts: List["RayVolumeIntegral"],
    void_model: NeRFModel,
    shared: bool = False,
    prev_raw_outputs: Optional[List[AttrDict]] = None,
    render_with_direction: bool = True,
    importance_sampling_options: Optional[Dict[str, Any]] = None,
) -> Tuple["RayVolumeIntegralResults", List["RaySampler"], List[AttrDict]]:
    """
    Perform volumetric rendering over a partition of possible t's in the union
    of rendering volumes (written below with some abuse of notations)

        C(r) := sum(
            transmittance(t[i]) *
            integrate(
                lambda t: density(t) * channels(t) * transmittance(t),
                [t[i], t[i + 1]],
            )
            for i in range(len(parts))
        ) + transmittance(t[-1]) * void_model(t[-1]).channels

    where

    1) transmittance(s) := exp(-integrate(density, [t[0], s])) calculates the
       probability of light passing through the volume specified by [t[0], s].
       (transmittance of 1 means light can pass freely)
    2) density and channels are obtained by evaluating the appropriate
       part.model at time t.
    3) [t[i], t[i + 1]] is defined as the range of t where the ray intersects
       (parts[i].volume \\ union(part.volume for part in parts[:i])) at the surface
       of the shell (if bounded). If the ray does not intersect, the integral over
       this segment is evaluated as 0 and transmittance(t[i + 1]) :=
       transmittance(t[i]).
    4) The last term is integration to infinity (e.g. [t[-1], math.inf]) that
       is evaluated by the void_model (i.e. we consider this space to be empty).

    :param rays: [batch_size x ... x 2 x 3] origin and direction.
    :param parts: disjoint volume integrals.
    :param void_model: use this model to integrate over the empty space
    :param shared: All RayVolumeIntegrals are calculated with the same model.
    :param prev_raw_outputs: Raw outputs from the previous rendering step

    :return: A tuple of
        - AttrDict containing the rendered `channels`, `distances`, and the `aux_losses`
        - A list of importance samplers for additional fine-grained rendering
        - A list of raw output for each interval
    """
    if importance_sampling_options is None:
        importance_sampling_options = {}

    origin, direc = rays[..., 0, :], rays[..., 1, :]

    if prev_raw_outputs is None:
        prev_raw_outputs = [None] * len(parts)

    samplers = []
    raw_outputs = []
    t0 = None
    results = None

    for part_i, prev_raw_i in zip(parts, prev_raw_outputs):

        # Integrate over [t[i], t[i + 1]]
        results_i = part_i.render_rays(
            origin,
            direc,
            t0=t0,
            prev_raw=prev_raw_i,
            shared=shared,
            render_with_direction=render_with_direction,
        )

        # Create an importance sampler for (optional) fine rendering
        samplers.append(
            ImportanceRaySampler(
                results_i.volume_range, results_i.raw, **importance_sampling_options
            )
        )
        raw_outputs.append(results_i.raw)

        # Pass t[i + 1] as the start of integration for the next interval.
        t0 = results_i.volume_range.next_t0()

        # Combine the results from [t[0], t[i]] and [t[i], t[i+1]]
        results = results_i if results is None else results.combine(results_i)

    # While integrating out [t[-1], math.inf] is the correct thing to do, this
    # erases a lot of useful information. Also, void_model is meant to predict
    # the channels at t=math.inf.

    # # Add the void background over [t[-1], math.inf] to complete integration.
    # results = results.combine(
    #     RayVolumeIntegralResults(
    #         output=AttrDict(
    #             channels=void_model(origin, direc),
    #             distances=torch.zeros_like(t0),
    #             aux_losses=AttrDict(),
    #         ),
    #         volume_range=VolumeRange(
    #             t0=t0,
    #             t1=torch.full_like(t0, math.inf),
    #             intersected=torch.full_like(results.volume_range.intersected, True),
    #         ),
    #         # Void space extends to infinity. It is assumed that no light
    #         # passes beyond the void.
    #         transmittance=torch.zeros_like(results_i.transmittance),
    #     )
    # )

    results.output.channels = results.output.channels + results.transmittance * void_model(
        Query(origin, direc)
    )

    return results, samplers, raw_outputs

@dataclass
class RayVolumeIntegralResults:
    """
    Stores the relevant state and results of

        integrate(
            lambda t: density(t) * channels(t) * transmittance(t),
            [t0, t1],
        )
    """

    # Rendered output and auxiliary losses
    # output.channels has shape [batch_size, *inner_shape, n_channels]
    output: AttrDict

    """
    Optional values
    """

    # Raw values contain the sampled `ts`, `density`, `channels`, etc.
    raw: Optional[AttrDict] = None

    # Integration
    volume_range: Optional[VolumeRange] = None

    # If a ray intersects, the transmittance from t0 to t1 (e.g. the
    # probability that the ray passes through this volume).
    # has shape [batch_size, *inner_shape, 1]
    transmittance: Optional[torch.Tensor] = None

    def combine(self, cur: "RayVolumeIntegralResults") -> "RayVolumeIntegralResults":
        """
        Combines the integration results of `self` over [t0, t1] and
        `cur` over [t1, t2] to produce a new set of results over [t0, t2] by
        using a similar equation to (4) in NeRF++:

            integrate(
                lambda t: density(t) * channels(t) * transmittance(t),
                [t0, t2]
            )

          = integrate(
                lambda t: density(t) * channels(t) * transmittance(t),
                [t0, t1]
            ) + transmittance(t1) * integrate(
                lambda t: density(t) * channels(t) * transmittance(t),
                [t1, t2]
            )
        """
        assert torch.allclose(self.volume_range.next_t0(), cur.volume_range.t0)

        def _combine_fn(
            prev_val: Optional[torch.Tensor],
            cur_val: Optional[torch.Tensor],
            *,
            prev_transmittance: torch.Tensor,
        ):
            assert prev_val is not None
            if cur_val is None:
                # cur_output.aux_losses are empty for the void_model.
                return prev_val
            return prev_val + prev_transmittance * cur_val

        output = self.output.combine(
            cur.output, combine_fn=partial(_combine_fn, prev_transmittance=self.transmittance)
        )

        combined = RayVolumeIntegralResults(
            output=output,
            volume_range=self.volume_range.extend(cur.volume_range),
            transmittance=self.transmittance * cur.transmittance,
        )
        return combined

@dataclass
class RayVolumeIntegral:
    model: NeRFModel
    volume: Volume
    sampler: "RaySampler"
    n_samples: int

    def render_rays(
        self,
        origin: torch.Tensor,
        direction: torch.Tensor,
        t0: Optional[torch.Tensor] = None,
        prev_raw: Optional[AttrDict] = None,
        shared: bool = False,
        render_with_direction: bool = True,
    ) -> "RayVolumeIntegralResults":
        """
        Perform volumetric rendering over the given volume.

        :param position: [batch_size, *shape, 3]
        :param direction: [batch_size, *shape, 3]
        :param t0: Optional [batch_size, *shape, 1]
        :param prev_raw: the raw outputs when using multiple levels with this model.
        :param shared: means the same model is used for all RayVolumeIntegral's
        :param render_with_direction: use the incoming ray direction when querying the model.

        :return: RayVolumeIntegralResults
        """
        # 1. Intersect the rays with the current volume and sample ts to
        # integrate along.
        vrange = self.volume.intersect(origin, direction, t0_lower=t0)
        ts = self.sampler.sample(vrange.t0, vrange.t1, self.n_samples)

        if prev_raw is not None and not shared:
            # Append the previous ts now before fprop because previous
            # rendering used a different model and we can't reuse the output.
            ts = torch.sort(torch.cat([ts, prev_raw.ts], dim=-2), dim=-2).values

        # Shape sanity checks
        batch_size, *_shape, _t0_dim = vrange.t0.shape
        _, *ts_shape, _ts_dim = ts.shape

        # 2. Get the points along the ray and query the model
        directions = torch.broadcast_to(direction.unsqueeze(-2), [batch_size, *ts_shape, 3])
        positions = origin.unsqueeze(-2) + ts * directions

        optional_directions = directions if render_with_direction else None
        mids = (ts[..., 1:, :] + ts[..., :-1, :]) / 2
        raw = self.model(
            Query(
                position=positions,
                direction=optional_directions,
                t_min=torch.cat([vrange.t0[..., None, :], mids], dim=-2),
                t_max=torch.cat([mids, vrange.t1[..., None, :]], dim=-2),
            )
        )
        raw.ts = ts

        if prev_raw is not None and shared:
            # We can append the additional queries to previous raw outputs
            # before integration
            copy = prev_raw.copy()
            result = torch.sort(torch.cat([raw.pop("ts"), copy.pop("ts")], dim=-2), dim=-2)
            merge_results = partial(self._merge_results, dim=-2, indices=result.indices)
            raw = raw.combine(copy, merge_results)
            raw.ts = result.values

        # 3. Integrate the raw results
        output, transmittance = self.integrate_samples(vrange, raw)

        # 4. Clean up results that do not intersect with the volume.
        transmittance = torch.where(
            vrange.intersected, transmittance, torch.ones_like(transmittance)
        )

        def _mask_fn(_key: str, tensor: torch.Tensor):
            return torch.where(vrange.intersected, tensor, torch.zeros_like(tensor))

        def _is_tensor(_key: str, value: Any):
            return isinstance(value, torch.Tensor)

        output = output.map(map_fn=_mask_fn, should_map=_is_tensor)

        return RayVolumeIntegralResults(
            output=output,
            raw=raw,
            volume_range=vrange,
            transmittance=transmittance,
        )

    def integrate_samples(
        self,
        volume_range: VolumeRange,
        raw: AttrDict,
    ) -> Tuple[AttrDict, torch.Tensor]:
        """
        Integrate the raw.channels along with other aux_losses and values to
        produce the final output dictionary containing rendered `channels`,
        estimated `distances` and `aux_losses`.

        :param volume_range: Specifies the integral range [t0, t1]
        :param raw: Contains a dict of function evaluations at ts. Should have

            density: torch.Tensor [batch_size, *shape, n_samples, 1]
            channels: torch.Tensor [batch_size, *shape, n_samples, n_channels]
            aux_losses: {key: torch.Tensor [batch_size, *shape, n_samples, 1] for each key}
            no_weight_grad_aux_losses: an optional set of losses for which the weights
                                       should be detached before integration.

            after the call, integrate_samples populates some intermediate calculations
            for later use like

            weights: torch.Tensor [batch_size, *shape, n_samples, 1] (density *
                transmittance)[i] weight for each rgb output at [..., i, :].
        :returns: a tuple of (
            a dictionary of rendered outputs and aux_losses,
            transmittance of this volume,
        )
        """

        # 1. Calculate the weights
        _, _, dt = volume_range.partition(raw.ts)
        ddensity = raw.density * dt

        mass = torch.cumsum(ddensity, dim=-2)
        transmittance = torch.exp(-mass[..., -1, :])

        alphas = 1.0 - torch.exp(-ddensity)
        Ts = torch.exp(torch.cat([torch.zeros_like(mass[..., :1, :]), -mass[..., :-1, :]], dim=-2))
        # This is the probability of light hitting and reflecting off of
        # something at depth [..., i, :].
        weights = alphas * Ts

        # 2. Integrate all results
        def _integrate(key: str, samples: torch.Tensor, weights: torch.Tensor):
            if key == "density":
                # Omit integrating the density, because we don't need it
                return None
            return torch.sum(samples * weights, dim=-2)

        def _is_tensor(_key: str, value: Any):
            return isinstance(value, torch.Tensor)

        if raw.no_weight_grad_aux_losses:
            extra_aux_losses = raw.no_weight_grad_aux_losses.map(
                partial(_integrate, weights=weights.detach()), should_map=_is_tensor
            )
        else:
            extra_aux_losses = {}
        output = raw.map(partial(_integrate, weights=weights), should_map=_is_tensor)
        if "no_weight_grad_aux_losses" in output:
            del output["no_weight_grad_aux_losses"]
        output.aux_losses.update(extra_aux_losses)

        # Integrating the ts yields the distance away from the origin; rename the variable.
        output.distances = output.ts
        del output["ts"]
        del output["density"]

        assert output.distances.shape == (*output.channels.shape[:-1], 1)
        assert output.channels.shape[:-1] == raw.channels.shape[:-2]
        assert output.channels.shape[-1] == raw.channels.shape[-1]

        # 3. Reduce loss
        def _reduce_loss(_key: str, loss: torch.Tensor):
            return loss.view(loss.shape[0], -1).sum(dim=-1)

        # 4. Store other useful calculations
        raw.weights = weights

        output.aux_losses = output.aux_losses.map(_reduce_loss)

        return output, transmittance

    def _merge_results(
        self, a: Optional[torch.Tensor], b: torch.Tensor, dim: int, indices: torch.Tensor
    ):
        """
        :param a: [..., n_a, ...]. The other dictionary containing the b's may
            contain extra tensors from earlier calculations, so a can be None.
        :param b: [..., n_b, ...]
        :param dim: dimension to merge
        :param indices: how the merged results should be sorted at the end
        :return: a concatted and sorted tensor of size [..., n_a + n_b, ...]
        """
        if a is None:
            return None

        merged = torch.cat([a, b], dim=dim)
        return torch.gather(merged, dim=dim, index=torch.broadcast_to(indices, merged.shape))

class RaySampler(ABC):
    @abstractmethod
    def sample(self, t0: torch.Tensor, t1: torch.Tensor, n_samples: int) -> torch.Tensor:
        """
        :param t0: start time has shape [batch_size, *shape, 1]
        :param t1: finish time has shape [batch_size, *shape, 1]
        :param n_samples: number of ts to sample
        :return: sampled ts of shape [batch_size, *shape, n_samples, 1]
        """

class StratifiedRaySampler(RaySampler):
    """
    Instead of fixed intervals, a sample is drawn uniformly at random from each
    interval.
    """

    def __init__(self, depth_mode: str = "linear"):
        """
        :param depth_mode: linear samples ts linearly in depth. harmonic ensures
            closer points are sampled more densely.
        """
        self.depth_mode = depth_mode
        assert self.depth_mode in ("linear", "geometric", "harmonic")

    def sample(
        self,
        t0: torch.Tensor,
        t1: torch.Tensor,
        n_samples: int,
        epsilon: float = 1e-3,
    ) -> torch.Tensor:
        """
        :param t0: start time has shape [batch_size, *shape, 1]
        :param t1: finish time has shape [batch_size, *shape, 1]
        :param n_samples: number of ts to sample
        :return: sampled ts of shape [batch_size, *shape, n_samples, 1]
        """
        ones = [1] * (len(t0.shape) - 1)
        ts = torch.linspace(0, 1, n_samples).view(*ones, n_samples).to(t0.dtype).to(t0.device)

        if self.depth_mode == "linear":
            ts = t0 * (1.0 - ts) + t1 * ts
        elif self.depth_mode == "geometric":
            ts = (t0.clamp(epsilon).log() * (1.0 - ts) + t1.clamp(epsilon).log() * ts).exp()
        elif self.depth_mode == "harmonic":
            # The original NeRF recommends this interpolation scheme for
            # spherical scenes, but there could be some weird edge cases when
            # the observer crosses from the inner to outer volume.
            ts = 1.0 / (1.0 / t0.clamp(epsilon) * (1.0 - ts) + 1.0 / t1.clamp(epsilon) * ts)

        mids = 0.5 * (ts[..., 1:] + ts[..., :-1])
        upper = torch.cat([mids, t1], dim=-1)
        lower = torch.cat([t0, mids], dim=-1)
        t_rand = torch.rand_like(ts)

        ts = lower + (upper - lower) * t_rand
        return ts.unsqueeze(-1)

class ImportanceRaySampler(RaySampler):
    """
    Given the initial estimate of densities, this samples more from
    regions/bins expected to have objects.
    """

    def __init__(
        self, volume_range: VolumeRange, raw: AttrDict, blur_pool: bool = False, alpha: float = 1e-5
    ):
        """
        :param volume_range: the range in which a ray intersects the given volume.
        :param raw: dictionary of raw outputs from the NeRF models of shape
            [batch_size, *shape, n_coarse_samples, 1]. Should at least contain

            :param ts: earlier samples from the coarse rendering step
            :param weights: discretized version of density * transmittance
        :param blur_pool: if true, use 2-tap max + 2-tap blur filter from mip-NeRF.
        :param alpha: small value to add to weights.
        """
        self.volume_range = volume_range
        self.ts = raw.ts.clone().detach()
        self.weights = raw.weights.clone().detach()
        self.blur_pool = blur_pool
        self.alpha = alpha

    @torch.no_grad()
    def sample(self, t0: torch.Tensor, t1: torch.Tensor, n_samples: int) -> torch.Tensor:
        """
        :param t0: start time has shape [batch_size, *shape, 1]
        :param t1: finish time has shape [batch_size, *shape, 1]
        :param n_samples: number of ts to sample
        :return: sampled ts of shape [batch_size, *shape, n_samples, 1]
        """
        lower, upper, _ = self.volume_range.partition(self.ts)

        batch_size, *shape, n_coarse_samples, _ = self.ts.shape

        weights = self.weights
        if self.blur_pool:
            padded = torch.cat([weights[..., :1, :], weights, weights[..., -1:, :]], dim=-2)
            maxes = torch.maximum(padded[..., :-1, :], padded[..., 1:, :])
            weights = 0.5 * (maxes[..., :-1, :] + maxes[..., 1:, :])
        weights = weights + self.alpha
        pmf = weights / weights.sum(dim=-2, keepdim=True)
        inds = sample_pmf(pmf, n_samples)
        assert inds.shape == (batch_size, *shape, n_samples, 1)
        assert (inds >= 0).all() and (inds < n_coarse_samples).all()

        t_rand = torch.rand(inds.shape, device=inds.device)
        lower_ = torch.gather(lower, -2, inds)
        upper_ = torch.gather(upper, -2, inds)

        ts = lower_ + (upper_ - lower_) * t_rand
        ts = torch.sort(ts, dim=-2).values
        return ts


# -*- coding: utf-8 -*-
"""
Created on Tue Jan 31 12:39:09 2023

@author: Mouhamad Ali Elamine
"""

import argparse
import json
import re

parser = argparse.ArgumentParser(description='A1T1')
parser.add_argument('--input_file', type=str, default='./review.json', help='the input file ')
parser.add_argument('--output_file', type=str, default= './a1t1.json', help='the output file contains your answer')
parser.add_argument('--stopwords', type=str, default='./stopwords',help='the file contains the stopwords')
parser.add_argument('--y', type=int, default=2018, help='year')
parser.add_argument('--m', type=int, default=10, help='top m users')
parser.add_argument('--n', type=int, default=10, help='top n frequent words')

args = parser.parse_args()
stopwords = args.stopwords
f = open(stopwords)
#initialize stopwords list with empty string to account for trailing spaces
stopwords_list = ['']
#append stop words to list
for line in f:
    stopwords_list.append(line.rstrip())
f.close()

#create context
from pyspark import SparkConf, SparkContext
if __name__ == '__main__':
    sc_conf = SparkConf() \
        .setAppName('task1') \
        .setMaster('local[*]') \
        .set('spark.driver.memory','8g') \
        .set('spark.executor.memory','4g')
    sc = SparkContext.getOrCreate(conf=sc_conf)
    sc.setLogLevel('OFF')

input_file = 'review.json'
#persist lines -> read input file only once
lines = sc.textFile(input_file).persist()
#persist review_rdd -> convert json into dictionary only once
review_rdd = lines.map(lambda x: json.loads(x)).persist()

#part A
rdd_count = review_rdd.count()

#part B
year_rdd = review_rdd.filter(lambda x: x["date"][:4] == str(args.y)).persist()
year_count = year_rdd.count()

#part C
user_rdd = review_rdd.map(lambda x: x["user_id"]).distinct()
user_count = user_rdd.count()

#part D
topm_rdd = review_rdd.map(lambda x: (x["user_id"],1) )
topm_rdd1 = topm_rdd.groupByKey().mapValues(lambda x: sum(x))
topm_rdd2 = topm_rdd1.sortBy(lambda x: (-x[1], x[0])).take(args.m)

#part E
text_rdd = review_rdd.map(lambda x: re.sub('[\(\[,.!?:;\]\)]','', x["text"]))
text_rdd1 = text_rdd.flatMap(lambda x: x.lower().split())
text_rdd2 = text_rdd1.filter(lambda x: x not in stopwords_list)
text_rdd3 = text_rdd2.map(lambda x: (x,1))
text_rdd4 = text_rdd3.groupByKey().mapValues(lambda x: sum(x))
text_rdd5 = text_rdd4.sortBy(lambda x: (-x[1],x[0]))
text_rdd6 = text_rdd5.map(lambda x: x[0]).take(args.n)

task1 = {
    "A": rdd_count,
    "B":year_count,
    "C":user_count,
    "D":topm_rdd2,
    "E":text_rdd6
}

json_task1 = json.dumps(task1, indent=4)

with open(args.output_file, "w") as outfile:
    outfile.write(json_task1)


"""
    	***************************
    	--------EveIDE_LIGHT--------
 	 Author: Adancurusul
 	 Date: 2021-07-17 18:07:02
 	 LastEditors: Adancurusul
 	 LastEditTime: 2021-07-31 14:10:21
 	 Github: https://github.com/Adancurusul
 	 Email: adancurusul@gmail.com

    	***************************
    """
import re
import os
class GetSimDumpFile():
    def rmComments(self,text):
        singLineComments = re.compile(r'//(.*)', re.MULTILINE)
        multiLineComments = re.compile(r'/\*(.*)\*/', re.DOTALL)
        text = singLineComments.sub('', text)
        text = multiLineComments.sub('', text)
        return text
    def getDumpFile(self,fileName)->str:
        stPath = ""
        with open(fileName, "r", encoding="utf-8") as rFile:
            fileText = self.rmComments(rFile.read())
            tp = r"(\$dumpfile)(.+)[\;]"
            # patternStr = r"(\w+|_.+)(\s+|\t)(\w+|_.+)(\s+|\t|\s?)\("
            pattern = re.compile(tp)
            match = pattern.search(fileText)
            if (match):
                st = match.group(2).replace(" ", "").replace("(", "").replace(")", "").replace("\"", "")
                stPath = os.path.dirname(fileName)+"/"+st
        return stPath


from django.core import urlresolvers
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.comments.moderation import CommentModerator, moderator
from django.contrib.sites.models import Site

from akismet import Akismet

AKISMET_KEY = getattr(settings, "AKISMET_KEY", None)

class BlogdorModerator(CommentModerator):
    email_notification = False
    enable_field = 'comments_enabled'

    def email(self, comment, content_object, request):

        from_email = "bounce@%s" % Site.objects.get_current().domain

        subject = "Comment on %s pending your approval" % content_object.title
        appr_link = 'http://%s%s' % (Site.objects.get_current().domain, urlresolvers.reverse('comments-approve', args=(comment.id,))   )
        message = '\n\n'.join((comment.get_as_text(), appr_link))
        recipient_email = content_object.author.email

        #send_mail(subject, message, from_email, (recipient_email,), fail_silently=False)

    def moderate(self, comment, content_object, request):
        a = Akismet(AKISMET_KEY, blog_url='http://%s/' % Site.objects.get_current().domain)

        akismet_data = {
            'user_ip': comment.ip_address,
            'user_agent': request.META['HTTP_USER_AGENT'],
            'comment_author': comment.user_name.encode('ascii','ignore'),
            'comment_author_email': comment.user_email.encode('ascii','ignore'),
            'comment_author_url': comment.user_url.encode('ascii','ignore'),
            'comment_type': 'comment',
        }

        is_spam = a.comment_check(comment.comment.encode('ascii','ignore'), akismet_data)

        comment.is_public = False
        comment.save()

        if not is_spam:
           pass
           #self.email(comment, content_object, request)

        return True


from operator import itemgetter

import networkx as nx
import prefect
from sklearn.metrics import roc_auc_score

logger = prefect.context.get("logger")

def compute_centrality_metrics(G):
    closeness_centrality = nx.centrality.closeness_centrality(G)
    degree_centrality = nx.centrality.degree_centrality(G)
    betweenness_centrality = nx.centrality.betweenness_centrality(G)
    eigenvector_centrality = nx.centrality.eigenvector_centrality(G)
    return (
        closeness_centrality,
        degree_centrality,
        betweenness_centrality,
        eigenvector_centrality,
    )

def evaluate_roc_auc(clf, link_features, link_labels):
    predicted = clf.predict_proba(link_features)

    # check which class corresponds to positive links
    positive_column = list(clf.classes_).index(1)
    return roc_auc_score(link_labels, predicted[:, positive_column])

def node_with_largest_degree(G):
    node_and_degree = G.degree()
    return sorted(node_and_degree, key=itemgetter(1))[-1]

def connected_components(G):
    components = nx.connected_components(G)
    print(components)
    largest_component = max(components, key=len)
    return components, largest_component


# Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.

# Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
# Output: [[1,0,1],[0,0,0],[1,0,1]]

def setZeroes(matrix):
    x, y = [], []
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == 0:
                if i not in y:
                    y.append(i)
                if j not in x:
                    x.append(j)
    for k in range(len(y)):
        for i in range(len(matrix[0])):
            matrix[y[k]][i] = 0

    for k in range(len(x)):
        for i in range(len(matrix)):
            matrix[i][x[k]] = 0
    return matrix

matrix = [[1,1,1],[1,0,1],[1,1,1]]
print(setZeroes(matrix))

def setZeroes(matrix):
    x,y = [], []
    cols, rows = len(matrix), len(matrix[0])
    for i in range(cols):
        for j in range(rows):
            if matrix[i][j] == 0:
                if i not in x:
                    x.append(i)
                if j not in y:
                    y.append(j)

    for i in range(len(x)):
        matrix[x[i]] = [0]*rows

    for i in range(cols):
        for j in range(rows):
            if j in y:
                matrix[i][j] = 0


# demonstration of the YCbCr encoder/decoder functionality

import numpy as np
import cv2
#import matplotlib.pyplot as plt
#import matplotlib.image as mpimg

K_VALS = [.299, .587, .114] # ITU-R BT.601
#K_VALS = [.2627, .678, .0593] # ITU-R BT.2020
R = 0
G = 1
B = 2

def color_matrix(values):
  """
  Generates a color matrix from the K values
  :param values: list of values [Kr, Kg, Kb]
  :return: 3x3 matrix (list) of the color matrix
  """
  kr = values[0]
  kg = values[1]
  kb = values[2]

  matrix = []
  matrix.append(values)
  matrix.append([-.5*kr/(1-kb), -.5*kg/(1-kb), .5])
  matrix.append([.5, -.5*kg/(1-kr), -.5*kb/(1-kr)])

  return matrix

def rgb_to_ycbcr(image, constants=K_VALS):
  """
  Converts an RGB image (list of lists of lists of uint8's) to a YCbCr image
  :param values: input image
  :param constants: The conversion constants to use [Kr, Kg, Kb]
  :return: a new 3-channel image in YCbCr encoding
  """

  kr = constants[0]
  kg = constants[1]
  kb = constants[2]
  m = color_matrix(constants)

  new_image = []

  for y in range(len(image)):

    row = []
    for x in range(len(image[y])):

      pixel = []

      # JPEG conversion
      r = image[y][x][R]
      g = image[y][x][G]
      b = image[y][x][B]

      luma_p = 0 + (kr*r) + (kg*g) + (kb*b)
      cb = 128 + (m[1][0]*r) + (m[1][1]*g) + (m[1][2]*b)
      cr = 128 + (m[2][0]*r) + (m[2][1]*g) + (m[2][2]*b)

      pixel = [luma_p, cr, cb]

      row.append(np.array(pixel, dtype = 'uint8'))

    new_image.append(np.array(row, dtype = 'uint8'))

  return np.array(new_image, dtype = 'uint8')

def ycbcr_to_rgb(image, constants=K_VALS):
  """
  Converts a YCbCr image (list of lists of lists of uint8's) to an RGB image
  :param values: input image
  :param constants: The conversion constants to use
  :return: a new 3-channel image in RGB encoding
  """

  m = np.linalg.inv(np.array(color_matrix(constants)))

  new_image = []

  for y in range(len(image)):

    row = []
    for x in range(len(image[y])):

      pixel = []

      # JPEG conversion
      luma_p = image[y][x][R]
      cr = image[y][x][G]
      cb = image[y][x][B]

      r = luma_p + (m[0][2] * (cr-128))
      g = luma_p + (m[1][1] * (cb-128)) + (m[1][2] * (cr-128))
      b = luma_p + (m[2][1] * (cb-128))

      pixel = [r, g, b]

      # restricting range of the values to 0-255
      for i in range(len(pixel)):
        if pixel[i] < 0:
          pixel[i] = 0
        elif pixel[i] > 255:
          pixel[i] = 255

      row.append(np.array(pixel, dtype = 'uint8'))

    new_image.append(np.array(row, dtype = 'uint8'))

  return np.array(new_image, dtype = 'uint8')

if __name__ == "__main__":

  img = cv2.imread('software tests/full_ycbcr_demo/surf.png')
  img2 = rgb_to_ycbcr(img)
  #img3 = cv2.cvtColor(img2, cv2.COLOR_YCrCb2RGB)
  #img4 = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)
  img5 = ycbcr_to_rgb(img2)

  cv2.imshow('original', img)
  cv2.imshow('converted', img2)
  cv2.imshow('reconstructed', img5)

  cv2.waitKey(0)
  cv2.destroyAllWindows()


import discord
import asyncio

from dotenv import load_dotenv
from collections import Counter
from os import getenv

intents = discord.Intents.default()
intents.members = True
intents.presences = True

load_dotenv()
TOKEN = getenv('DISCORD_TOKEN')

class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # create the background task and run it in the background
        self.bg_task = self.loop.create_task(self.check_game_update())

    async def on_ready(self):
        print('--------------------------------------------------')
        print(f'Logged in as: {self.user.name} {self.user.id}')
        print('--------------------------------------------------')
        await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Game Activity"))

    async def check_game_update(self):
        await self.wait_until_ready()
        while not self.is_closed():
            for guild in self.guilds:
                for channel in guild.voice_channels:
                    if(len(channel.members) > 0):
                        numChatting = 0
                        vidChatting = 0
                        activityList = []
                        for chatter in channel.members:
                            if(chatter.activity == None):
                                numChatting += 1
                                if(chatter.voice.self_video):
                                    vidChatting += 1
                            elif(chatter.activity.type.name == 'playing' or chatter.activity.type.name == 'streaming'):
                                activityList.append(chatter.activity.name)
                            else:
                                numChatting += 1
                                if(chatter.voice.self_video):
                                    vidChatting += 1

                        if(numChatting > (len(channel.members)/2)):
                            if(vidChatting > (numChatting/2)):
                                new_name = 'Garage Talk'
                            else:
                                new_name = 'Just Chatting'
                        else:
                            new_name = str(Counter(activityList).most_common(1)[0][0])
                        await channel.edit(name=new_name)
                        channel2 = self.get_channel(791066555085094923)
                        await channel2.send(new_name)
                await asyncio.sleep(300) # task runs every 5 Minutes, temp set to 5 seconds when sending messages instead of updating channel name

client = MyClient(intents = intents)
client.run(TOKEN)


from rpython.rlib import jit_hooks
from rpython.rlib.jit import JitHookInterface, Counters

from pypy.interpreter.error import OperationError
from pypy.module.pypyjit.interp_resop import (Cache, wrap_greenkey,
    WrappedOp, W_JitLoopInfo, wrap_oplist)

class PyPyJitIface(JitHookInterface):
    def are_hooks_enabled(self):
        space = self.space
        cache = space.fromcache(Cache)
        return (cache.w_compile_hook is not None or
                cache.w_abort_hook is not None or
                cache.w_trace_too_long_hook is not None)

    def on_abort(self, reason, jitdriver, greenkey, greenkey_repr, logops, operations):
        space = self.space
        cache = space.fromcache(Cache)
        if cache.in_recursion:
            return
        if cache.w_abort_hook is not None:
            cache.in_recursion = True
            oplist_w = wrap_oplist(space, logops, operations)
            try:
                try:
                    space.call_function(cache.w_abort_hook,
                        space.newtext(jitdriver.name),
                        wrap_greenkey(space, jitdriver, greenkey, greenkey_repr),
                        space.newtext(Counters.counter_names[reason]),
                        space.newlist(oplist_w)
                    )
                except OperationError as e:
                    e.write_unraisable(space, "jit hook ", cache.w_abort_hook)
            finally:
                cache.in_recursion = False

    def on_trace_too_long(self, jitdriver, greenkey, greenkey_repr):
        space = self.space
        cache = space.fromcache(Cache)
        if cache.in_recursion:
            return
        if cache.w_trace_too_long_hook is not None:
            cache.in_recursion = True
            try:
                try:
                    space.call_function(cache.w_trace_too_long_hook,
                        space.newtext(jitdriver.name),
                        wrap_greenkey(space, jitdriver, greenkey, greenkey_repr))
                except OperationError as e:
                    e.write_unraisable(space, "jit hook", cache.w_trace_too_long_hook)
            finally:
                cache.in_recursion = False

    def after_compile(self, debug_info):
        self._compile_hook(debug_info, is_bridge=False)

    def after_compile_bridge(self, debug_info):
        self._compile_hook(debug_info, is_bridge=True)

    def before_compile(self, debug_info):
        pass

    def before_compile_bridge(self, debug_info):
        pass

    def _compile_hook(self, debug_info, is_bridge):
        space = self.space
        cache = space.fromcache(Cache)
        if cache.in_recursion:
            return
        if cache.w_compile_hook is not None:
            w_debug_info = W_JitLoopInfo(space, debug_info, is_bridge,
                                         cache.compile_hook_with_ops)
            cache.in_recursion = True
            try:
                try:
                    space.call_function(cache.w_compile_hook,
                                        w_debug_info)
                except OperationError as e:
                    e.write_unraisable(space, "jit hook ", cache.w_compile_hook)
            finally:
                cache.in_recursion = False

pypy_hooks = PyPyJitIface()


#!/usr/bin/python
import sys, glob

from sys import platform
if platform == "linux" or platform == "linux2":
    sys.path.insert(0, glob.glob('/home/yaoliu/src_code/local/lib/lib/python2.7/site-packages/')[0])

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from thrift.Thrift import TProcessor
from thrift.protocol import TProtocol

try:
    from thrift.protocol import fastbinary
except:
    fastbinary = None

import re
import hashlib

class NodeID:
    """
  Attributes:
   - id
   - ip
   - port
  """

    thrift_spec = (
        None,  # 0
        (1, TType.STRING, 'id', None, None,),  # 1
        (2, TType.STRING, 'ip', None, None,),  # 2
        (3, TType.I32, 'port', None, None,),  # 3
    )

    def __init__(self, id=None, ip=None, port=None, ):
        self.id = id
        self.ip = ip
        self.port = port

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,
                                                                                TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.STRING:
                    self.id = iprot.readString()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.STRING:
                    self.ip = iprot.readString()
                else:
                    iprot.skip(ftype)
            elif fid == 3:
                if ftype == TType.I32:
                    self.port = iprot.readI32()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('NodeID')
        if self.id is not None:
            oprot.writeFieldBegin('id', TType.STRING, 1)
            oprot.writeString(self.id)
            oprot.writeFieldEnd()
        if self.ip is not None:
            oprot.writeFieldBegin('ip', TType.STRING, 2)
            oprot.writeString(self.ip)
            oprot.writeFieldEnd()
        if self.port is not None:
            oprot.writeFieldBegin('port', TType.I32, 3)
            oprot.writeI32(self.port)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

    def validate(self):
        return

    def __repr__(self):
        L = ['%s=%r' % (key, value)
             for key, value in self.__dict__.items()]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not (self == other)

class Iface:
    def setReplicationtable(self, node_list):
        """
        Parameters:
         - node_list
        """
        pass

class Client(Iface):
    def __init__(self, iprot, oprot=None):
        self._iprot = self._oprot = iprot
        if oprot is not None:
            self._oprot = oprot
        self._seqid = 0

    def setReplicationtable(self, node_list):
        """
        Parameters:
         - node_list
        """
        self.send_setReplicationtable(node_list)
        self.recv_setReplicationtable()

    def send_setReplicationtable(self, node_list):
        self._oprot.writeMessageBegin('setReplicationtable', TMessageType.CALL, self._seqid)
        args = setReplicationtable_args()
        args.node_list = node_list
        args.write(self._oprot)
        self._oprot.writeMessageEnd()
        self._oprot.trans.flush()

    def recv_setReplicationtable(self):
        (fname, mtype, rseqid) = self._iprot.readMessageBegin()
        if mtype == TMessageType.EXCEPTION:
            x = TApplicationException()
            x.read(self._iprot)
            self._iprot.readMessageEnd()
            raise x
        result = setReplicationtable_result()
        result.read(self._iprot)
        self._iprot.readMessageEnd()
        return

class setReplicationtable_args:
    """
  Attributes:
   - node_list
  """

    thrift_spec = (
        None,  # 0
        (1, TType.LIST, 'node_list', (TType.STRUCT, (NodeID, NodeID.thrift_spec)), None,),  # 1
    )

    def __init__(self, node_list=None, ):
        self.node_list = node_list

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,
                                                                                TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.LIST:
                    self.node_list = []
                    (_etype3, _size0) = iprot.readListBegin()
                    for _i4 in range(_size0):
                        _elem5 = NodeID()
                        _elem5.read(iprot)
                        self.node_list.append(_elem5)
                    iprot.readListEnd()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('setReplicationtable_args')
        if self.node_list is not None:
            oprot.writeFieldBegin('node_list', TType.LIST, 1)
            oprot.writeListBegin(TType.STRUCT, len(self.node_list))
            for iter6 in self.node_list:
                iter6.write(oprot)
            oprot.writeListEnd()
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

    def validate(self):
        return

    def __repr__(self):
        L = ['%s=%r' % (key, value)
             for key, value in self.__dict__.items()]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not (self == other)

class setReplicationtable_result:
    thrift_spec = (
    )

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans,
                                                                                TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('setReplicationtable_result')
        oprot.writeFieldStop()
        oprot.writeStructEnd()

    def validate(self):
        return

    def __repr__(self):
        L = ['%s=%r' % (key, value)
             for key, value in self.__dict__.items()]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not (self == other)

def create_node(s):
    sha256 = hashlib.sha256()
    sha256.update(s.encode())
    k = sha256.hexdigest()

    m = re.match('([^:]+):([^:]+)', s)
    return NodeID(k, m.group(1), int(m.group(2)))

def createReplicas(nid, lst):
    print('Creation replica for', nid)
    index = lst.index(nid) // 4
    start = 4 * index
    end = 4 * (index + 1) if 4 * (index + 1) < len(lst) else len(lst)
    replicas = lst[start:end]
    # print(replicas)
    return replicas

def init_replicatiom(nid, lst, cdct=None):
    replicaTable = createReplicas(nid, lst)

    if cdct == None:
        transport = TSocket.TSocket(nid.ip, nid.port)
        transport = TTransport.TBufferedTransport(transport)
        protocol = TBinaryProtocol.TBinaryProtocol(transport)
        client = Client(protocol)
        transport.open()
        try:
            client.setReplicationtable(replicaTable)
        finally:
            transport.close()
    else:
        # buffered clients
        client = cdct['%s:%d' % (nid.ip, nid.port)]
        client.setReplicationtable(replicaTable)

if __name__ == '__main__':
    fn = sys.argv[1]
    lst = sorted([create_node(l[:-1]) for l in open(fn)], key=lambda x: x.id)

    print ('starting replicas')
    for l in lst:
        print('replica for' , l.port)
        init_replicatiom(l, lst)


#!/usr/bin/python

import argparse

def find_max_profit(prices):
    max_profit = float("-inf") # start with neg. infinity (account for least worse loss)
    for p in range(1,len(prices)):
        profit = prices[p] - min(prices[:p])
        if profit > max_profit:
            max_profit = profit
    return max_profit

if __name__ == '__main__':
    # This is just some code to accept inputs from the command line
    parser = argparse.ArgumentParser(description='Find max profit from prices.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
    args = parser.parse_args()

    print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))


import rrdtool

def graficar(rrdpath,imgpath):
    print("\n *****************************************")
    print(" *       = Generación de Gráficas =       *")
    print(" *****************************************\n")

    ultima_lectura = int(rrdtool.last(rrdpath + "CpuLoad1.rrd"))
    tiempo_final = ultima_lectura
    tiempo_inicial = tiempo_final - 600

    ret1 = rrdtool.graph(imgpath + "CPU1.png",
                        "--start", str(tiempo_inicial),
                        "--end", str(tiempo_final),
                        "--vertical-label=Carga CPU 1",
                        "--title=Uso de CPU1",
                        "--color", "ARROW#009900",
                        '--vertical-label', "Uso de CPU1 (%)",
                        '--lower-limit', '0',
                        '--upper-limit', '100',
                        "DEF:carga1=" + rrdpath + "CpuLoad1.rrd:CPUload1:AVERAGE",
                        "CDEF:umbral70=carga1,70,LT,0,carga1,IF",
                        "VDEF:carga1MAX=carga1,MAXIMUM",
                        "VDEF:carga1MIN=carga1,MINIMUM",
                        "VDEF:carga1STDEV=carga1,STDEV",
                        "VDEF:carga1LAST=carga1,LAST",
                        "AREA:carga1#00FF00:Carga del CPU 1",
                        "AREA:umbral70#FF9F00:Tráfico de carga mayor que 70",
                        "HRULE:90#FF0000:Umbral 3 - 90%",
                        "HRULE:80#FFAA00:Umbral 2 - 80%",
                        "HRULE:70#CCFF00:Umbral 1 - 70%",
                        "PRINT:carga1MAX:%6.2lf %S",
                        "GPRINT:carga1MIN:%6.2lf %SMIN",
                        "GPRINT:carga1STDEV:%6.2lf %SSTDEV",
                        "GPRINT:carga1LAST:%6.2lf %SLAST")

    ultimo_valor1 = float(ret1[0])

    ret2 = rrdtool.graphv(imgpath + "CPU2.png",
                          "--start", str(tiempo_inicial),
                          "--end", str(tiempo_final),
                          "--title", "Carga de CPU 2",
                          "--vertical-label=Uso de CPU (%)",
                          '--lower-limit', '0',
                          '--upper-limit', '100',
                          "DEF:carga2=" + rrdpath + "CpuLoad2.rrd:CPUload2:AVERAGE",
                          "CDEF:umbral70=carga2,70,LT,0,carga2,IF",
                          "VDEF:carga2MAX=carga2,MAXIMUM",
                          "VDEF:carga2MIN=carga2,MINIMUM",
                          "VDEF:carga2STDEV=carga2,STDEV",
                          "VDEF:carga2LAST=carga2,LAST",
                          "AREA:carga2#00FF00:Carga del CPU 2",
                          "AREA:umbral70#FF9F00:Tráfico de carga mayor que 70",
                          "HRULE:90#FF0000:Umbral 3 - 90%",
                          "HRULE:80#FFAA00:Umbral 2 - 80%",
                          "HRULE:70#CCFF00:Umbral 1 - 70%",
                          "PRINT:carga2MAX:%6.2lf %S",
                          "GPRINT:carga2MIN:%6.2lf %SMIN",
                          "GPRINT:carga2STDEV:%6.2lf %SSTDEV",
                          "GPRINT:carga2LAST:%6.2lf %SLAST")

    ultimo_valor2 = float(ret2['print[0]'])

    ret_ram = rrdtool.graphv(imgpath + "Ram_Used.png",
                             "--start", str(tiempo_inicial),
                             "--end", str(tiempo_final),
                             "--title", "Memoria Ram utilizada",
                             "--vertical-label=Uso de la RAM (%)",
                             '--lower-limit', '0',
                             '--upper-limit', '100',
                             "DEF:cargaRam=" + rrdpath + "RAMUsed.rrd:RAMUsed:AVERAGE",
                             "CDEF:umbral70=cargaRam,70,LT,0,cargaRam,IF",
                             "VDEF:cargaRamMAX=cargaRam,MAXIMUM",
                             "VDEF:cargaRamMIN=cargaRam,MINIMUM",
                             "VDEF:cargaRamSTDEV=cargaRam,STDEV",
                             "VDEF:cargaRamLAST=cargaRam,LAST",
                             "AREA:cargaRam#00FF00:Uso de la RAM",
                             "AREA:umbral70#FF9F00:Tráfico de carga mayor que 70",
                             "HRULE:90#FF0000:Umbral 3 - 90%",
                             "HRULE:80#FFAA00:Umbral 2 - 80%",
                             "HRULE:70#CCFF00:Umbral 1 - 70%",
                             "PRINT:cargaRamMAX:%6.2lf %S",
                             "GPRINT:cargaRamMIN:%6.2lf %SMIN",
                             "GPRINT:cargaRamSTDEV:%6.2lf %SSTDEV",
                             "GPRINT:cargaRamLAST:%6.2lf %SLAST")

    ultimo_valorRAM = float(ret_ram['print[0]'])

    print(str(ultimo_valor1) + " : " + str(ultimo_valor2) + " : " + str(ultimo_valorRAM))


import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer

# constants
TRAIN_DATA_FILE_PATH = "Lyrics-Genre-Train.csv"
TEST_DATA_FILE_PATH = "Lyrics-Genre-Test-GroundTruth.csv"
LYRICS_COLUMN = "Lyrics"
GENRE_COLUMN = "Genre"

# useful variables
output_mappings = {}

# Pentru ca vrem ca input doar versurile si ca output genul vom citi tot setul de date si vom arunca toate datele
# care nu ne sunt de folos.
def read_data(file_path):
    data = pd.read_csv(file_path)
    # return data[LYRICS_COLUMN], data[GENRE_COLUMN]
    return pd.read_csv(file_path)[[LYRICS_COLUMN, GENRE_COLUMN]]

def create_new_dataset(dataset):
    global output_mappings
    dataset[GENRE_COLUMN] = dataset[GENRE_COLUMN].map(output_mappings)
    return dataset

# Encoding labels with [0, number of labels] so we will have proper outputs
def label_encoding(train_data, test_data):
    possible_labels = train_data[GENRE_COLUMN].unique()
    global output_mappings
    output_mappings = {genre: index for index, genre in enumerate(possible_labels)}
    new_train_data = create_new_dataset(train_data)
    new_test_data = create_new_dataset(test_data)
    return new_train_data, new_test_data

def bag_of_words(train_data, test_data):
    vectorizer = CountVectorizer()
    data = np.concatenate((train_data[LYRICS_COLUMN].as_matrix(), test_data[LYRICS_COLUMN].as_matrix()), axis=0)
    bow_model = vectorizer.fit(data)
    bow = vectorizer.transform(data)
    print(bow)
    return bow

if __name__ == "__main__":
    # Read data
    train_data = read_data(TRAIN_DATA_FILE_PATH)
    test_data = read_data(TEST_DATA_FILE_PATH)
    # changel labeling from string to int
    train_data, test_data = label_encoding(train_data, test_data)

    # Feature extraction

    # Machine learning


"""Support for the Mastertherm Sensors."""
from decimal import Decimal
from datetime import date, datetime
import logging

from homeassistant.core import HomeAssistant
from homeassistant.components.sensor import SensorEntity, SensorDeviceClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ENTITIES, UnitOfTemperature, Platform
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType

from .const import DOMAIN, MasterthermSensorEntityDescription
from .coordinator import MasterthermDataUpdateCoordinator
from .entity import MasterthermEntity

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
):
    """Load Sensors from the config settings."""
    coordinator: MasterthermDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]

    entities: list[SensorEntity] = []
    for entity_key, entity_description in coordinator.entity_types[
        Platform.SENSOR
    ].items():
        for module_key, module in coordinator.data["modules"].items():
            if entity_key in module[CONF_ENTITIES]:
                entities.append(
                    MasterthermSensor(
                        coordinator, module_key, entity_key, entity_description
                    )
                )

    async_add_entities(entities, True)
    coordinator.remove_old_entities(Platform.SENSOR)

class MasterthermSensor(MasterthermEntity, SensorEntity):
    """Representation of a MasterTherm Sensor, e.g. ."""

    def __init__(
        self,
        coordinator: MasterthermDataUpdateCoordinator,
        module_key: str,
        entity_key: str,
        entity_description: MasterthermSensorEntityDescription,
    ):
        """Initialize the sensor."""
        self._icon_state_map = entity_description.icon_state_map

        if entity_description.device_class == SensorDeviceClass.TEMPERATURE:
            entity_description.native_unit_of_measurement = UnitOfTemperature.CELSIUS
            entity_description.suggested_unit_of_measurement = UnitOfTemperature.CELSIUS

        self._attr_state_class = entity_description.state_class

        super().__init__(
            coordinator=coordinator,
            module_key=module_key,
            entity_key=entity_key,
            entity_type=Platform.SENSOR,
            entity_description=entity_description,
        )

    @property
    def icon(self) -> str | None:
        """Set dynamic icons if available."""
        if self._icon_state_map:
            return self._icon_state_map[self.native_value]
        else:
            return self.entity_description.icon

    @property
    def native_value(self) -> StateType | date | datetime | Decimal:
        """Return the sensor value."""
        return self.coordinator.data["modules"][self._module_key]["entities"][
            self._entity_key
        ]


from django.shortcuts import render
from .models import cities, city
from django.http import Http404
from datetime import datetime
import pytz
import folium

now = datetime.now(pytz.timezone('Europe/Warsaw')).strftime("%H")

def weather_view(request, *args, **kwargs):
    cities_ = cities.objects.all()
    city_ = city.objects.all()
    ci_date = city.objects.get(city_id=1)
    if int(now) >= 6 and int(now) < 20:
        for c in city_:
            c.pic = c.pic.replace("n","d")
    context = {
        'cities': cities_,
        'city': city_,
        'c_date':ci_date,
    }
    return render(request, "weather.html", context)

def weather_view_detail(request,pk):
    city_ = city.objects.get(city_id=pk)
    city_name = cities.objects.get(id=pk)
    city_name_n = city_name.name.replace(" ","_")

    timezone = int(city_.timezone) // 3600
    timezone = f"UTC {('+' if timezone >= 0 else '')}{timezone}"
    sunset = city_.sunset
    sunrise = datetime.utcfromtimestamp(city_.sunrise).strftime("%H:%M")
    sunset = datetime.utcfromtimestamp(sunset)
    sunset = sunset.strftime("%H:%M")
    if int(now) >= 6 and int(now) < 20:
        city_.pic = city_.pic.replace("n","d")

    m = folium.Map(location=[city_.lat, city_.lon], zoom_start=12)
    folium.Marker([city_.lat, city_.lon], popup=city_name.name).add_to(m)
    map_html = m._repr_html_()

    context = {
        'map_html': map_html,
        'city': city_,
        'name_space': city_name.name,
        'name' : city_name_n,
        'timezone': timezone,
        'sunrise': sunrise,
        'sunset': sunset,

    }
    if city_ is not None:
        return render(request, 'detail.html', context)
    else:
        raise Http404('Something gone wrong')

# def index(request):
#     cities_ = cities.objects.all()
#     return render(request, 'weather/index.html', {'cities': cities_})
#
# def city(request, city_id):
#     city_ = city.objects.get(id=city_id)
#     return render(request, 'weather/city.html', {'city': city_})