import cv2
def collage(imag):
    vi=cv2.VideoCapture("C:\\Users\\anand\\Videos\\cheeta.mp4")
    fps=int(vi.get(cv2.CAP_PROP_FPS))
    w=int(vi.get(cv2.CAP_PROP_FRAME_WIDTH))
    h=int(vi.get(cv2.CAP_PROP_FRAME_HEIGHT))
    op=cv2.VideoWriter("C:\\Users\\anand\\Videos\\cheeta.avi",cv2.VideoWriter_fourcc('X','V','I','D'),fps,(w,h))
    while True:
        success,frame=vi.read()
        if success:
            frame[0:270,1180:1280]=imag
            frame=cv2.copyMakeBorder(frame,10,10,10,10,cv2.BORDER_CONSTANT,value=[255,0,0])
            cv2.imshow("Video",frame)
            op.write(frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break
    vi.release()
    op.release()
    cv2.destroyAllWindows()

liberty=cv2.imread("C:\\Users\\anand\\Pictures\\Liberty.jpg",1)
statue=liberty[50:320,180:280]
collage(statue)


# Tower of hanoi
"""
n - number of disks
move top n-1 disk from A to B using c as intermediate
move the remaining disk from A to C
move n-1 disks from B to C using A as intermediate
"""
def towers(n,source,destination,support):    # n =  number of disk, a,b,c = towers
    if n==1:
        # if only one disk, then move it from A to C directly
        print("move disk %i from pole %s to pole %s"%(n,source,destination))
    else:
        towers(n-1,source,support,destination) # first move n-1 disk to B, i.e. using C as intermediate
        print("move disk %i from pole %s to pole %s"%(n,source,destination)) # move remaining 1 disk to C
        towers(n-1,support,destination,source) # ni1 disk move from B to C

towers(2,"A","C","B") # A = starting, C finishing , B intermediate


from scapy.all import *
from scapy.contrib.pnio_rpc import *
from scapy.contrib.dce_rpc import *
from scapy.contrib.pnio import *

import crcmod

from helper.gsdml_parser import XMLDevice

load_contrib("pnio")
load_contrib("pnio_rpc")
load_contrib("dce_rpc")

class PNIOPSMessage:
    def __init__(self) -> None:
        self.cycle_counter = 0
        self.data_status = {
            "ignore": False,  # 1: Ignore 0: Evaluate
            "reserved_2": False,  # should be zero
            "station_problem_indicator": False,  # 1: Ok, 0: Problem
            "provider_state": False,  # 1: Run 0: Stop
            "reserved_1": False,  # should be zero
            "data_valid": False,  # 1: Valid, 0: Invalid
            "redundancy": False,  # has no meaning for outputCRs
            "state": False,  # 1: primary, 0. backup
        }
        self.input_data = {"iops": [], "iocs": [], "data": []}

    def convert_number_to_state_array(self, flags):
        self.data_status = {
            "ignore": flags.ignore,  # 1: Ignore 0: Evaluate
            "reserved_2": flags.reserved_2,  # should be zero
            "station_problem_indicator": flags.no_problem,  # 1: Ok, 0: Problem
            "provider_state": flags.run,  # 1: Run 0: Stop
            "reserved_1": flags.reserved_1,  # should be zero
            "data_valid": flags.validData,  # 1: Valid, 0: Invalid
            "redundancy": flags.redundancy,  # has no meaning for outputCRs
            "state": flags.primary,  # 1: primary, 0. backup
        }

    def bitarray_to_number(self, array):
        i = 0
        for bit in array:
            i = (i << 1) | bit
        return i

    def parse_io_state(self, state, slot, subslot):
        status_array = [int(digit) for digit in bin(state + 0x100)[2:]][1:]
        return {
            "module": str(slot),
            "submodule": str(subslot),
            "data_state": bool(status_array[0]),  # 1: Good 0: Bad
            "instance": self.bitarray_to_number(
                status_array[1:3]
            ),  # should be zero 0: Detected by subslot
            "reserved": self.bitarray_to_number(status_array[3:7]),  # should be zero
            "extension": bool(
                status_array[7]
            ),  # 0: No IOxS octet follows 1: IOxS octet follows
        }

    def parse_input_data(self, data, device):
        usable_modules = device.body.dap_list[0].usable_modules

        payload_bytes = list(data)

        first_iops = self.parse_io_state(payload_bytes[0], 0x1, 0x1)

        sec_iops = self.parse_io_state(payload_bytes[1], 0x1, 0x8000)

        thir_iops = self.parse_io_state(payload_bytes[2], 0x1, 0x8001)

        iops = [first_iops, sec_iops, thir_iops]
        iocs = []
        data = []

        output_frame_offset = 3

        for module in usable_modules:
            if module.used_in_slots != "" and module.output_length != 0:
                data.append(
                    payload_bytes[
                        output_frame_offset : (
                            output_frame_offset + module.output_length
                        )
                    ]
                )
                iops.append(
                    self.parse_io_state(
                        payload_bytes[output_frame_offset + module.output_length],
                        module.module_ident_number,
                        module.submodule_ident_number,
                    )
                )
                output_frame_offset += module.output_length + 1
        for module in usable_modules:
            if module.used_in_slots != "" and module.input_length != 0:
                iocs.append(
                    self.parse_io_state(
                        payload_bytes[output_frame_offset],
                        module.module_ident_number,
                        module.submodule_ident_number,
                    )
                )
                output_frame_offset += 1

        self.input_data = {"iops": iops, "iocs": iocs, "data": data}

def parse_data_message(packet, device):
    message = PNIOPSMessage()

    if packet.haslayer("PROFINET IO Real Time Cyclic Default Raw Data"):
        pkt_rt = packet.getlayer("PROFINET Real-Time")
        pkt_raw_layer = packet.getlayer("PROFINET IO Real Time Cyclic Default Raw Data")
        message.convert_number_to_state_array(pkt_rt.dataStatus)
        message.cycle_counter = pkt_rt.cycleCounter
        message.parse_input_data(pkt_raw_layer.data, device)

        return message

    else:
        return

    # CRC24bit

crc24_func = crcmod.mkCrcFun(0x15D6DCB, initCrc=0, xorOut=0x0, rev=False)
scapy_cap = rdpcap("../sniff/only_status_msgs.pcap")
device = XMLDevice("../gsdml/test_project.xml")

for idx, packet in enumerate(scapy_cap[4:]):
    pdu = bytearray(parse_data_message(packet, device).input_data["data"][0])
    print(pdu[0:9])
    print(hex(int.from_bytes(bytes(pdu[9:]), "little")))
    # checksum should be #3345b6
    def someWork():
        for i1 in range(0, 256):
            for i2 in range(0, 256):
                for i3 in range(0, 256):
                    # print(bytearray([0x0, i1, i2, i3] + list(pdu[0:9])))
                    if (
                        hex(
                            crc24_func(
                                bytearray([0x0, i1, i2, i3] + list(pdu[0:9]))[::-1],
                                crc=0x22FF,
                            )
                        )
                        == hex(int.from_bytes(bytes(pdu[9:]), "big"))
                    ):
                        print(idx)
                        print("vcn", hex(i1), hex(i2), hex(i3))
                        print("_---------------------")
                        return
    someWork()

    # packet.getlayer("PROFINET Real-Time").data.getLayer("PROFINET IO Real Time Cyclic Default Raw Data").show()
    # PROFIsafe(packet.getlayer("PROFINET Real-Time").getLayer("PROFINET IO Real Time Cyclic Default Raw Data")).show()


import imutils
import shutil
import numpy as np
import copy
import glob
import cv2
import os
import re

PIC_NAMES = [
    #'alien',
    'alienmonster',
    #'avocado',
    'beamingfacewithsmilingeyes',
    #'baguettebread',
    'butterfly',
    'banana',
    'babychick',
    'balloon',
    'books',
    'bird',
    #'cat',
    'cactus',
    'carrot',
    #'clapperboard',
    'dragon',
    #'dog',
    #'duck',
    'eyes',
    'fox',
    'fire',
    'fish',
    'frog',
    #'flagpoland',
    'ghost',
    'growingheart',
    'gemstone',
    #'hamburger',
    'honeybee',
    'lizard',
    'octopus',
    'okhandlightskintone',
    'parrot',
    'panda',
    'penguin',
    'pizza',
    'purpleheart',
    'rainbow',
    #'radioactive',
    #'rabbit',
    #'rabbitface',
    'recyclingsymbol',
    'rooster',
    #'rocket',
    #'smilingfacewithsmilingeyes',
    #'shark',
    'shield',
]

PAL_DIR = os.path.join('backend', 'palette')
DEST_DIR = os.path.join('static', 'emotes')
stack = None
SIZE = 40

for family in os.listdir(PAL_DIR):
    path = os.path.join(PAL_DIR, family)
    count = 0
    if os.path.isdir(path):
        "CHECK FAMILY Loop LEVEL"
        destination = os.path.join(DEST_DIR, family)
        os.makedirs(destination, exist_ok=True)

        for fil in os.listdir(path):
            name = os.path.basename(fil)[:-4]
            src = os.path.join(path, fil)
            dst = os.path.join(destination, fil)

            if name in PIC_NAMES:
                shutil.copyfile(src, dst)
                count += 1

        all_pics = copy.copy(PIC_NAMES)
        preview = None
        for name in PIC_NAMES:
            "Check pictures in order from list"
            fil = f"{name}.png"

            img_array = cv2.imread(os.path.join(destination, fil), cv2.IMREAD_UNCHANGED)
            try:
                img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2BGRA)
                img_array = cv2.resize(img_array, (SIZE,SIZE))
                all_pics.pop(all_pics.index(name))
            except Exception:
                img_array = np.zeros((SIZE,SIZE,4), dtype=np.uint8)
                #img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2BGRA)

            if preview is not None:
                #print(preview.shape, img_array.shape)
                preview = np.concatenate([preview, img_array], axis=1)
            else:
                preview = img_array

        "Save preview image is exists"
        if preview is not None:
            cv2.imwrite(os.path.join(DEST_DIR, f"{family}.png"), preview)
            if stack is not None:
                stack = np.concatenate([stack, preview], axis=0)
            else:
                stack = preview

        print()
        print(f"{path}")
        print(f"missing:\n{all_pics}")

if stack is not None:
    cv2.imwrite(os.path.join(DEST_DIR, f"STACK.png"), stack)


command = ''
started = False
while True:

    command = input('> ').lower()

    if command == 'start':
        if started:

            print('Hoy, car is started')
        else:
            started = True
            print('Car Started... Ready to go')

    elif command == 'stop':
        if not started:
            print('Hoy, car is stopped')
        else:
            started = False
            print('Car stopped')

    elif command == 'quit':
        print('Good by then.')
        break

    elif command == 'help':
        print("""
 start - to start the car
 stop - to stop the car
 exit - to exit
        """)

    else:
        print("I don't understand")


from sys import argv
from os.path import abspath
from os import getenv
import json
import codecs

type_ = argv[1]
alias, code_dir = argv[2:4]
home = '/home/'+getenv("SUDO_USER")
if type_ == "file":
	code_lit = ""
	with open(abspath(code_dir),'r') as codeF:
		line = codeF.readline()
		while line:
			code_lit += line
			line = codeF.readline()
else:
	code_lit = code_dir

with open(f'{home}/.SHDev/program.json','r') as programF:
	aliases = json.load(programF)
	if alias in aliases:
		print(f"Alias {alias} already exist")
		exit()
	else:
		aliases[alias] = code_lit
with open(f'{home}/.SHDev/program.json','w') as programF:
	json.dump(aliases,programF)
with open(f'{home}/.SHDev/SHDev.sh',"w") as SHDevF:
	for value in aliases.values():
		SHDevF.write(value+'\n')


# Util classes from utils file
from utils import Stack
from utils import Queue

# This BFS will take the player back to the nearest room that has an unexplored exit
def uncharted_path(currentPath, room_id, player):
    # Create an empty set to store visited nodes
    visited = set()
    # Create an empty Queue and enqueue A PATH TO the starting vertex
    q = Queue()
    path = [room_id]
    q.enqueue(path)
    # While the queue is not empty...
    while q.size() > 0:
        # Dequeue the first PATH
        p = q.dequeue()
        # GRAB THE VERTEX FROM THE START OF THE PATH
        v = p[0]
        # IF VERTEX == TARGET ('?'), SET PATH THEN BREAK
        if v == '?':
            path = p[1:]
            break
        # If that vertex has not been visited...
        if v not in visited:
            # Mark it as visited
            visited.add(v)
            # Then add A PATH TO all of its neighbors to the back of the queue
            for neighbors in currentPath[v]:
                node = currentPath[v][neighbors]
                new_path = p.copy()
                new_path.insert(0, node)
                q.enqueue(new_path)
    # this list will contain the directions that the player needs to move back
    movements = []

    # While loop runs trying to create a path of movements
    while len(path) > 1:
        # remove the last room and store as a variable
        current = path.pop(-1)
        # find the direction that will take you to the prior room and add it to a movements list
        for route in currentPath[current]:
            if currentPath[current][route] == path[-1]:
                movements.append(route)

    # for every element in movements, move in that direction until you reach the spot
    for move in movements:
        player.travel(move)

    # return the movements to be appended to traversalPath
    return movements

# This function is only for getting the opposite compass pointer to update our question marks for the room we just came from
def inverse_point(point):
    if point == 'n':
        direc = 's'
    elif point == 's':
        direc = 'n'
    elif point == 'e':
        direc = 'w'
    elif point == 'w':
        direc = 'e'
    return direc


"""Problem Description:
Aaron has a number D containing only digits 0's and 1's. He wants to make the number to have all the digits same. For that, he will change exactly one digit, i.e. from 0 to 1 or from 1 to 0.
If it is possible to make all digits equal (either all 0's or all 1's) by flipping exactly 1 digit then output "Yes", else print "No" (quotes for clarity)
Constraints:
1 ≤ T ≤ 10
1 ≤ Length of the number D ≤ 10
Input Format:
The first line will contain an integer 'T' representing the number of test cases.
Each test case contain a number made of only digits 1's and 0's on newline
Output Format:
Print T lines with a "Yes" or a "No", depending on whether its possible to make it all 0s or 1s or not.

Logical Test Cases
Test Case 1
INPUT (STDIN)
3
1010
101
100
EXPECTED OUTPUT
NO
YES
Test Case 2
INPUT (STDIN)
6
010
1101
0011
101110
0001
0010
EXPECTED OUTPUT
YES
NO
NO
YES"""

def check_all_same(s):
    # Count number of 0s and 1s
    count_0 = s.count('0')
    count_1 = s.count('1')

    # If all digits are already same, return Yes
    if count_0 == len(s) or count_1 == len(s):
        return "YES"
    # If there is only one 0 or one 1, return Yes
    if count_0 == 1 or count_1 == 1:
        return "YES"
    # If there is more than one 0 and more than one 1, return No
    if count_0 > 1 and count_1 > 1:
        return "NO"
    # If there is exactly one 0 and more than one 1, or exactly one 1 and more than one 0, return Yes
    else:
        return "YES"
if __name__ == "__main__":
    # Get number of test cases
    T = int(input())
    # Loop over all test cases
    for i in range(T):
        # Get input string
        s=str(input())
        # Call function to check if all digits can be made same by flipping one digit
        result = check_all_same(s)
        # Print the result
        print(result)


from http.client import responses
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from scipy.stats import chi2_contingency
from sklearn.preprocessing import LabelEncoder

import matplotlib as plt
import seaborn as sns

url="http://data.insideairbnb.com/singapore/sg/singapore/2021-10-28/visualisations/listings.csv"
data =pd.read_csv(url)

new_data=data.copy()

# x1: reviews_per_month  --> mean_rpm: 0.65
mean_rpm="{:.2f}".format((data.iloc[:,-5]).mean(skipna=True))
(new_data.iloc[:,-5]).fillna(value=mean_rpm,inplace=True)

# x2: availability_365   --> mean_nor: 239.63
mean_nor="{:.2f}".format((data.iloc[:,-3]).mean(skipna=True))
(new_data.iloc[:,-3]).fillna(value=mean_nor,inplace=True)

with open ("/Users/faritorab/Desktop/newlisting.csv" , 'w') as f:
    new_data.to_csv(f)

# print(new_data.head())
#        id                                              name  host_id host_name  ... calculated_host_listings_count availability_365  number_of_reviews_ltm  license
# 0   50646                   Pleasant Room along Bukit Timah   227796   Sujatha  ...                              1              365                      0      NaN
# 1   71609               Ensuite Room (Room 1 & 2) near EXPO   367042   Belinda  ...                              4              365                      0      NaN
# 2   71896                   B&B  Room 1 near Airport & EXPO   367042   Belinda  ...                              4              365                      0      NaN
# 3   71903                        Room 2-near Airport & EXPO   367042   Belinda  ...                              4              365                      0      NaN
# 4  275343  Conveniently located City Room!(1,2,3,4,5,6,7,8)  1439258     Joyce  ...                             50              343                      0      NaN

# [5 rows x 18 columns]

X=new_data[["reviews_per_month","availability_365"]]
y=new_data["price"]

print("X: \n",X)
# X:
#       reviews_per_month  availability_365
# 0                 0.21               365
# 1                 0.27               365
# 2                 0.32               365
# 3                 0.64               365
# 4                 0.19               343
# ...                ...               ...
# 4118              0.65               362
# 4119              0.65               365
# 4120              0.65               358
# 4121              0.65               364
# 4122              0.65               358
print("y:\n",y)
# y:
#  0        80
# 1       177
# 2        81
# 3        81
# 4        52
#        ...
# 4118    123
# 4119     88
# 4120     58
# 4121    276
# 4122    480

regr = LinearRegression()
regr.fit(X, y)

print('b0: \t', regr.intercept_)
# b0: 174.4405622545075

print('slope: \t', regr.coef_)
# slope: [-6.76081324  0.0507245 ]

print('R^2: \t', regr.score(X, y))
# R^2: 0.0006654739313914915

response = regr.predict(X)
print('predicted response:', response, sep='\n')
# predicted response:
# [191.5352338  191.129585   190.79154434 ... 188.20540448 188.50975147
#  188.20540448]

#------------------------------------------------------------------------------------------------------------------------------------

contingency_table = pd.crosstab(
    new_data['neighbourhood_group'],
    new_data['room_type'],
    margins = True
)

print(contingency_table)
# room_type            Entire home/apt  Hotel room  Private room  Shared room   All
# neighbourhood_group
# Central Region                  1547         179          1448          132  3306
# East Region                       54           3           201            6   264
# North Region                      13           0           100            6   119
# North-East Region                 33           0           106            4   143
# West Region                      122           0           158           11   291
# All                             1769         182          2013          159  4123

# print(stats.chi2_contingency(crosstab))

# neighbourhood_group = new_data["neighbourhood_group"]
# # l=LabelEncoder()
# # neighbourhood_group=l.fit_transform(neighbourhood_group)

# room_type=new_data["room_type"]
# # l=LabelEncoder()
# # room_type=l.fit_transform(room_type)

x_squared, p, dof, expected = chi2_contingency(contingency_table)

print(x_squared,"\n", p,"\n", dof,"\n",expected )


from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import numpy as np
import itertools

#file path predicted labels
file_path_pred = '/home/kenelly/workspaces/emotionnewsheadlines/emotiondetection/resources/model_unsupervised_ml_output.txt'

#file path true labels
file_path_true = '/home/kenelly/workspaces/emotionnewsheadlines/emotiondetection/resources/semeval2007testunsupervisedml.txt'

#function to collect the predicted and true labels from the files
def emotion_pred(file_path_pred):
    with open(file_path_pred) as f:
        emotion_list_pred = list()
        for line in f:
            line_vec = line.split(" ")
            emotion = line_vec[0].replace("__label__", "")
            emotion_list_pred.append(emotion)
        return emotion_list_pred

#function to collect the predicted and true labels from the files
def emotions(file_path_pred, file_path_true):
    pred = emotion_pred(file_path_pred)#src/python/evaluationml.py:24
    pred_final = []
    true_final = []
    i=0
    with open(file_path_true) as p:
        for line in p:
            line_vec = line.split(" ")
            for label in line_vec:
                if label.startswith('__label__'):
                    emotion_true = label.replace("__label__", "")
                    true_final.append(emotion_true)
                    pred_final.append(pred[i])
            i+=1

    return pred_final, true_final

y_pred, y_true = emotions(file_path_pred, file_path_true)

#function to calculate multilabel metrics
def metrics(y_true, y_pred):

    precision, recall, f_score, _ = \
        precision_recall_fscore_support(y_true, y_pred, average='macro')

    accuracy = accuracy_score(y_true, y_pred)

    print('Precision:' + str(precision) + '\nRecall:' + str(recall) +
          '\nF1 score:'+ str(f_score) + '\nAccuracy:' + str(accuracy))

#function to calculate the metrics by label
def metrics_labels(y_true, y_pred):

    target_names = ['anger','disgust','fear','joy','sadness','surprise']
    print(classification_report(y_true, y_pred, target_names=target_names))

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '17f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()

target_names = ['anger','disgust','fear','joy','sadness','surprise']
metrics(y_true, y_pred)
metrics_labels(y_true, y_pred)
confusionmatrix = confusion_matrix(y_true, y_pred, labels=['anger','disgust','fear','joy','sadness','surprise'])
np.set_printoptions(precision=2)
plt.figure()
plot_confusion_matrix(confusionmatrix, classes=target_names,
                      title='Confusion matrix multi-label')
plt.show()
print(confusionmatrix)


import asyncio

from services import file_manager
from services import rcon_manager
from services import permission_manager
from services import db_access
from datetime import datetime, timedelta

config = file_manager.load_config()

def main_check():
    for x in config["servers"]:

        tribe_list = rcon_manager.player_tribe_check(x["address"], x["password"], x["rcon_port"])
        print(tribe_list)
        if tribe_list is None:
            continue

        map_name = rcon_manager.get_server_map(x["address"], x["query_port"])
        if map_name is None:
            continue

        print("checking " + map_name + " on server: " + x["address"], x["query_port"])
        update_users(tribe_list, map_name)

    check_tribe_leave()

def update_users(tribe_list: list, map_name: str):
    timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
    new_members = []

    # update or set database record for user
    connection = db_access.get_connection()
    context = connection.cursor(buffered=True)
    for x in tribe_list:
        # try to find user
        context.execute(f"SELECT * FROM tribes WHERE steam_id = {x[0]} AND tribe_name = '{x[1]}' AND map_name = '{map_name}'")
        record = context.fetchone()

        if record is None:
            # set user record
            context.execute(f"INSERT INTO `tribes`(steam_id,tribe_name,tribe_size,map_name,last_seen)"
                            f" VALUES ({x[0]}, '{x[1]}', {0}, '{map_name}', '{timestamp}')")

            # update tribe size
            new_members.append(x[0])
        else:
            # update last seen
            context.execute(f"UPDATE tribes SET last_seen = '{timestamp}' WHERE steam_id = {x[0]} AND map_name = '{map_name}'")

    context.close()
    connection.commit()
    connection.close()

    members_to_update = []
    # update added members
    for y in new_members:
        tribe_name = get_current_tribe(y, map_name)
        members_to_update.extend(get_tribe_members(tribe_name, map_name))

    for z in members_to_update:

        tribe_name = get_current_tribe(z, map_name)
        calculate_tribe_size(z, tribe_name, map_name)
        max_size = get_max_tribe_size(z)
        print("updating member: " + str(z))
        permission_manager.set_tribe_rank(z, max_size)

# calculate all ranks for tribe based on one new member who joined
def calculate_tribe_size(steam_id: int, tribe_name: str, map_name: str):
    connection = db_access.get_connection()
    context = connection.cursor(buffered=True)

    tribe_size = len(get_tribe_members(tribe_name, map_name))
    tribe_name = get_current_tribe(steam_id, map_name)

    # solo no tribe Check
    # if tribe_name == "":
    #     tribe_size = 1

    context.execute(f"UPDATE tribes SET tribe_size = {tribe_size} WHERE steam_id = {steam_id} AND tribe_name = '{tribe_name}' AND map_name = '{map_name}' AND tribe_name != '[]' ")

    context.close()
    connection.commit()
    connection.close()

def get_tribe_members(tribe_name: str, map_name: str):
    connection = db_access.get_connection()
    context = connection.cursor(buffered=True)

    context.execute(f"SELECT steam_id FROM tribes WHERE tribe_name = '{tribe_name}' AND map_name = '{map_name}'")
    tribe_members = list(sum(context.fetchall(), ()))

    context.close()
    connection.close()
    return tribe_members

def get_current_tribe(steam_id: int, map_name: str):
    connection = db_access.get_connection()
    context = connection.cursor(buffered=True)

    # review
    context.execute(f"SELECT tribe_name FROM tribes WHERE steam_id = {steam_id} AND map_name = '{map_name}' AND last_seen = (SELECT MAX(last_seen) FROM tribes WHERE steam_id = {steam_id} AND map_name = '{map_name}')")
    record = context.fetchone()

    context.close()
    connection.close()
    return record[0]

def check_tribe_leave():
    connection = db_access.get_connection()
    context = connection.cursor(buffered=True)
    time = datetime.utcnow() - timedelta(hours=22)

    context.execute(f"SELECT * FROM tribes WHERE last_seen < '{time}'")
    expired_members = context.fetchall()
    context.execute(f"DELETE FROM tribes WHERE last_seen < '{time}'")

    context.close()
    connection.commit()
    connection.close()

    # recalculate tribe size for all tribes who had members that expired
    for x in expired_members:
        print(x)
        tribe_members = get_tribe_members(x[2], x[4])
        print("found members")
        print(tribe_members)

        for y in tribe_members:
            calculate_tribe_size(y, x[2], x[4])

def get_max_tribe_size(steam_id: str):
    connection = db_access.get_connection()
    context = connection.cursor(buffered=True)
    time = datetime.utcnow() - timedelta(hours=22)

    # exclude solo tribes here
    context.execute(f"SELECT tribe_size FROM tribes WHERE steam_id = '{steam_id}' AND tribe_name != '[]' ")
    record = context.fetchall()

    max_size = 0
    for x in record:
        if x[0] > max_size:
            max_size = x[0]

    context.close()
    connection.commit()
    connection.close()

    return max_size

def get_steam_id(discord_id: str):
    connection = db_access.get_connection()
    context = connection.cursor(buffered=True)

    context.execute(f"SELECT SteamId FROM discordaddonplayers WHERE discid = '{discord_id}'")
    record = context.fetchone()

    if not record:
        context.close()
        connection.commit()
        connection.close()
        return None

    else:
        context.close()
        connection.commit()
        connection.close()
        return record[0]

async def loop_task():
    while True:
        main_check()
        await asyncio.sleep(config["general"]["tribe_check_interval"])

task = asyncio.ensure_future(loop_task())


#!/usr/bin/python3

'''
Using names.txt, a file containing over 5000 first names, begin by
sorting it into alphabetical order. Then working out the alphabetical
value for each name, multiply this value by its alphabetical position
in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN,
which is worth 3+15+12+9+14=53, is the 938th name in the list. So,
COLIN would obtain a score of 938 * 53 = 49714.

What is the total of all the name scores in the file?
'''

import time
import re

start = time.time()

# read through file, clean up names, return names as sorted list
def slurp_names():
    names = ''
    with open('names.txt') as f:
        names = f.readlines()[0]
        names = re.sub('"', '', names)
        names = names.split(',')
    return sorted(names)

# return the value of a letter using its ascii value
def get_char_value(char):
    return ord(char) - 64 # 'A' = 65, 'Z' = 90

# return the sum of character values in a name
def get_name_value(name):
    total = 0
    for char in name:
        total += get_char_value(char)
    return total

names = slurp_names()
total = 0
for i in range(len(names)):
    name_value = get_name_value(names[i])
    total += name_value * (i+1)

print(total)

end = time.time()
print('{}s'.format(end-start))


import datetime
from typing import Callable, List

MIGRATIONS: List[Callable] = []
migration = MIGRATIONS.append

def migrate(db):
    ensure_migrations_table(db)
    already_applied = {r["name"] for r in db["_llm_migrations"].rows}
    for fn in MIGRATIONS:
        name = fn.__name__
        if name not in already_applied:
            fn(db)
            db["_llm_migrations"].insert(
                {"name": name, "applied_at": str(datetime.datetime.utcnow())}
            )
            already_applied.add(name)

def ensure_migrations_table(db):
    if not db["_llm_migrations"].exists():
        db["_llm_migrations"].create(
            {
                "name": str,
                "applied_at": str,
            },
            pk="name",
        )

@migration
def m001_initial(db):
    # Ensure the original table design exists, so other migrations can run
    if db["log"].exists():
        # It needs to have the chat_id column
        if "chat_id" not in db["log"].columns_dict:
            db["log"].add_column("chat_id")
        return
    db["log"].create(
        {
            "provider": str,
            "system": str,
            "prompt": str,
            "chat_id": str,
            "response": str,
            "model": str,
            "timestamp": str,
        }
    )

@migration
def m002_id_primary_key(db):
    db["log"].transform(pk="id")

@migration
def m003_chat_id_foreign_key(db):
    db["log"].transform(types={"chat_id": int})
    db["log"].add_foreign_key("chat_id", "log", "id")

@migration
def m004_column_order(db):
    db["log"].transform(
        column_order=(
            "id",
            "model",
            "timestamp",
            "prompt",
            "system",
            "response",
            "chat_id",
        )
    )

@migration
def m004_drop_provider(db):
    db["log"].transform(drop=("provider",))

@migration
def m005_debug(db):
    db["log"].add_column("debug", str)
    db["log"].add_column("duration_ms", int)

@migration
def m006_new_logs_table(db):
    columns = db["log"].columns_dict
    for column, type in (
        ("options_json", str),
        ("prompt_json", str),
        ("response_json", str),
        ("reply_to_id", int),
    ):
        # It's possible people running development code like myself
        # might have accidentally created these columns already
        if column not in columns:
            db["log"].add_column(column, type)

    # Use .transform() to rename options and timestamp_utc, and set new order
    db["log"].transform(
        column_order=(
            "id",
            "model",
            "prompt",
            "system",
            "prompt_json",
            "options_json",
            "response",
            "response_json",
            "reply_to_id",
            "chat_id",
            "duration_ms",
            "timestamp_utc",
        ),
        rename={
            "timestamp": "timestamp_utc",
            "options": "options_json",
        },
    )

@migration
def m007_finish_logs_table(db):
    db["log"].transform(
        drop={"debug"},
        rename={"timestamp_utc": "datetime_utc"},
        drop_foreign_keys=("chat_id",),
    )
    with db.conn:
        db.execute("alter table log rename to logs")

@migration
def m008_reply_to_id_foreign_key(db):
    db["logs"].add_foreign_key("reply_to_id", "logs", "id")

@migration
def m008_fix_column_order_in_logs(db):
    # reply_to_id ended up at the end after foreign key added
    db["logs"].transform(
        column_order=(
            "id",
            "model",
            "prompt",
            "system",
            "prompt_json",
            "options_json",
            "response",
            "response_json",
            "reply_to_id",
            "chat_id",
            "duration_ms",
            "timestamp_utc",
        ),
    )

@migration
def m009_delete_logs_table_if_empty(db):
    # We moved to a new table design, but we don't delete the table
    # if someone has put data in it
    if not db["logs"].count:
        db["logs"].drop()

@migration
def m010_create_new_log_tables(db):
    db["conversations"].create(
        {
            "id": str,
            "name": str,
            "model": str,
        },
        pk="id",
    )
    db["responses"].create(
        {
            "id": str,
            "model": str,
            "prompt": str,
            "system": str,
            "prompt_json": str,
            "options_json": str,
            "response": str,
            "response_json": str,
            "conversation_id": str,
            "duration_ms": int,
            "datetime_utc": str,
        },
        pk="id",
        foreign_keys=(("conversation_id", "conversations", "id"),),
    )

@migration
def m011_fts_for_responses(db):
    db["responses"].enable_fts(["prompt", "response"], create_triggers=True)


# defining a node object construct
class Node:
    def __init__(self, value):
        self.value = value
        self.nextnode = None

# making some nodes
a = Node("monday")
b = Node("teusday")
c = Node("wednessday")
d = Node("thursday")
e = Node("friday")
f = Node("saturday")
# linking these nodes
a.nextnode = b
b.nextnode = c
c.nextnode = d
d.nextnode = e
e.nextnode = f
#defining a list construct and print function
class linklist:
    def __init__(self):
        self.head = None
    def printlist(self): # to print the list
        headpointer = self.head
        while(headpointer is not None):
            print(headpointer.value, end = " ")
            headpointer = headpointer.nextnode
    # to add a node in start, end and in between at a specific index
    def atstart(self, value):
        newnode = Node(value)
        newnode.nextnode = self.head
        self.head = newnode

    def atEnd(self, value):
        headpointer = self.head
        newnode = Node(value)
        if(headpointer is None):
            newnode.nextnode = headpointer
            headpointer = newnode
        else:
            while(headpointer.nextnode is not None):
                    headpointer = headpointer.nextnode
                    if(headpointer.nextnode is None):
                        headpointer.nextnode = newnode
                        return
    def sizeLinklist(self):
            headpointer = self.head
            count = 0
            while(headpointer):
                count+=1
                headpointer = headpointer.nextnode
            return count

    def insertposition(self, value, index):
        if( index < 1 or index > l.sizeLinklist()):
            print(" the position is out of range")
        elif( index == 1):
                self.atstart(value)
        elif( index == l.sizeLinklist()+1):
                self.atEnd(value)
        else:
            headpointer = self.head
            count = 1
            while(headpointer is not None and count < index-1):
                count += 1
                headpointer = headpointer.nextnode
            newnode = Node(value)
            newnode.nextnode = headpointer.nextnode
            headpointer.nextnode = newnode

# the main program of building link list start
l = linklist()
# declaring first node to head
l.head = a
# linking first node
l.head.nextnode = b

#l.atstart("sunday")
#print("your sinlgly linklist new element added at start is: ")
#l.printlist()
#print("\nyour singly linklist new element added at end is: ")
#l.atEnd("superSunday")
l.printlist()
print("\n the size of the list is: ", l.sizeLinklist())
l.insertposition("super wednessday", 6)
print("\nyour list after inserting of new element at nth position ")
l.printlist()


import layers
import cv2
import numpy as np
import utils
from PIL import Image
import computationalgraph

def load_images(filenames, IMG_SIZE=50):
    images = []

    for filename in filenames:
        #X shape is [WIDTH, HEIGHT, CHANNELS]
        X = cv2.imread(filename)
        #Resize X to [IMG_SIZE, WIDTH, HEIGHT]
        X = cv2.resize(X, (IMG_SIZE, IMG_SIZE))
        #Transform X to shape [CHANNELS, HEIGHT, WIDTH]
        X = X.transpose(2, 0, 1)
        #X = X[np.newaxis, :, :, :]
        images.append(X)

    return np.stack(images, axis=0)

X = load_images(["billie.png"], IMG_SIZE=50)
print(X.shape)

T = np.array([1,0,0,0,0])
T = T.T

######################################################################################################################
conv = layers.Convolution(kernel_size=3, kernel_channels=3, n_kernels=10, stride=1, same_padding=True)
X  = conv.forward(X)
print("[+] CONVOLVED_shape:", X.shape)
print()

activation = layers.Activation(activation="relu")
X = activation.forward(X)
print("[+] ACTIVATION_shape:", X.shape)
dActivation = activation.backward(np.ones_like(X))
print("dActivation_SHAPE:", dActivation.shape)
print()

maxpool = layers.MaxPooling(window_size=2, window_channels=10, stride=2)
X = maxpool.forward(X)
print("[+] MAXPOOLED_shape:", X.shape)
dMaxpool = maxpool.backward(np.ones_like(X))
print("dMaxpool_SHAPE:", dMaxpool.shape)

N, C, H, W = X.shape

flatten = layers.Flatten((C*H*W, N))
X = flatten.forward(X)
print(X.shape)

I, N = X.shape

fc1 = layers.FullyConnected("fc1", I, 1000, activation="relu")
X = fc1.forward(X)
print(X.shape)

fc2 = layers.FullyConnected("fc2", 1000, 10, activation="softmax")
Y = fc2.forward(X)
print(Y.shape)

cross_entropy = layers.CrossEntropy()
loss = cross_entropy.forward(Y, T)
print(loss)
######################################################################################################################

'''
print()

print("XSHAPE:", X.shape)
print()

N, C, H, W = X.shape

for n in range(N):
    for i in range(C):
        Xi = X[n][i]
        img = Image.fromarray(Xi)
        img = img.convert("LA")
        img_name = "output_example" + str(n) + "_filter" + str(i) + ".png"
        img.save(img_name)
        print("[+] " + img_name + " saved successfully")
'''


from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
from sqlalchemy.sql import text
from sqlalchemy.orm import Session
from models import games as games_model
from models import users as users_model
from schemas import games as games_schema

def read_boxes(db: Session):
    BoxList = db.query(games_model.boxes).all()
    return BoxList

# お題一覧取得
def read_boxes(db: Session, skip: int = 0):
    BoxList = db.query(games_model.boxes).offset(skip).all()
    return BoxList

# 札セット取得
def read_playing_cards(db: Session, box_id: int) -> games_model.boxes_cards :
    play_cards_select = f"SELECT CAST(qac.card_id AS CHAR) AS card_id, CAST(qt.question_id AS CHAR) AS question_id, \
            CAST(at.answer_id AS CHAR) AS answer_id, qt.question_text AS question_text, \
            CONCAT(qt.question_text, '  ', at.answer_text) AS card_text,\
            at.answer_text AS answer_text, aimg.answer_file_pass AS answer_file_pass \
            FROM (box_card AS bc \
            INNER JOIN question_answer_cards AS qac \
            ON bc.card_id = qac.card_id AND bc.box_id = {box_id} \
            INNER JOIN question_texts AS qt \
            ON qac.question_id = qt.question_id) \
            INNER JOIN answer_texts AS at \
            ON qac.answer_id = at.answer_id \
            LEFT JOIN answer_images AS aimg \
            ON at.answer_id = aimg.answer_id \
            ORDER BY RAND() LIMIT 10 \
            " #結合抽出処理
    t = text(play_cards_select)
    PlayCardsList = db.execute(t).fetchall()

    return PlayCardsList

# 苦手札セット取得
def weak_point_cards(db: Session, user_id: str) -> users_model.Users :

    t = f"SELECT card_id FROM answer_rate_view WHERE answer_rate <= 0.8 AND user_id = :user_id"
    select_text = text(t)
    cid = db.execute(select_text,{"user_id": user_id}).fetchall()
    card_id_list = [item[0] for item in cid]
    weak_card_id = ', '.join(map(str, card_id_list))
    print(weak_card_id)
    weak_cards_select = f"SELECT CAST(qac.card_id AS CHAR) AS card_id, CAST(qt.question_id AS CHAR) AS question_id, \
            CAST(at.answer_id AS CHAR) AS answer_id, qt.question_text AS question_text, \
            CONCAT(qt.question_text, '  ', at.answer_text) AS card_text,\
            at.answer_text AS answer_text, aimg.answer_file_pass AS answer_file_pass \
            FROM (box_card AS bc \
            INNER JOIN question_answer_cards AS qac \
            ON bc.card_id = qac.card_id AND qac.card_id IN({weak_card_id}) \
            INNER JOIN question_texts AS qt \
            ON qac.question_id = qt.question_id) \
            INNER JOIN answer_texts AS at \
            ON qac.answer_id = at.answer_id \
            LEFT JOIN answer_images AS aimg \
            ON at.answer_id = aimg.answer_id \
            ORDER BY RAND() LIMIT 10 \
            " #結合抽出処理
    cards_set = text(weak_cards_select)
    WeakCardsList = db.execute(cards_set).fetchall()

    return WeakCardsList

#　プレイ結果記録 非同期にする！！
async def play_records(db: AsyncSession, result: games_schema.Results):
    #プレイ記録親テーブルに記録
    db_result = games_model.play_records(
        user_id = result.user_id,
        number_of_question = result.number_of_question,
        number_of_corrected = result.number_of_corrected,
        played_at = result.played_at,
        play_type = result.play_type
    )
    db.add(db_result)
    db.commit()
    db.refresh(db_result)

    #↑で発行されたplayed_idを取得
    played_db = db.query(games_model.play_records).\
        filter(games_model.play_records.played_at == db_result.played_at).\
            filter(games_model.play_records.user_id == db_result.user_id).first()
    print(played_db)
    played_id = played_db.played_id

    # プレイしたお題の記録
    db_box = games_model.play_type_boxes(
        played_id = played_id,
        box_id = result.box_id
    )
    db.add(db_box)
    db.commit()
    db.refresh(db_box)

    record_result = result.record_result

    for card_id, judgement in record_result.items():

        db_detail = games_model.record_details(
            played_id = played_id,
            card_id = card_id,
            judgement = judgement,
            user_id = result.user_id
        )

        db.add(db_detail)
        db.commit()
        db.refresh(db_detail)

    return {"message": "Good!"}


from Logic import *;

## HELPER FUNCTIONS ________________________________________________________________________________

def checkBrackets(Code):
    """ Raises an exception if the number of left brackets != number of right brackets. """

    left = 0; right = 0;
    for item in Code:
        if "(" in item: left+= item.count("(");
        if ")" in item: right += item.count(")");
    if left != right: raise Exception("incorrect number of brackets.");

def orderOfComputation(Code, setPrec):
    """ (list[str], set[str]) -> tuple[int]

    Returns the order of computation to be applied to the code.
    """

    T = tuple(); resulT = tuple();
    for i in range(len(Code)):
        item = Code[i];
        if item in setPrec:
            T += (i,);
    return T;

def containsBrackets(Code):
    """ (list[str]) -> bool

    Returns True iff code contains brackets.
    """

    for item in Code:
        if '(' in item or ')' in item:
            return True;
    return False;

def total_sub(sub, index):
    """ (dict[int:int], int) -> int

    Determines the total amount to be taken away from index sub as a consequence of indices reduced
    during computation.
    """

    s = 0;
    for i in range(index):
        if i in sub:
            s += sub[i];
    return s;

def endBrackets(Code):
    """ (list[str]) -> (int, int)

    Returns indices of rightmost left end brackets and leftmost right end bracket.

    >>> endBrackets(['(', 'T', ')'])
    (0, -1)
    >>> endBrackets(['(', 'T', 'and', 'F', ')', 'oor', 'F'])
    (0, -3)
    >>> endBrackets(['(', '(', 'T', 'iif', 'F', ')', 'eeq', 'F', ')'])
    (1, -1)
    """

    left = 0; right = len(Code)-1;
    while right >= left:
        if Code[left] in brackets: left += 1;
        if Code[right] in brackets: right -= 1;
        if not (Code[left] in brackets or Code[right] in brackets): break;

    return (left-1, right+1);

def hasMidBrackets(Code):
    """ (list[str]) -> bool

    Returns True iff code contains any brackets in the middle.
    """

    l = len(Code);

    # Skip past the end brackets.
    left, right = endBrackets(Code)[0], endBrackets(Code)[1];
    left += 1; right -= 1;

    # Then keep going until either references a bracket or right < left.
    while right >= left:
        if Code[left] in brackets: return True;
        if Code[right] in brackets: return True;
        left += 1; right -= 1;

    # Return False if right < left.
    return False;

## MAIN FUNCTIONS __________________________________________________________________________________

def computeList(Code):
    """ (list[str]) -> str

    Computes code provided by given list of string, which is a splitted string.

    >>> s1 = "T"
    >>> computeList(s1.split())
    'T'
    >>> s2 = "((F))"
    >>> computeList(s2.split())
    'F'
    >>> s3 = "T and F"
    >>> computeList(s3.split())
    'F'
    >>> s4 = "neg T oor F"
    >>> computeList(s4.split())
    'F'
    >>> s5 = "neg F iif T neq T"
    >>> computeList(s5.split())
    'F'
    >>> s6 = "neg (neg T) sso (T nnd F)"
    >>> computeList(s6.split())
    'T'
    """

    l = len(Code);
    # Make sure number of left brackets still == no of right brackets
    checkBrackets(Code);

    if l == 0:
        return None

    # Base case: Code = ['T'] or ['F'] or has brackets.
    if l == 1:

        C = Code[0].strip('( )');

        if C in constants: return C;

        else: return Exception("output is neither true nor false.");

    # Secondary case: No brackets remaining.
    elif not containsBrackets(Code):

        sub = {}; # records reduced indices in list, as a result of computation

        order = tuple();
        for prec in precedence:
            order += orderOfComputation(Code, prec); # Order of looking at the computation

        for i in order:

            s = total_sub(sub, i); # Computes the total to be subtracted from index.
            j = i-s; item = Code[j];

            # Negation case.
            if inputs[item] == 1:
                f = interpret[item]; inp = interpret[Code[j+1]];
                result = f(inp); string = inverse[result];
                Code = Code[:j] + [string] + Code[j+2:];

                # Update sub
                if not i in sub:
                    sub[i] = 1;

                else:
                    sub[i] += 1;

            # Binary Relation case.
            elif inputs[item] == 2:
                f = interpret[item];
                inp = (interpret[Code[j-1]], interpret[Code[j+1]]);
                result = f(*inp); string = inverse[result];
                Code = Code[:j-1] + [string] + Code[j+2:];

                # Update sub
                if not i in sub:
                    sub[i] = 2;

                else:
                    sub[i] += 2;

            else:
                raise Exception('incomplete inputs set.')

    # Tertiary case: brackets left inside to compute.
    else: # Here, deal with brackets to make sure no brackets are contained in between.

        # Remove the same total number of brackets from each end.
        if not hasMidBrackets(Code):
            endB = endBrackets(Code); first = endB[0]; last = endB[1];
            Code = Code[first+1: last];

            return computeList(Code);

        # Keep going until right bracket
        j = 0;
        while not ")" in Code[j]: j += 1;

        # Go back for left bracket.
        i = j-1;
        while not "(" in Code[i] or i < 0: i -= 1;

        if i < 0: raise Exception("improper use of brackets.");

        Code = Code[:i] + [ computeList(Code[i+1:j]) ] + Code[j+1:];

    return computeList(Code);

def compute(s):
    computeList(s.split(' '));


import json
from datetime import datetime, date

from flask import Blueprint, request
from flask import current_app as app

from db.wikishield_connection import DBConnection as WS
from db.wikishield_db import WikishieldDB
from lang.langs import Lang, LangsManager
from db.connection_info import read_sql_user_name
from clf.classifier_manager import reload_classifier
from sklearn.exceptions import NotFittedError

api = Blueprint('api', __name__)

# default number of revisions to fetch
_DEF_NUM_OF_REVS = 50
# maximum number of revisions to fetch
_MAX_NUM_OF_REVS = 500

# TODO: close wikishield_db at all routes

# TODO: define HTTP status codes here

# ----------------------------------------------------------------------------------------------------
class WikishieldApiResult:
    """
    this class generate JSON results for Wikishield API
    """

    @staticmethod
    def build_good_res(data=None):
        """
        build good result JSON of API

        param data: data to send at response. data must be serializable value (i.e. can converted to dictionary).
                    if your data it numpy value. use `data = my_numpy_obj.item()` function for converting to pure Python object

        return JSON result
        """
        return json.dumps(obj={'status': 'ok', 'data': data}, default=WikishieldApiResult._encode_object)

    @staticmethod
    def build_err_res(err_msg: str = None):
        """
        build error result JSON of API

        param err_msg: error message

        return JSON result
        """

        return json.dumps(obj={'status': 'error', 'errInfo': {'errMsg': err_msg}},
                          default=WikishieldApiResult._encode_object)

    @staticmethod
    def _encode_object(obj):
        if isinstance(obj, (datetime, date)):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, ValueError):
            return obj.__str__()  # return error message
        else:
            return obj.__dict__()

# ----------------------------------------------------------------------------------------------------
def _get_lang(lang_name: str):
    """
    get language from query parameters

    param lang_name: name of the language

    return language
    """

    lang_manager = LangsManager()
    if not lang_manager.is_support_lang(lang_name):
        raise ValueError("API not support `lang`={}".format(lang_name))
    return lang_manager.get_lang(lang_name)

# ----------------------------------------------------------------------------------------------------
def _try_parse_int(value: str):
    """
    try parse integer from string

    param value: string to parse

    return int
    """

    try:
        return int(value)
    except ValueError:
        raise ValueError("Cannot parse int from string")

# ----------------------------------------------------------------------------------------------------
def _try_parse_bool(value: str):
    """
    try parse boolean from string

    param value: string to parse

    return boolean
    """

    try:
        return bool(value)
    except ValueError:
        raise ValueError("Cannot parse boolean from string")

# ----------------------------------------------------------------------------------------------------
def _get_wikishield_db(lang: Lang):
    """
    get Wikishield database

    param lang: language

    return Wikishield database
    """

    sql_user_name = read_sql_user_name()
    wikishield_conn = WS(sql_user_name)
    wikishield_conn.start()
    return WikishieldDB(wikishield_conn.ctx, lang, sql_user_name)

# ----------------------------------------------------------------------------------------------------
@api.route('/score_rev', methods=['GET'])  # TODO: change to POST
def score_rev():
    """
    score revision route

    request parameters:
                `rev_text` - revision text
                `lang` = language
    response:
                JSON with `scoreResult`
    """

    try:
        rev_text = request.args.get("rev_text")
        rev_text = rev_text.strip() if rev_text else False
        if not rev_text:
            return WikishieldApiResult.build_err_res("Missing `rev_text` parameter"), 400
        lang_name = request.args.get("lang")
        _get_lang(lang_name)  # check language
        wiki_classifier = reload_classifier(lang_name)
        score_result = wiki_classifier.score_rev(rev_text)
        return WikishieldApiResult.build_good_res({'scoreResult': score_result})
    except Exception as ex:
        err_msg = str(ex)
        return WikishieldApiResult.build_err_res(err_msg), 400

# ----------------------------------------------------------------------------------------------------
@api.route('/manage_rev', methods=['POST'])
def manage_rev():
    """
    manage a revision at Wikipedia and update revision good editing in Wikishield table

    request parameters:
                `rev_id` - revision id to verify or restore
                `lang` = language
    response: /
    """

    try:
        req_data = request.get_json()
        rev_id = _try_parse_int(req_data['rev_id'])
        if rev_id < 1:
            raise ValueError("Parameter out of range `rev_id`={}".format(rev_id))
        lang_name = req_data['lang']
        lang = _get_lang(lang_name)
        good_editing = _try_parse_bool(req_data['good_editing'])
        wikishield_db = _get_wikishield_db(lang)
        wikishield_db.update_rev_good_editing(rev_id, good_editing)
        wikishield_db.commit()
        return WikishieldApiResult.build_good_res({})
    except Exception as ex:
        err_msg = str(ex)
        return WikishieldApiResult.build_err_res(err_msg), 400

# ----------------------------------------------------------------------------------------------------
@api.route('/get_revs', methods=['GET'])
def get_revs():
    """
    get last unverified revisions

    request parameters:
                `num_revs` - number of revisions to fetch
                 `lang` = language
    response:
                JSON with list of revisions
    """
    try:
        num_revs = _try_parse_int(request.args.get("num_revs", default=_DEF_NUM_OF_REVS))
        if num_revs < 0 or num_revs > _MAX_NUM_OF_REVS:
            raise ValueError("Illegal parameter range `num_revs`")
        lang_name = request.args.get("lang")
        lang = _get_lang(lang_name)
        wikishield_db = _get_wikishield_db(lang)
        revs = wikishield_db.fetch_recent_unverified_revs(num_revs)
        return WikishieldApiResult.build_good_res({'revs': revs})
    except Exception as ex:
        err_msg = str(ex)
        return WikishieldApiResult.build_err_res(err_msg), 400

# ----------------------------------------------------------------------------------------------------
@api.route('/<path:path>')
def unknown_request(path: str):
    """
    route for all unknown requests in API

    this return an error JSON response
    """

    err_msg = "Unknown request at path '{}'".format(path)
    return WikishieldApiResult.build_err_res(err_msg), 404


#!/usr/bin/env python

import os
import sys
import argparse
import wikimap
from itertools import imap

class GridSearch(object):
    """
    This class iterates through different combinations of parameters.

    For each argument a value or a list of values is given. At each step of the
    iteration one value from each list is chosen.
    """

    def __init__(self, grid_args):
        """
        Initialize the grid search.

        `grid_args` is an iterable of pairs consisting of a name of an argument
                    and a list of possible values (or a single value)
        """
        self._grid_args = [
            (arg_name, self._maybe_wrap_with_list(arg_values))
            for (arg_name, arg_values)
            in grid_args
            if arg_values is not None]

        self.max_config_num = max(sum(1 for _ in self), 1)

    def __iter__(self):
        """
        Iterate configs.

        Each value in _grid_args is a list. Each step of iteration yields
        a different combination of elements from lists (with one element per
        list at the same time).
        """
        def recursive_iterator(grid):
            if not grid:
                yield []
            else:
                key, value_axis = grid[0]
                for value in value_axis:
                    for tail in recursive_iterator(grid[1:]):
                        yield [(key, value)] + tail

        if not self._grid_args:
            return iter([{}])  # default config
        else:
            return imap(dict, iter(recursive_iterator(self._grid_args)))

    def _maybe_wrap_with_list(self, value):
        if isinstance(value, list):
            return value
        else:
            return [value]

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        '--target', '-t',
        dest='target_jobs',
        default=wikimap.DEFAULT_TARGET_JOBS,
        type=wikimap.Utils.parse_comma_separated_strings,
        help="Choose jobs to do. Their dependencies will also be included. "
             "The jobs should be specified as their aliases. Aliases can be "
             "obtained with '--print-jobs' option. Multiple comma-separated "
             "aliases are allowed. A wildcard 'all' can be used to select all "
             "jobs.")
    parser.add_argument(
        '--forced', '-f',
        dest='forced_jobs',
        default=wikimap.DEFAULT_FORCED_JOBS,
        type=wikimap.Utils.parse_comma_separated_strings,
        help=("Add targets (like '-t' option) but also mark them for "
              "recomputation, even if their results could be copied from "
              "previous runs. It expects the same kind of arguments as '-t'."))
    parser.add_argument(
        '--skip', '-s',
        dest='skipped_jobs',
        default=wikimap.DEFAULT_SKIPPED_JOBS,
        type=wikimap.Utils.parse_comma_separated_strings,
        help=("Choose jobs to skip unconditionally. Can't conflict with "
              "forced jobs. It expects the same kind of arguments as '-t'."))
    parser.add_argument(
        '--buildpath', '-b',
        type=str,
        default=os.environ.get("WIKIMAP_BUILDPATH", None),
        help=("Choose a directory for builds. Each build will create a new "
              "subdirectory inside. Can also be set by WIKIMAP_BUILDPATH "
              "environment variable."))
    parser.add_argument(
        '--prefix', '-p',
        type=str,
        default='build',
        help="Choose a prefix for subdirectories inside the builds directory.")
    parser.add_argument(
        '--lang',
        dest='meta.language',
        type=wikimap.Utils.parse_comma_separated_strings,
        default=wikimap.DEFAULT_LANGUAGE,
        help="Choose an edition of wikipedia to use. Should be a valid "
             "wikipedia code like 'en' or 'pl'. "
             "https://en.wikipedia.org/wiki/List_of_Wikipedias provides a "
             "list.")
    parser.add_argument(
        '--base',
        dest='base_build_index',
        type=int,
        default=-1,
        help=("Choose an index of a base build. The program will try to skip "
              "parts of the build if it thinks they would have the same "
              "results. By default the last build is used."))
    parser.add_argument(
        '--print-config',
        action='store_true',
        help="Print the full configuration of the build and quit.")
    parser.add_argument(
        '--print-jobs',
        action='store_true',
        help="Print a list of jobs included in the build and quit.")
    parser.add_argument(
        '--ldnn.neighbors_count',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_NEAREST_NEIGHBORS_COUNT,
        help=("Choose a number of nearest neighbors computed for each point "
              "in map. Can also be a comma-separated list of ints."))
    parser.add_argument(
        '--embed.context_size',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_CONTEXT_SIZE,
        help=("Choose a context size of word embedding method. Can also be "
              "a comma-separated list of ints."))
    parser.add_argument(
        '--embed.backtrack_probability',
        type=wikimap.Utils.parse_comma_separated_floats,
        default=wikimap.DEFAULT_BACKTRACK_PROBABILITY,
        help=("Choose a probability of backtracking in a random walk "
              "through link graph. Can also be a comma-separated list of "
              "floats."))
    parser.add_argument(
        '--embed.dimension',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_DIMENSION,
        help=("Choose a dimension of embeddings. Can also be a "
              "comma-separated list of ints."))
    parser.add_argument(
        '--embed.walks_per_node',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_WALKS_PER_NODE,
        help=("Choose a number of random walks per node in graph-based "
              "embedding algorithms. Can also be a comma-separated list of "
              "ints."))
    parser.add_argument(
        '--embed.method',
        type=wikimap.Utils.parse_comma_separated_strings,
        default=wikimap.DEFAULT_EMBEDDING_METHOD,
        help=("Choose an embedding method. Has to be one of the following: "
              "{}. Can also be a comma-separated list of the above.".format(
                ', '.join(wikimap.EMBEDDING_METHODS))))
    parser.add_argument(
        '--embed.node_count',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_EMBEDDING_NODE_COUNT,
        help=("Choose a number of embedded nodes (wikipedia titles). Can also "
              "be a comma-separated list of ints."))
    parser.add_argument(
        '--embed.epoch_count',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_EPOCH_COUNT,
        help=("Choose a number of epochs to use during training. Can also be "
              "a comma=separated list of ints."))
    parser.add_argument(
        '--embed.walk_length',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_WALK_LENGTH,
        help=("Choose a maximum walk length of random walks during embedding. "
              "Can also be a comma-separated list of ints."))
    parser.add_argument(
        '--embed.categories',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_USE_CATEGORIES,
        help=("Train also on links from pages to categories. Use 0 (off) and "
              "1 (on). Can also be a comma-separated list of ints."))
    parser.add_argument(
        '--embed.negative_samples',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_NEGATIVE_SAMPLES,
        help=("Number of noise samples drawn for each real sample coming from "
              "data. Can also be a comma-separated list of ints."))
    parser.add_argument(
        '--tsne.point_count',
        type=wikimap.Utils.parse_comma_separated_ints,
        default=wikimap.DEFAULT_TSNE_POINT_COUNT,
        help=("Number of points in t-SNE projection to compute. Can also be a "
              "comma-separated list of ints."))

    args = parser.parse_args()

    if not args.buildpath:
        sys.exit("Choose a build path, by using --buildpath (-b) option or by "
                 "setting the WIKIMAP_BUILDPATH environment variable.")

    wikimap.Utils.config_logging()
    logger = wikimap.Utils.get_logger(__name__)

    grid_arg_names = [
        'ldnn.neighbors_count', 'embed.context_size', 'embed.walks_per_node',
        'embed.backtrack_probability', 'embed.dimension', 'embed.node_count',
        'embed.method', 'embed.epoch_count', 'embed.walk_length',
        'embed.categories', 'embed.negative_samples', 'meta.language',
        'tsne.point_count']
    grid_args = [
        (arg_name, vars(args)[arg_name])
        for arg_name
        in grid_arg_names]

    build_configs = GridSearch(grid_args)

    for config_no, config in enumerate(build_configs):
        build = wikimap.Build(
            builds_dir=args.buildpath,
            build_prefix=args.prefix,
            base_build_index=args.base_build_index,
            target_jobs=args.target_jobs,
            forced_jobs=args.forced_jobs,
            skipped_jobs=args.skipped_jobs,
            config=config)

        if args.print_jobs:
            build.print_jobs()
        elif args.print_config:
            build.print_config()
        else:
            logger.important(wikimap.Utils.thick_line_separator)
            format_str = 'STARTING BUILD [{{:{}}}/{{}}]'.format(
                wikimap.Utils.get_number_width(build_configs.max_config_num))
            logger.important(format_str.format(
                config_no + 1,
                build_configs.max_config_num))

            build.run()

if __name__ == "__main__":
    main()


def findancestors(thing):
	''' specify and object (thing) to traceback,
	returns G wich is an AGraph object
	to plot:
	G.draw('<filename>.svg/jpg/tiff/pdf', prog = 'dot')

	'''
	import pygraphviz as pgv

	mro = thing.__mro__
	base_relations = {}
	base_relations_literal = {}
	for i in mro:
		base_relations[i] = i.__bases__
		base_relations_literal[i.__name__] = [r.__name__ for r in base_relations[i]]
	# draw out main graph

	G = pgv.AGraph()
	G.node_attr['shape']='box'
	G.edge_attr['dir']='backward'
	G.edge_attr['arrowhead'] = 'normal'
	G.graph_attr['rankdir']='BT'

	edges = []

	for i in base_relations:
		for k in base_relations[i]:
			edges.append((i.__name__,k.__name__))

	G.add_edges_from(edges)

	return G


import json
import pytest

from anno.crud import CRUD
from anno.errors import InvalidInputWebAnnotationError
from anno.json_models import AnnoJS
from anno.json_models import Catcha

from .conftest import make_wa_object

@pytest.mark.skip('debugging fixture')
@pytest.mark.usefixtures('wa_list')
def test_fixture_wa_list(wa_list):
    print(json.dumps(wa_list, sort_keys=True, indent=2))
    assert wa_list == 'blah'

@pytest.mark.skip('debugging fixture')
@pytest.mark.usefixtures('js_list')
def test_fixture_js_list(js_list):
    print(json.dumps(js_list, sort_keys=True, indent=2))
    assert js_list == 'blah'

@pytest.mark.usefixtures('js_list')
@pytest.mark.django_db
def test_to_annotatorjs(js_list):
    for js in js_list:
        catcha = AnnoJS.convert_to_catcha(js)
        anno = CRUD.create_anno(catcha, catcha['creator']['name'])
        js_back = AnnoJS.convert_from_anno(anno)
        assert AnnoJS.are_similar(js, js_back)

def test_body_sanitize():
    body_unsafe_text = [
        '  <   script same_attr=blah other_attr="pooh"></scritp>',
        '<script>',
        'something <\tscript\t  somethingelse="{}">'.format('blah'),
    ]
    catcha = make_wa_object()

    for b_text in body_unsafe_text:
        catcha['body']['items'][0]['value'] = b_text
        with pytest.raises(InvalidInputWebAnnotationError) as e:
            safe = Catcha.safe_body_text_value(catcha)

    catcha['body']['items'][0]['value'] = \
        'body of annotation that is safe and has no script tags.'
    safe = Catcha.safe_body_text_value(catcha)
    assert safe

@pytest.mark.usefixtures('wa_image')
@pytest.mark.django_db
def test_catcha_normalize_ok(wa_image):
    catch = wa_image
    catcha = Catcha.normalize(catch)

    assert json.dumps(catch, sort_keys=True, indent=4) == json.dumps(
        catcha, sort_keys=True, indent=4)


import cv2
import numpy as np
import pandas as pd
from tensorflow import keras
model = keras.models.load_model('MNIST_AmericanSignLanguage.h5')

cap = cv2.VideoCapture(0)
while True:
    ret, photo = cap.read()
    photo = cv2.cvtColor(photo, cv2.COLOR_BGR2GRAY)

    # photo = cv2.flip(photo,1)
    photo = cv2.rectangle(photo,(0,0),(200,200),(0,0,255),thickness=3,)
    hand = photo[0:200,0:200]
    hand = cv2.resize(hand,(28,28))

    # r = model.predict(hand)
    # print(np.argmax(r))
    # cphoto = photo[100:400, 50:350]
    cv2.imshow('hi', photo)
    cv2.imshow('hand', hand)
    # hand = cv2.resize(hand,(28,28))
    hand = hand.reshape(1,28,28,1)
    # print(hand.shape)
    r = model.predict(hand)
    print(np.argmax(r))
    if cv2.waitKey(1) == 13:
        break

cv2.destroyAllWindows()
cap.release()


from json import load
from itsdangerous import exc
import VideoPage
from PyQt5 import QtWidgets
import data
import loadingPage
import pafy
import videoLoading
import urllib.request
from PyQt5.QtGui import *

class PlayList:
    def __init__(self,Ui,con):
        self.ui=Ui
        self.con=con # 굳이 매개변수로 할필요 없었다

        self.load=loadingPage.Loading(self.ui)
        self.Videoload=videoLoading.LoadingVideo(self.ui)
        self.video=VideoPage.Video(self.ui)  # None 으로 해놓고 객체를 삭제하는 방법을 찾아야했다

        self.db=data.Database()
        self.dialog=QtWidgets.QDialog()     # dialog checkedit
        self.dialog2=QtWidgets.QDialog()    # dialogPlayList
        self.dialog3=QtWidgets.QDialog()    # dialog check
        self.dialog4=QtWidgets.QDialog()    # dialogYesNo
        self.id=None
        self.playListText=[]
        self.playList=[]
        self.playListClick()# 이름
        self.playListbtnEvent() # control 버튼 이름 이름이 너무 비슷해서 유지보수가 힘들다

    def playListbtnEvent(self):
        self.ui.playListBack.clicked.connect(self.backEvent)
        for index in range(0,len(self.ui.playListBtnList)):
            self.ui.playListBtnList[index].clicked.connect(lambda event,value=index : self.playListEvent(value))
    def receiveId(self,id):
        self.id=id
        self.playListClick()

    def playListClick(self):
        # search update insert delete
        for index in range(0,len(self.ui.mainLogoListBtn)):
           self.ui.mainLogoListBtn[index].clicked.connect(lambda event,value=index : self.moveEvent(value))

    def playListEvent(self,number):
        if number==0:#search
            self.searchList()
        elif number==1:
            self.updateList()
        elif number==2:
            self.ui.dialogCheckEdit(self.dialog,"insert")
            self.ui.dialogCheckEditBtn.clicked.connect(lambda event : self.insertPlayList())
            self.dialog.exec()
        else:
            self.deleteList()

    def insertPlayList(self):
        listData=[self.id,self.ui.dialogText.text()]
        checkPlayListRepeat=self.db.readData("playList",["id","playList"],listData,self.db.cursor2)
        print(len(checkPlayListRepeat))
        if len(checkPlayListRepeat)==0:
            self.db.insertData("playList",self.db.column2Value,listData,self.db.cursor2,self.db.connect2)
            self.dialog.close()
            self.playListSet()
        else:
            self.ui.dialogCheck(self.dialog3,"repeat")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()

    def playListSet(self):
        listData=self.db.readData("playList",["id"],[self.id],self.db.cursor2)
        self.playListText=[]
        for index in range (0,len(listData)):
            self.playListText.append(listData[index][2])

        self.videoListText=[]
        for index in range(0,len(listData)):
            listData2=self.db.readData("playVideo",["id","playList"],[self.id,self.playListText[index]],self.db.cursor3)
            try:
                self.videoListText.append(listData2[0][3])
            except:
                self.videoListText.append("")
        print("비디오제목은:"+str(self.videoListText))
        self.ui.playList(self.playListText,self.videoListText)
        self.playListClick()

    def moveEvent(self,number):
        #비디오 객체 선언
        self.load.setMovie(4)
        self.video.id=self.id
        self.video.playList=self.playListText[number]
        self.video.videoPlay(0)
        self.presentList=self.playListText[number]
        self.video.videoListSet()

    def backEvent(self):
        self.ui.stackedWidget.setCurrentIndex(0)
        self.con.setTextClear()
        #객체 삭제
        # event 버튼 등등 모두 clear

    def updateList(self):
        self.ui.dialogPlayList(self.dialog2,"update",self.playListText)
        self.ui.Listcheckbtn[1].clicked.connect(lambda event : self.dialog2.close())
        self.ui.Listcheckbtn[0].clicked.connect(lambda event : self.updateName())
        self.dialog2.exec()

    def updateName(self):
        state=[]
        count=0
        indexState=None
        for index in range(0,len(self.ui.dialogListBox)):
            state.append(self.ui.dialogListBox[index].isChecked())
            if state[index]==True:
                count+=1
                indexState=index
        if count>=2 :
            self.ui.dialogCheck(self.dialog3,"repeat input")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()
        elif count<=0 :
            self.ui.dialogCheck(self.dialog3,"pls input")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()
        elif count==1:
            self.ui.dialogCheckEdit(self.dialog,"update")
            self.ui.dialogCheckEditBtn.clicked.connect(lambda event : self.updateData(indexState))
            self.dialog.exec()

    def updateData(self,number):
        listData=[self.id,self.ui.dialogText.text()]
        checkPlayListRepeat=self.db.readData("playList",["id","playList"],listData,self.db.cursor2)
        print(checkPlayListRepeat)
        if len(checkPlayListRepeat)==0:
            playList=self.ui.dialogListBox[number].text()
            data=self.db.readData("playList",["id","playList"],[self.id,playList],self.db.cursor2)
            updateData=["sequance",data[0][0]]
            self.db.updateData("playList",["playList",self.ui.dialogText.text()],updateData,self.db.cursor2,self.db.connect2)
            self.dialog2.close()
            self.dialog.close()
            self.playListSet()
        else:
            self.ui.dialogCheck(self.dialog3,"repeat")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()

    def deleteList(self):
        self.ui.dialogPlayList(self.dialog2,"delete",self.playListText)
        self.ui.Listcheckbtn[1].clicked.connect(lambda event : self.dialog2.close())
        self.ui.Listcheckbtn[0].clicked.connect(lambda event : self.deleteEvent())
        self.dialog2.exec()

    def deleteEvent(self):
        state=[]
        count=0
        indexState=None
        for index in range(0,len(self.ui.dialogListBox)):
            state.append(self.ui.dialogListBox[index].isChecked())
            if state[index]==True:
                count+=1
                indexState=index
        if count>=2 :
            self.ui.dialogCheck(self.dialog3,"repeat input")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()
        elif count<=0 :
            self.ui.dialogCheck(self.dialog3,"pls input")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()
        elif count==1:
            self.ui.dialogYesNo(self.dialog4,"delete?")
            self.ui.dialogYesNoBtn[0].clicked.connect(lambda event : self.deleteData(indexState))
            self.ui.dialogYesNoBtn[1].clicked.connect(lambda event : self.dialog4.close())
            self.dialog4.exec()

    def deleteData(self,number):
        playList=self.ui.dialogListBox[number].text()
        data=self.db.readData("playList",["id","playList"],[self.id,playList],self.db.cursor2)
        deleteData=["sequance",data[0][0]]
        data=self.db.readData("playVideo",["id","playList"],[self.id,playList],self.db.cursor3)
        try:
            deleteData2=["sequance",data[0][0]]
            self.db.deleteData("playList",deleteData,self.db.cursor2,self.db.connect2)
            self.db.deleteData("playVideo",deleteData2,self.db.cursor3,self.db.connect3)
            self.dialog4.close()
            self.dialog2.close()
            self.playListClick()
            self.playListSet()
        except:
            self.db.deleteData("playList",deleteData,self.db.cursor2,self.db.connect2)
            self.dialog4.close()
            self.dialog2.close()
            self.playListClick()
            self.playListSet()

            # rdData 통해서 id 랑 입력된 text 로 시퀀스 찾아서 그 시퀀스 딜리트

    def searchList(self):
        self.ui.dialogPlayList(self.dialog2,"search",self.playListText)
        self.ui.Listcheckbtn[1].clicked.connect(lambda event : self.dialog2.close())
        self.ui.Listcheckbtn[0].clicked.connect(lambda event : self.videoInsertEvent())
        self.dialog2.exec()

    def insertVideo(self,number):
        playList=self.ui.dialogListBox[number].text()
        videoData=self.storeVideo(self.ui.dialogText.text())
        try:
            listData=[self.id,playList,videoData[0],videoData[1],videoData[2]]
            print(listData)
            checkPlayListRepeat=self.db.readData("playVideo",["id","playList","video","time","imageURL"],listData,self.db.cursor3)
            print(len(checkPlayListRepeat))
            if len(checkPlayListRepeat)==0:
                self.dialog2.close()
                self.dialog.close()
                self.presentList=playList
                self.db.insertData("playVideo",self.db.column3Value,listData,self.db.cursor3,self.db.connect3)
                self.playListClick()
                qPixmapVar = QPixmap()
                urlString = videoData[2]
                imageFromWeb = urllib.request.urlopen(urlString).read()
                qPixmapVar.loadFromData(imageFromWeb)
                qPixmapVar=qPixmapVar.scaled(480,270)
                qPixmapVar.save("thumbnail/"+videoData[0]+".PNG")
                self.Videoload.setDown(self.best)
                self.playListSet()
            else:
                self.ui.dialogCheck(self.dialog3,"repeat")
                self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
                self.dialog3.exec()
        except:
            self.ui.dialogCheck(self.dialog3,"URL wrong")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()

    def videoInsertEvent(self):
        state=[]
        count=0
        indexState=None
        for index in range(0,len(self.ui.dialogListBox)):
            state.append(self.ui.dialogListBox[index].isChecked())
            if state[index]==True:
                count+=1
                indexState=index
        if count>=2 :
            self.ui.dialogCheck(self.dialog3,"repeat input")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()
        elif count<=0 :
            self.ui.dialogCheck(self.dialog3,"pls input")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()
        elif count==1:
            self.ui.dialogCheckEdit(self.dialog,"Insert Video")
            self.ui.dialogCheckEditBtn.clicked.connect(lambda event : self.insertVideo(indexState))
            self.dialog.exec()

    def storeVideo(self,url):
        try:
            video = pafy.new(url)
            streams = video.streams
            for i in streams:
                print(i)
            # get best resolution regardless of format
            self.best = video.getbest()
            print(self.best.resolution, self.best.extension)
            # Download the video

            sec=int(video.duration[0])*36000+int(video.duration[1])*3600+int(video.duration[3])*600+int(video.duration[4])*60+int(video.duration[6])*10+int(video.duration[7])
            videoName=video.title
            videoImage = video.bigthumb

            return videoName,sec,videoImage
        except:
            self.ui.dialogCheck(self.dialog3,"URL wrong")
            self.ui.dialogCheckbtn.clicked.connect(lambda event : self.dialog3.close())
            self.dialog3.exec()


import json
import random

import requests
from discord.ext.commands import Bot, BucketType, Cog, Context, command, cooldown

from .utils.logs import *

class RandomAPI:
    def __init__(self, api_key: str) -> None:
        self.api_key = api_key
        self.cache = []
        self.d1k = []
        self.cache_size = 20

    def _api_request(self, i: int, j: int, n: int) -> list:
        """ Get a number from random.org """

        # JSON request to random.org API
        url = "https://api.random.org/json-rpc/2/invoke"
        headers = {'content-type': 'application/json'}
        payload = {
            "jsonrpc": "2.0",
            "method": "generateIntegers",
            "params": {
                "apiKey": self.api_key,
                "n": n,
                "min": min(i, j),
                "max": max(i, j),
            },
            "id": 0
        }
        response = requests.post(url, data=json.dumps(payload), headers=headers).json()
        assert response["id"] == 0

        # If something went wrong, generate pseudorandom number
        if "result" not in response:
            result = [random.randint(min(i, j), max(i, j)) for x in range(n)]

        # Grab the result
        else:
            result = response["result"]["random"]["data"]

        return result

    def roll(self, i: int, j: int, n: int=1) -> list:
        """ Return cached result if any, generate otherwise."""

        # No roll needed if same
        if i == j:
            result = [i for x in range(n)]

        # Generate standard roll, from cache if available
        elif (i == 1 and j == 6):
            if len(self.cache) == 0:
                self.cache += self._api_request(1, 6, self.cache_size)
            result = self.cache[0:n]
            del self.cache[0]

        # Generate d1k roll, from cache if available
        elif (i == 1 and j == 1000):
            if len(self.d1k) == 0:
                self.d1k += self._api_request(1, 1000, self.cache_size)
            result = self.d1k[0:n]
            del self.d1k[0]

        # Generate non-standard dice roll
        else:
            result = self._api_request(i, j, n)

        return result

class Dice(Cog):
    """
    Dice roll command using random.org
    Given no arguments, generates number between 1 and 6 inclusive.
    Given one integer j, generates number between 1 and j inclusive.
    Given two integers i and j, generates number between i and j inclusive.
    Given three integers i, j, and n, generates n numbers between i and j inclusive.
    """

    def __init__(self, bot: Bot) -> None:
        self.bot = bot
        self.dice = RandomAPI(bot.keys['random'])

    # Initialise dice cache on start up
    @Cog.listener()
    async def on_ready(self) -> None:
        self.dice.roll(1, 6)     # initialise dice cache
        self.dice.roll(1, 1000)  # initialise d1k cache

    @command()
    @cooldown(5, 60, BucketType.user)
    async def roll(self, ctx: Context, j: str='6', i: str='1', n: str='1') -> None:
        if ctx.guild and ctx.guild.id in self.bot.quiet['guilds']:
            return
        if ctx.channel.id in self.bot.quiet['channels']:
            return

        log_command(ctx)
        try:
            i = int(i)
            j = int(j)
            n = int(n)
        except ValueError:
            return
        async with ctx.typing():
            result = self.dice.roll(i, j, n)
        await self._send(ctx, result)

    async def _send(self, ctx: Context, result: list) -> None:
        """Send formatted output to Discord."""
        message = ', '.join(str(x) for x in result)
        if len(message) > 2000:
            await ctx.send("Your roll is too big for Discord.")
        elif len(message) > 250:
            await ctx.send("Your roll has been sent as a DM.")
            await ctx.author.send(message)
        else:
            await ctx.send(message)

def setup(bot: Bot) -> None:
    """Load cog into bot."""
    bot.add_cog(Dice(bot))


from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import HttpResponse
from subtitlingAI.forms import VideoFileForm
from subtitlingAI.models import VideoFile
from subtitlingAI.data_process.transcription import main
import shutil, os

def clean_database():
    n = VideoFile.objects.count()
    if n > 0:
        db = VideoFile.objects.all()
        for i in range(n):
            db[0].delete()

def index(request):
    clean_database()
    if request.method == "POST":
        form = VideoFileForm(request.POST, request.FILES)
        if form.is_valid():
            video = form.save()
            video_name = os.path.splitext(os.path.basename(video.video_file.path))[0]
            srt_content = main(video.google_project_id, video.video_file.path, video.transcription_language)
            video.delete()
            shutil.rmtree(f'uploaded/{video.google_project_id}')
            response = HttpResponse(srt_content, content_type='application/octet-stream')
            response['Content-Disposition'] = f'attachment; filename="{video_name}.srt"'
            return response
        else:
            messages.warning(request, "Form not valid. Are the Google Project ID and the extension format of the video correct?")
            return redirect('index')
    form = VideoFileForm()
    return render(request,
                  'subtitlingAI/index.html',
                  {'form': form})

def about(request):
    return render(request,
                  'subtitlingAI/about.html')


# Запросить у пользователя желаемую фигуру посредством выбора из существующих
#   вывести список всех фигур с номерами и ждать ввода номера желаемой фигуры.
# и нарисовать эту фигуру в центре экрана

import simple_draw as sd

COLOR_WHITE = (255, 255, 255)
COLOR_BLACK = (0, 0, 0)
COLOR_RED = (255, 0, 0)
COLOR_ORANGE = (255, 127, 0)
COLOR_GREEN = (0, 255, 0)
COLOR_CYAN = (0, 255, 255)
COLOR_BLUE = (0, 0, 255)
COLOR_PURPLE = (255, 0, 255)

color_print = int(input('Какой цвет вы хотите выбрать \n1 White \n2 Black \n3 Red \n4 Orange \n5 Green '
                        '\n6 Cyan \n7 Blue \n8 Purple \n'))

def color_type():
    if color_print == 1:
        return COLOR_WHITE
    elif color_print == 2:
        return COLOR_BLACK
    elif color_print == 3:
        return COLOR_RED
    elif color_print == 4:
        return COLOR_ORANGE
    elif color_print == 5:
        return COLOR_GREEN
    elif color_print == 6:
        return COLOR_CYAN
    elif color_print == 7:
        return COLOR_BLUE
    elif color_print == 8:
        return COLOR_PURPLE

def triangle(start_point=sd.get_point(480, 20), angle=0, length=100):
    for angle_1 in (0, 120, 240):
        v = sd.get_vector(start_point=start_point, angle=angle + angle_1, length=length, width=2)
        v.draw(color_type())
        start_point = v.end_point

def rectangle(start_point=sd.get_point(20, 20), length=100, angle=0):
    for angle_ in (0, 90, 180, 270):
        v = sd.get_vector(start_point=start_point, angle=angle + angle_, length=length, width=2)
        v.draw(color_type())
        start_point = v.end_point

def five_angle(start_point=sd.get_point(250, 20), length=100, angle=0):
    for angle_ in (0, 72, 144, 216, 288):
        v = sd.get_vector(start_point=start_point, angle=angle + angle_, length=length, width=2)
        v.draw(color_type())
        start_point = v.end_point

def six_angle(start_point=sd.get_point(250, 300), length=100, angle=0):
    for angle_ in (0, 60, 120, 180, 240, 300):
        v = sd.get_vector(start_point=start_point, angle=angle + angle_, length=length, width=2)
        v.draw(color_type())
        start_point = v.end_point

type_figure = int(input('\n1 Треуголник \n2 Четыриугольник \n3 Пятиугольник \n4 Шестиугольник \n5 Все фигуры \n'))

if type_figure == 1:
    triangle(start_point=sd.get_point(250, 250))
elif type_figure == 2:
    rectangle(start_point=sd.get_point(250, 250))
elif type_figure == 3:
    five_angle(start_point=sd.get_point(250, 250))
elif type_figure == 4:
    six_angle(start_point=sd.get_point(250, 250))
elif type_figure == 5:
    triangle()
    rectangle()
    five_angle()
    six_angle()

if __name__ == "__main__":
    sd.pause()


import i2c

MPU6050_I2CADDR = 0x68

def _buildVal(msd, lsd): #From 2 8bit numbers to one 16 bit number
    print('msd: ', msd, 'lsd: ', lsd)
    val = ( msd << 8 ) + lsd
    if (val >= 0x8000):
        return -((65535 - val) +1)
    else:
        return val

class MPU6050:

    def __init__(self, addr=MPU6050_I2CADDR, clk=400000):
        self.portI2C=i2c.I2C(I2C0, addr) #Declared port i2c ex. I2C0 on the board connected with 0x68, the i2c address of the sensor SDA on D25 n SCL on D26,
        try:
            self.portI2C.start()
            print('initialized')
        except Exception as e:
            print(e)
        self.setup()

    def setup(self):
        print('initialized MPU6050 ')
        self.portI2C.write([0x6B,0b10000000]) #Dev Reset
        print('MPU6050 resetted')
        self.portI2C.write([0x6B,0x00])#Wake up MPU
        print('MPU6050 ready')

    def getTemp(self):
        temp=self.portI2C.write_read(0x41, 2)
        print('RowTemph ', temp[0], 'rowtempl', temp[1])
        rowTemp=_buildVal(temp[0],temp[1])
        return ((rowTemp/340)+36.53) #As in datasheet

    def getGyroX(self):
        gyroX = self.portI2C.write_read(0x43, 2)
        print('rowX ', gyroX[0], gyroX[1])
        return(_buildVal(gyroX[0], gyroX[1]))

    def getGyroY(self):
        gyroY = self.portI2C.write_read(0x45, 2)
        return(_buildVal(gyroY[0], gyroY[1]))

    def getGyroZ(self):
        gyroZ = self.portI2C.write_read(0x47, 2)
        return(_buildVal(gyroZ[0], gyroZ[1]))


from turtle import Turtle, Screen
import random
import colorgram
import re
turtle = Turtle()

turtle.shape("turtle")
turtle.color("DarkOrchid1")

def draw_square():
    """draw a square"""
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)

# draw_square()

def draw_dash():
    """draw a dash line"""
    i = 0
    while i < 25:
        for c in ('black', 'white'):
            turtle.color(c)
            turtle.forward(10)
            i += 1

# draw_dash()

def draw_different_shapes():
    """draw different type of shapes, and each shape is outside the last shape"""
    for angle in range(3,10):
        inside_angle = (180 * (angle - 2)) / angle
        turn_angle = 180 - inside_angle

        c1,c2,c3 = random.uniform(0,1), random.uniform(0,1), random.uniform(0,1)
        tup = (c1, c2, c3)
        turtle.pencolor(tup)

        i = 1
        while i <= angle:
            turtle.right(turn_angle)
            turtle.forward(100)
            i += 1

# draw_different_shapes()

def random_walk():
    """walk random direction for same steps but change color each steps"""
    direction = [0, 90, 180, 270]

    for i in range(100):
        turtle.pensize(15)
        dir_choose = int(random.choice(direction))
        turtle.right(dir_choose)
        turtle.forward(20)
        c1, c2, c3 = random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)
        tup = (c1, c2, c3)
        turtle.pencolor(tup)

# random_walk()

def draw_circle():
    """draw loop circles that spin 360 degree"""
    for time in range(36):
        c1, c2, c3 = random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)
        tup = (c1, c2, c3)
        turtle.pencolor(tup)
        turtle.circle(50)
        turtle.right(10)

# draw_circle()

def hirs_spot():
    """draw the dot in random color, which extract from hirs spot painting"""
    colors = colorgram.extract('image.jpg', 35)

    rgb_colors = []
    for color in range(len(colors)):
        rgb_colors.append(colors[color].rgb)

    formatted_rgb = []
    for rgb in rgb_colors:
        rgb_value = f"({rgb.r},{rgb.g},{rgb.b})"
        # 將字串中的數字切割並轉換成整數，然後用 tuple 函數來創建元組
        rgb_color_tuple = tuple(map(int, rgb_value[1:-1].split(',')))
        formatted_rgb.append(rgb_color_tuple)

    turtle.penup()
    turtle.speed("fastest")
    turtle.setheading(225)
    turtle.forward(350)
    turtle.setheading(0)
    number_of_dots = 100

    for dot_count in range(1, number_of_dots + 1):
        # 將 numeric color tuple 轉換成 Turtle 模組接受的顏色字串格式
        turtle.dot(20, "#%02x%02x%02x" % random.choice(formatted_rgb))
        turtle.fd(50)

        if dot_count % 10 == 0:
            turtle.setheading(90)
            turtle.fd(50)
            turtle.setheading(180)
            turtle.fd(500)
            turtle.setheading(0)

# hirs_spot()

screen = Screen()
screen.exitonclick()


def DP_Knapsack(W, items):
    num_items = len(items)
    # initialize an empty table of size (W + 1) x (N + 1)
    DP_table = [[0 for x in range(W + 1)] for x in range(num_items + 1)]

    # find the max value
    for i in range(num_items + 1):
        for wt in range(W + 1):
            if i == 0 or wt == 0:
                DP_table[i][wt] = 0
            elif items[i - 1].weight <= wt:
                DP_table[i][wt] = max(items[i - 1].value +
                            DP_table[i - 1][wt - items[i - 1].weight],
                                        DP_table[i - 1][wt])
            else:
                DP_table[i][wt] = DP_table[i - 1][wt]
    maxValue = DP_table[num_items][W]

    chosen_items = []
    res = maxValue
    # find the items that get the max value
    for i in range(num_items, 0, -1):
        if res <= 0:
            break

        if res != DP_table[i - 1][W]:
            chosen_items.append(items[i - 1])
            res = res - items[i - 1].value
            W = W - items[i - 1].weight

    return maxValue, chosen_items


# -*- coding: utf-8 -*-
# initializing empty envelops
# i = int(input())
# if (not i and i%2):
#     print("true")
#
# else:
#     print("false")
# i = int(input())
# if(i%2 and not i%3 and not i%5 and i%10):
#     print("da")
# else:
#     print ("no")
# i = int(input())
# t=1
#
# while(t<i/2):
#     if not i%t:
#          print(t)
#     t+=1
#
i=int(input())
t=1
count =0
while((t<i)):
    t *= 10
    if t==10:
        print(i%t)
    else:
        print((i % t)//(t/10))
    count+=1
print ("разрядов: " + str(int(count)))
k=2
l=0
m=0
while(i>1):

    if(i%k==0):
        l=i/k
        m += 1
        print("множитль" + str(int(m)) + " = " + str(int(k)))
        k=2
        i = l
    else: k+=1
    if(i==1):print("множитль" + str(int(m+1)) + " = " + str(int(1)))


import argparse
import os
import sys
import time
import mmap
import signal
from os import fork

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--file',
                        help='Path del archivo')
    args = parser.parse_args()

    mapp(args)

def store_up(segment, cpid, args):
    for line in sys.stdin:
        if os.getpid() == cpid[0]:
            print(line)
            if os.getpid() == cpid[0]:
                print('Hijo_1')
                segment.write(bytes(line))
                signal.raise_signal(signal.SIGUSR1)

            elif os.getpid() == cpid[1]:
                print('Hijo_2')
            for h in range(2):
                signal.sigwait([signal.SIGUSR1])

            readLine = segment.readline()

            with open(args.file, 'w') as file:
                file.write(readLine.upper())

def mapp(args):

    with open('file.txt', 'w+') as file:
        segment = mmap.mmap(-1, 1024)
        signal.signal(signal.SIGUSR1, signal.SIG_DFL)
        ppid = os.getpid()
        cpid = []

        for i in range(2):
            if os.getpid() == ppid:
                cpid.append(os.fork())
            else:
                os.wait()
        if os.fork():
            w = os.fdopen(w, 'w')
            print(cpid)
            w.write(f'{cpid}')
            w.close()
        else:
            os.close(w)
            r = os.fdopen(r, 'r')
            cpid = r.read()
            print(cpid)
            r.close()

        store_up(segment, cpid, args)

if __name__ == '__main__':
    main()