# Truncable primes (37)
# 748317

import math

primeList = [2]
truncable_primes = []

# Checks n for prime
def prime(n):
    upperLimit = 0
    #while upperLimit < math.sqrt(n):
    #    upperLimit = next(iter(primeList))

    # Set upper limit for divisor search
    for i in primeList:
        if i > math.sqrt(n):
            upperLimit = i
            break

    # Do divisor search
    for i in primeList[:primeList.index(upperLimit)+1]:
        if n % i == 0:
            # Divisor found, n is not prime
            return False
            break
    # No divisor found, n is prime
    return True

# Checks if n is a truncable prime
def truncable_prime(n):
    n = str(n)

    #
    for j in range(len(n)):
        # 3, 73, 373
        if int(n[j:]) not in primeList:
            return False

    #
    for k in range(len(n)):
        # 3, 37, 373..
        if int(n[:k+1]) not in primeList:
            return False

    #
    return True

for i in range(3, 1000000):
    if prime(i):
        primeList.append(i)

print('Done')

# Primes under 7 are by definition not truncable primes

for prime in primeList:

    if prime in [2, 3, 5, 7]:
        continue

    if len(truncable_primes) == 11:
        break

    if truncable_prime(prime):
        truncable_primes.append(prime)
        print('New truncable prime:', prime)

print(str(truncable_primes))
print(sum(truncable_primes))


# python3
import sys
import threading
import numpy as np

def compute_height(n, parents):
    tree = [[] for i in range(n)]
    for i, parent in enumerate(parents):
        if parent != -1:
            tree[parent].append(i)
    root = np.where(parents == -1)[0][0]
    queue = [(root, 0)]
    max_height = 0
    while queue:
        node, height = queue.pop(0)
        max_height = max(max_height, height+1)
        for child in tree[node]:
            queue.append((child, height + 1))
    return max_height

def main():
    input_type = input().strip()
    if "I" in input_type:
        n = int(input().strip())
        parents_str = input().strip()
        parents = np.array(list(map(int, parents_str.split())))
        height = compute_height(n, parents)
    elif "F" in input_type:
        file_name = input().strip()
        if "a" in file_name:
            print("wrong")
            return
        with open("./test/" + file_name, 'r') as file:
            n = int(file.readline().strip())
            parents_str = file.readline().strip()
            parents = np.array(list(map(int, parents_str.split())))
            height = compute_height(n, parents)
    print(height)

if __name__ == "__main__":
    sys.setrecursionlimit(10**7)
    threading.stack_size(2**27)
    thread = threading.Thread(target=main)
    thread.start()
    thread.join()


from django.urls import path
from . import views

app_name = 'ecommerce'

urlpatterns = [
    path('', views.index, name="index"),
    path('registeras', views.register_page, name="register_page"),
    path('vendor_register', views.registerasvendor, name="registerasvendor"),
    path('customer_register', views.registerascustomer, name="registerascustomer"),
    path('logout/', views.userLogout, name="userLogout"),
    path('login/',views.userLogin,name='userLogin'),
    path('dashboard',views.dashboard,name='dashboard'),
]


from typing import Tuple, List

def part1(program: List[Tuple[str, int]]):
    pc, acc = 0, 0
    executed = set()
    while pc < len(program):
        inst, i = program[pc]
        if inst == 'nop':
            pc += 1
        elif inst == 'acc':
            acc += i
            pc += 1
        elif inst == 'jmp':
            pc += i

        if pc in executed:
            break
        else:
            executed.add(pc)
    else:
        return acc, True

    return acc, False

def part2(program: List[Tuple[str, int]]):
    for i in range(len(program)):
        if program[i][0] == 'nop':
            program_copy = program[:]
            program_copy[i] = ('jmp', program[i][1])
        elif program[i][0] == 'jmp':
            program_copy = program[:]
            program_copy[i] = ('nop', program[i][1])
        else:
            continue

        acc, halts = part1(program_copy)
        if halts:
            return acc

def main():
    with open('input.txt', 'r') as f:
        program = [line.strip() for line in f.readlines()]
        program = [(line.split()[0], int(line.split()[1])) for line in program]

    print(part1(program)[0])
    print(part2(program))

if __name__ == '__main__':
    main()


import torch
import torchvision
import lightning.pytorch as pl
import pandas as pd

mapping = {'разметка_шипун' : 2, 'klikun' : 1, 'разметка_малый':0}
inv_mapping = { 2 : 'разметка_шипун', 1 : 'klikun', 0:'разметка_малый'}

def get_point(pred_id, gt_id):
    matr = [[3,-1,-3],
            [-1,3,-3],
            [-3,-3,2]]
    return matr[pred_id][gt_id]

def calc_metric(gt, pred):
    df = pd.DataFrame({'gt': gt, 'pred':pred})
    df['gt'] = df['gt'].map(mapping)
    df['pred'] = df['pred'].map(mapping)
    gt_points = []
    pred_points = []
    for i in df['gt']:
        gt_points.append(get_point(i, i))
    for i,j in zip(df['pred'],df['gt']):
        pred_points.append(get_point(i, j))
    df['gt_points'] = gt_points
    df['pred_points'] = pred_points
    return df

class SwanClassifier(pl.LightningModule):
    def __init__(self, learning_rate):
        super().__init__()
        self.learning_rate = learning_rate
        self.model = torchvision.models.resnet50(pretrained = True)
        self.model.fc = torch.nn.Linear(in_features=2048, out_features=3)
        weights = [1,1,4]
        class_weights = torch.FloatTensor(weights)
        self.criterion = torch.nn.CrossEntropyLoss(weight = class_weights)
        self.inv_mapping = { 2 : 'разметка_шипун', 1 : 'klikun', 0:'разметка_малый'}
        self.save_hyperparameters()

    def calc_score(self, preds, labels):
        gt_list = []
        pred_list = []
        max_preds = torch.argmax(preds, dim = 1)
        for pred, label in zip(max_preds, labels):
            pred_list.append(self.inv_mapping[pred.item()])
            gt_list.append(self.inv_mapping[label.item()])
        stat_df = calc_metric(gt_list, pred_list)
        return stat_df['pred_points'].sum()/stat_df['gt_points'].sum()

    def training_step(self, batch, batch_idx):
        crops = batch['image']
        labels = batch['img_class'].to(torch.long)
        preds = self.model(crops)
        loss = self.criterion(preds, labels)
        self.log("train_loss", loss)
        self.log('step', self.global_step)
        return loss

    def validation_step(self, batch, batch_idx):
        crops = batch['image']
        labels = batch['img_class'].to(torch.long)
        preds = self.model(crops)
        loss = self.criterion(preds, labels)
        self.log("validation_loss", loss, sync_dist=True)
        self.log("validation_score", self.calc_score(preds, labels), sync_dist=True)

    def forward(self, images):
        preds = self.model(images)
        preds = torch.argmax(preds, dim = 1)
        out = []
        for pred in preds:
            out.append(self.inv_mapping[pred.item()])
        return out

    def configure_optimizers(self):
        optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate)
        def func(epoch: int):
            return  2 ** (-epoch//4)
        scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=func)
        return {
            'optimizer': optimizer,
            'lr_scheduler': {
                'scheduler': scheduler,
                'interval': 'epoch'
            }
        }


import numpy as np
import cv2

def process_demo_videos(cam_id, track_id):

    fid_start = 15000
    nr_frames = 600

    prefixes = ['westbound', 'eastbound', 'northbound', 'southbound', 'osburn1004']
    prefix = prefixes[cam_id]
    postfix = ('_%d' % track_id)

    folder = '../avacar_data'

    fn_original = folder + '/video/' + prefix + postfix + '.mpg'
    fn_in = folder + '/processed_video/' + prefix + postfix + '.mp4'

    fn_out = folder + '/processed_video/' + prefix + postfix + '_demo' + '.mp4'

    writer_fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    writer_size = (2560, 1440)
    writer = cv2.VideoWriter(fn_out, writer_fourcc, 30, writer_size)

    cap = cv2.VideoCapture(fn_in)
    assert cap.isOpened()

    for i in range(0, fid_start):

        cap.read()

    for i in range(nr_frames):

        ret, frame = cap.read()
        assert ret

        frame = cv2.resize(frame, writer_size)

        writer.write(frame)

        print(i)

    writer.release()

    pass

def process_drone_demo_videos():

    g_prefix = 'osburn1004'
    g_postfix = '_1'

    a_prefix = '36'
    a_postfix = '_0'

    folder = '../avacar_data'

    fn_in_g = folder + '/processed_video/' + g_prefix + g_postfix + '.mp4'

    fn_in_a = folder + '/processed_aerial_video/' + a_prefix + a_postfix + '.mp4'

    fn_out = folder + '/processed_video/' + g_prefix + g_postfix + '_aerial_demo' + '.mp4'

    g_fid_start = 367
    g_fid_end = 9073

    a_fid_start = 0
    a_fid_end = 8706

    nr_frames = 8700

    writer_fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    writer_size = (2560, 1440)
    writer = cv2.VideoWriter(fn_out, writer_fourcc, 30, writer_size)

    cap_g = cv2.VideoCapture(fn_in_g)
    assert cap_g.isOpened()

    cap_a = cv2.VideoCapture(fn_in_a)
    assert cap_a.isOpened()

    for i in range(0, g_fid_start):

        cap_g.read()

    for i in range(0, a_fid_start):

        cap_a.read()

    for i in range(nr_frames):

        ret, frame_g = cap_g.read()
        assert ret

        ret, frame_a = cap_a.read()
        assert ret

        frame_a[0:1440, 0:1280] = frame_g[0:1440, 1280:]

        cv2.putText(frame_a, 'ground camera', (40, 760),
                    cv2.FONT_HERSHEY_SIMPLEX, 1.6, (0, 0, 0), 4)

        cv2.putText(frame_a, 'drone camera', (1320, 760),
                    cv2.FONT_HERSHEY_SIMPLEX, 1.6, (0, 0, 0), 4)

        writer.write(frame_a)

        print(i)

    writer.release()

    pass

if __name__ == '__main__':

    #process_demo_videos(4, 1)

    process_drone_demo_videos()

    pass


from future.utils import lmap # pragma: no cover

def fizz(input):
    return lmap(lambda x: (x % 3 == 0 and "Fizz") or x, input)

def buzz(input):
    return lmap(lambda x: (x % 5 == 0 and "Buzz") or x, input)

def fizzbuzz(input):
    join = lambda f, b: (
        (f == 'Fizz' and b == 'Buzz' and "FizzBuzz") or
        (f == 'Fizz' and f) or # return Fizz only if fizz == 'Fizz'
        (b == 'Buzz' and b) or # return Buzz only if buzz == 'Buzz'
        f                      # return number if none of the above
    )

    return [join(f, b) for (f, b) in zip(fizz(input), buzz(input))]

def minify_fizzbuzz(input, fizz=3, buzz=5):
    fizzbuzz = fizz * buzz
    return [(
        ((x % fizzbuzz == 0) and "FizzBuzz") or
        ((x % fizz == 0) and "Fizz") or
        ((x % buzz == 0) and "Buzz") or
        x
    ) for x in input]

if __name__ == '__main__': # pragma: no cover
    r = range(1, 101)
    fb = minify_fizzbuzz(r)

    for index in r:
        print("{}: {}".format(index, fb[index - 1]))


import os
import re
# from tools import write_map
from writefile.tools import write_map

def write_go_dapr_mygrations(p, path):
    """生成go dapr 后端文件"""
    print("生成go dapr 后端 数据库迁移文件。。。:", path)
    # 生成目录

    lines = []

    for table in p.tables:
        make_gin_dapr_internal_database_migrations_up(table, path)
        make_gin_dapr_internal_database_migrations_down(table, path)

def make_gin_dapr_internal_database_migrations_up(table, project_dir):
    file_path =  os.path.join(project_dir,f"internal/database/migrations/00000_{table.name}.up.sql")
    f_list = []
    f_list.append(f"/* {table.zh_name} */\n")
    f_list.append(f"CREATE TABLE IF NOT EXISTS `{table.name}`  (\n")
    for column in table.columns:
        default = f" DEFAULT {column.default.upper()}" if column.default else ""
        extra = column.extra.upper()
        s = f'    `{column.name}` {column.type.MYSQL_TYPE} {column.create_can_empty}{default} {extra} COMMENT \'{column.zh_name}\',\n'
        # print(s)
        f_list.append(s)

    for column in table.columns:
        if column.key:
            if column.key.lower() in ["pri","primary"]:
                s = f"    PRIMARY KEY (`{column.name}`),\n"
            elif column.key.lower() in ["pri","primary"]:
                s = f"    UNIQUE KEY (`{column.name}`),\n"

                    # s = f"{tab*tab_num}UNIQUE INDEX (`{column.name}`),\n"
            f_list.append(s)

    f_list[-1] =re.sub(",\n$","\n",f_list[-1])
    f_list.append(f") CHARACTER SET = utf8mb4;\n")

    r =  {file_path:f_list}
    write_map(r)

def make_gin_dapr_internal_database_migrations_down(table, project_dir):
    file_path =  os.path.join(project_dir,f"internal/database/migrations/00000_{table.names}.down.sql")
    f_list = []
    f_list.append(f"DROP TABLE IF EXISTS `{table.names}`;")
    write_map({file_path:f_list})


# Example of Extending the Thread Class and Returning Values
# We may need to retrieve data from the thread, such as a return value.
# There is no way for the run() function to return a value to the start() function and back to the caller.
# Instead, we can return values from our run() function by storing them as instance variables and having the caller retrieve the data from those instance variables.
#  indirectly return a value from the extended threading.Thread class.
import threading as th
from time import sleep

#  update the run() function to store some data as an instance variable (also called a Python attribute).
# custom thread class
class CustomThread(th.Thread):
    # override the run function
    def run(self):
        # block for a moment
        sleep(2)
        # display a message
        print('From another thread')
        # store return value
        self.value = 99

# Next, we can retrieve the “returned” (stored) value from the run function in the main thread.
# get the value returned from run
# create the thread
thread = CustomThread()
# start the thread
thread.start()
# wait for the thread to finish
print('Waiting for the thread to finish')
thread.join()
# get the value returned from run
value = thread.value
print(f'Got: {value}')


""" Implement tasks for invoke.
"""

import os
import sys
import subprocess
from invoke import task

this_dir = os.path.dirname(__file__)

def call(*cmd):
    sys.exit(subprocess.call(cmd, cwd=this_dir))

def get_node_exe():
    node_exe = 'nodejs'
    try:
        subprocess.check_output([node_exe, '--version'])
    except Exception:
        node_exe = 'node'
    return node_exe

@task
def lint(ctx):
    """ Test for style errors using JSHint. """
    call
    ret_code = subprocess.call(['jshint', 'bsdf.js'], cwd=this_dir, shell=True)
    if ret_code == 0:
        print('No style errors found')
    sys.exit(ret_code)

@task
def test_shared(ctx):
    """ Run BSDF tests on JS using the shared test service. """
    sys.path.insert(0, os.path.join(this_dir, '..', '_tools'))
    import testservice
    exe = get_node_exe()
    testservice.main(this_dir, exe, 'testservice_runner.js', '{fname1}', '{fname2}',
                     excludes=['roundfloatisnotint'])

@task
def test_unit(ctx):
    """ Run unit tests for JS BSDF implementation. """
    exe = get_node_exe()
    call(exe, 'test_unit.js')


from collections import deque

# 큐를 사용했으나 dfs 특성상 pop을 하지 못해 배열과 같은 효과 발생..
T = int(input())

dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]

def dfs(core_idx, line_len, core_num):
    global min_line, max_core
    if core_idx == len(core):  # 모든 코어 연결 성공
        if core_num > max_core:
            max_core = core_num
            min_line = line_len
        elif core_num == max_core:
            if min_line > line_len:
                min_line = line_len
        return

    y, x = core[core_idx]
    mem_visit = [[0 for i in range(N)] for j in range(N)]
    for n in range(N):
        for m in range(N):
            mem_visit[n][m] = visit[n][m]

    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        tmp_len = 0
        line_success = True
        while True:
            if ny < 0 or nx < 0 or ny > N - 1 or nx > N - 1:  # 벽까지 연결
                break
            if visit[ny][nx] == 1 or visit[ny][nx] == 2:  # core 이거나 전선 #더이상 연결 불가
                line_success = False
                break
            # 벽까지 연결될 수 있는지 검사 #i가 변하지 않으므로 한방향으로 증가
            visit[ny][nx] = 2
            nx += dx[i]
            ny += dy[i]
            tmp_len += 1
        if line_success:
            dfs(core_idx + 1, line_len + tmp_len, core_num + 1)
        for n in range(N):
            for m in range(N):
                visit[n][m] = mem_visit[n][m]
    # core에서 연결 불가
    dfs(core_idx + 1, line_len, core_num)

for test_case in range(1, T + 1):
    N = int(input())
    board = []
    visit = [[0 for i in range(N)] for j in range(N)]

    for n in range(N):
        # line = list(map(int, f.readline().split()))
        line = list(map(int, input().split()))
        board.append(line)

    core = deque([])
    core_idx = 0  # core 인덱스
    line_len = 0  # 전선 수
    core_num = 0  # 사용 core 수
    for y in range(N):
        for x in range(N):
            if board[y][x] == 1:
                visit[y][x] = 1
                if 1 <= y < N - 1 and 1 <= x < N - 1:
                    core.append([y, x])  # y: 세로, x: 가로
                else:
                    core_num += 1

    min_line = 150
    max_core = 0
    dfs(core_idx, line_len, core_num)
    print('#' + str(test_case) + ' ' + str(min_line))


from flask import Flask, render_template, request, redirect

app = Flask(__name__)

students=[]

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

@app.route('/registrants')
def registrants():
    return render_template("register.html", students=students)

@app.route('/register', methods=["POST"])
def register():
    name = request.form.get("name")
    dorm = request.form.get("dorm")
    if not name or not dorm:
        pass
    else:
        students.append(f'{name} from {dorm}')
        return redirect('/registrants')

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


from GWXtreme import eos_model_selection as ems
import lalsimulation as lalsim
import lal
import numpy as np
import pylab as pl
import json

# Prepare json with all values needed for table we can send to Jocelyn Read

#           Narrow                  Broad
# EOS Tabulated MCMC Paper  Tabulated MCMC Paper

p_eos_val = {"AP4":[33.269,2.830,3.445,3.348],
             "MPA1":[33.495,3.446,3.572,2.887],
             "MS1":[33.858,3.224,3.033,1.325]}

modsel1 = ems.Model_selection(posteriorFile="posterior_samples/posterior_samples_narrow_spin_prior.dat")

modsel2 = ems.Model_selection(posteriorFile="posterior_samples/posterior_samples_broad_spin_prior.dat")

with open("Analysis/Refined_bestof_1_8_eos_global_values.json","r") as f:
    data = json.load(f)

table_values = {}
for eos in data:

    bfs_holder = [] # hold bf for each eos

    n_lal_bf = modsel1.computeEvidenceRatio(eos,"SLY")
    b_lal_bf = modsel2.computeEvidenceRatio(eos,"SLY")

    p1,g1,g2,g3,_ = data[eos]
    n_mc_bf = modsel1.computeEvidenceRatio([p1,g1,g2,g3],"SLY")
    b_mc_bf = modsel2.computeEvidenceRatio([p1,g1,g2,g3],"SLY")

    if eos in p_eos_val:

        p1,g1,g2,g3 = p_eos_val[eos]
        n_p_bf = modsel1.computeEvidenceRatio([p1,g1,g2,g3],"SLY")
        b_p_bf = modsel2.computeEvidenceRatio([p1,g1,g2,g3],"SLY")

    else:

        n_p_bf = "nah"
        b_p_bf = "nah"

    table_values.update({eos:[n_lal_bf,n_mc_bf,n_p_bf,b_lal_bf,b_mc_bf,b_p_bf]})

with open("Plots/Casabona_plots/data/table_values_1.json","w") as f:
    json.dump(table_values, f, indent=2, sort_keys=True)


entrada = int(input())

def fibonacci(num):
    nums = [0]
    a, b = 0, 1
    while len(nums) < num:
        nums.append(b)
        a, b = b, a + b
    return nums

string = ''
for x in fibonacci(entrada):
    if x == fibonacci(entrada)[-1]:
        string += f"{x}"
    else:
        string += f"{x} "

print(string)


#Maliha Tasnim
#MALIHA.TASNIM64@myhunter.cuny.edu
#Date: September 26, 2022
#This program does stuff, hw24
#apple banana cantalope durian shrub
#af bce gdfgb agcg edc dade fggga gb
list1 = input("Enter a list of words, separated by a space: ")
list2= list1.split(' ')
print("number of words: ",(len(list2)))
lettera = "a"
letterb = "b"
number = 0
for i in range (len(list2)):
    if lettera in list2[i][-1]:
        number += 1
    if letterb in list2[i][-1]:
        number +=1
fraction = round(number/len(list2),2)
print("number of words ending with a or b: ", number)
print("fraction of words ending with a or b: ", fraction)


import numpy as np

class Control:

    def __init__(self, model):

        # Bind model
        self.model = model

        # Desired x_pos
        self.xd = 0.0

        # Control parameters
        self.N = 100  # Prediction and control horizon

        # Control parameters
        if self.model.name == 'Pendulum':
            self.Q = np.mat([[100, 0, 0, 0], [0, 10, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
            self.R = np.mat(np.identity(1))
            self.P = np.mat([[1000, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])
        else:
            self.Q = np.mat([[1.0, 0.0], [0.0, 1.0]])
            self.R = np.mat(np.identity(1))
            self.P = np.mat([[1.0, 0.0], [0.0, 1.0]])

        # Get dynamics
        A = np.mat(self.model.A_disc)
        B = np.mat(self.model.B_disc)

        # Calculate matrix relating initial state to all successive states
        Ahat = np.eye(len(A))
        for i in range(self.N):
            An = np.linalg.matrix_power(A, i + 1)
            Ahat = np.r_[Ahat, An]
        Ahat = Ahat[len(A):, :]

        # Calculate matrix relating control signals to successive states
        Cbar = np.zeros((len(A), self.N))
        for i in range(self.N):
            tmp = None
            for ii in range(i + 1):
                tm = np.linalg.matrix_power(A, ii) * B
                if tmp is None:
                    tmp = tm
                else:
                    tmp = np.c_[tm, tmp]
            for _ in np.arange(i, self.N - 1):
                tm = np.zeros(B.shape)
                if tmp is None:
                    tmp = tm
                else:
                    tmp = np.c_[tmp, tm]
            Cbar = np.r_[Cbar, tmp]
        Cbar = Cbar[len(A):, :]

        # Calculate penalty matrices
        tm1 = np.eye(self.N)
        tm1[self.N - 1, self.N - 1] = 0
        tm2 = np.zeros((self.N, self.N))
        tm2[self.N - 1, self.N - 1] = 1
        Qbar = np.kron(tm1, self.Q) + np.kron(tm2, self.P)
        Rbar = np.kron(np.eye(self.N), self.R)

        # Calculate objective derivative solution
        self.H = Cbar.T * Qbar * Cbar + Rbar
        self.F_trans = Ahat.T * Qbar * Cbar

    def set_desired_position(self, x):
        self.xd = x

    def control(self, state):

        # Initial state
        x0 = np.reshape(np.mat(state), (len(state), 1))

        # Solve for optimal control
        uopt = -self.H.I * self.F_trans.T * x0

        # Take only first control signal
        u = uopt[0]

        return u


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

# ## Тестовое задание для Bewise, Чупина Д.В.

# Первым делом стоит загрузить нужные для работы библиотеки, а также таблицу с данными в формате датафрейма.

# In[1]:

import pandas as pd
import pymorphy2
from yargy import Parser, rule, and_, or_
from yargy.predicates import gram, dictionary
from yargy.pipelines import caseless_pipeline

# In[2]:

df = pd.read_csv(r"C:\Users\Эрвин\Documents\Machine Learning\TestTask\NLP\test_data.csv")

# После этого имеет смысл оставить только те реплики, которые говорит менеджер, потому что в задании нет указаний для клиента. Также стоит добавить три новых столбца, все булевые и по умолчанию принимают значение **False** для всех строк: первый столбец показывает, есть ли в строке приветствие, второй показывает, есть ли в строке прощание, а третий -- есть ли и приветствие и прощание со стороны менеджера во всём отдельно взятом диалоге. После этого можно взглянуть на данные полностью -- их совсем немного, всего 201 строка.

# In[3]:

df = df.loc[df['role'] == 'manager']
df = df.reset_index(drop = True)
df['greeting'] = False
df['farewell'] = False
df['insight'] = False

# In[4]:

pd.set_option("display.max_rows", None)
df

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

# In[5]:

RULE = caseless_pipeline([
    'добрый',
    'доброе утро',
    'утро доброе',
    'добрый день',
    'день добрый',
    'добрый вечер',
    'вечер добрый',
    'здравствуйте'
])

df['greeting'] = False

parser = Parser(RULE)
text = list(df['text'])
for i in range(len(text)):
    line = text[i].lower()
    for match in parser.findall(line):
        if (df.iloc[i, 4] == False):
            print(i, line)
            df.iloc[i, 4] = True

# Для поиска же реплик с представлением себя было выбрано считать за таковую ту, где перед или после имени есть глагол "зовут", что используется в распространённом способе представления себя. Изначально была совершена попытка поиска имён через метод библиотеки Natasha, однако с этим возникли проблемы: поскольку это запись телефонного разговора, то все слова здесь, за исключением первого в строке, записаны прописными буквами, что мешает распознанию имени как имени, поскольку стоит оно не в начале предложения и начинается с прописной буквы. Была предпринята попытка поработать с этой библиотекой в том случае, когда все слова в тексте начинались с заглавной буквы, но это не увенчалось успехом -- слишком много случалось ложно-положительных результатов.
#
# Можно было искать по именам менеджеров, однако, поскольку к заданию не даются отдельно данные с их именами, я предположила, что мы не должны заранее их знать, а собирать всевозможные имена было бы крайне времязатратно.
#
# Поэтому пришлось выбрать именно этот подход, который, к сожалению, не всегда срабатывает: имеется, к примеру, способ представления как "это [имя менеджера]". Но такой вариант было сложно учесть, поскольку сочетание слова "это" и существительного слишком распространено в тексте в иных контекстах, а не только в представлении своего имени. Однако, учитывая и такой минус, всё же данный подход можно в целом считать рабочим.
#
# Также для удобства сразу же выводятся и реплика целиком, и имя менеджера. Имя определяется как таковое, если до него либо идёт слово "зовут", либо слово "меня" (но при условии, что текущее слово не "зовут"). После этого найденное имя выводится сразу после реплики.

# In[6]:

RULE = or_(
    rule(
        and_(
            gram('NOUN'),
        ),
        gram('NOUN').optional().repeatable(),
        dictionary({
            'зовут'
        })
    ),
    rule(
        dictionary({
            'зовут'
        }),
        and_(
            gram('NOUN'),
        ),
        gram('NOUN').optional().repeatable()
    )
)

parser = Parser(RULE)
text = list(df['text'])
for i in range(len(text)):
    line = text[i].lower()
    for match in parser.findall(line):
        print(i, line)
        prev_word = ''
        name_found = False
        for word in line.split():
            if ((prev_word == 'меня' or prev_word == 'зовут') and word != 'зовут' and name_found == False):
                print('Имя менеджера: ' + word)
                name_found = True
            prev_word = word

# Название компании находится следующим образом: оно определяется как таковое, если до названия шло слово "компания". Также, поскольку название компании может состоять из нескольких слов, выводятся все существительные, идущие после слова "компания".

# In[7]:

RULE = rule(
    dictionary({
        'компания'
    }),
    and_(
        gram('NOUN'),
    ),
    gram('NOUN').optional().repeatable()
)

parser = Parser(RULE)
for i in range(len(text)):
    line = text[i].lower()
    for match in parser.findall(line):
        temp = ''
        for _ in match.tokens:
            temp += _.value + ' '
        print(i, temp)

# Прощание определяется схожим образом, что и приветствие; и так же информация о том, что данная реплика является прощанием, заносится в отдельный столбик.

# In[8]:

RULE = caseless_pipeline([
    'всего доброго',
    'хорошего дня',
    'хорошего вечера',
    'до свидания',
    'до понедельника',
    'до вторника',
    'до среды',
    'до четверга',
    'до пятницы',
])

df['farewell'] = False

parser = Parser(RULE)
text = list(df['text'])
for i in range(len(text)):
    line = text[i].lower()
    for match in parser.findall(line):
        if (df.iloc[i, 5] == False):
            print(i, line)
            df.iloc[i, 5] = True

# Сейчас можно пройтись по всем строкам таблицы и посмотреть, есть ли в отдельно взятом диалоге и приветствие, и прощание. Если да, то **все** строки данного диалога помечаются как **True** в столбце insight.

# In[9]:

gret = False
fare = False
dlg = 0
for i in range(len(df)):
    if (df.iloc[i,0] > dlg):
        dlg+=1
        gret = False
        fare = False
    if (df.iloc[i,4] == True):
        gret = True
    if (df.iloc[i,5] == True):
        fare = True
    if (gret and fare):
        for j in range(len(df)):
            if (df.iloc[j,0] == dlg):
                df.iloc[j,6] = True

# In[10]:

pd.set_option("display.max_rows", None)
df


from itertools import chain

from notifications_python_client.errors import HTTPError

from app.extensions import redis_client
from app.notify_client import NotifyAdminAPIClient, cache

class OrganisationsClient(NotifyAdminAPIClient):

    @cache.set('organisations')
    def get_organisations(self):
        return self.get(url='/organisations')

    @cache.set('domains')
    def get_domains(self):
        return list(chain.from_iterable(
            organisation['domains']
            for organisation in self.get_organisations()
        ))

    def get_organisation(self, org_id):
        return self.get(url='/organisations/{}'.format(org_id))

    @cache.set('organisation-{org_id}-name')
    def get_organisation_name(self, org_id):
        return self.get_organisation(org_id)['name']

    def get_organisation_by_domain(self, domain):
        try:
            return self.get(
                url='/organisations/by-domain?domain={}'.format(domain),
            )
        except HTTPError as error:
            if error.status_code == 404:
                return None
            raise error

    @cache.delete('organisations')
    def create_organisation(self, name, crown, organisation_type, agreement_signed):
        return self.post(
            url="/organisations",
            data={
                "name": name,
                "crown": crown,
                "organisation_type": organisation_type,
                "agreement_signed": agreement_signed,
            }
        )

    @cache.delete('domains')
    @cache.delete('organisations')
    def update_organisation(self, org_id, cached_service_ids=None, **kwargs):
        api_response = self.post(url="/organisations/{}".format(org_id), data=kwargs)

        if cached_service_ids:
            redis_client.delete(*map('service-{}'.format, cached_service_ids))

        if 'name' in kwargs:
            redis_client.delete(f'organisation-{org_id}-name')

        if 'email_branding_id' in kwargs and kwargs['email_branding_id']:
            redis_client.delete(f'organisation-{org_id}-email-branding-pool')

        return api_response

    @cache.delete('organisation-{org_id}-email-branding-pool')
    def add_brandings_to_email_branding_pool(self, org_id, branding_ids):
        return self.post(
            url=f"/organisations/{org_id}/email-branding-pool",
            data={'branding_ids': branding_ids}
        )

    @cache.delete('service-{service_id}')
    @cache.delete('live-service-and-organisation-counts')
    @cache.delete('organisations')
    def update_service_organisation(self, service_id, org_id):
        data = {
            'service_id': service_id
        }
        return self.post(
            url="/organisations/{}/service".format(org_id),
            data=data
        )

    def get_organisation_services(self, org_id):
        return self.get(url="/organisations/{}/services".format(org_id))

    @cache.delete('user-{user_id}')
    def remove_user_from_organisation(self, org_id, user_id):
        return self.delete(f'/organisations/{org_id}/users/{user_id}')

    def get_services_and_usage(self, org_id, year):
        return self.get(
            url=f"/organisations/{org_id}/services-with-usage",
            params={"year": str(year)}
        )

    @cache.delete('organisations')
    @cache.delete('domains')
    def archive_organisation(self, org_id):
        redis_client.delete(f'organisation-{org_id}-name')

        return self.post(
            url=f"/organisations/{org_id}/archive",
            data=None,
        )

    @cache.set('organisation-{org_id}-email-branding-pool')
    def get_email_branding_pool(self, org_id):
        branding = self.get(
            url=f"/organisations/{org_id}/email-branding-pool",

        )
        return branding["data"]

    @cache.delete('organisation-{org_id}-email-branding-pool')
    def remove_email_branding_from_pool(self, org_id, branding_id):
        self.delete(f"/organisations/{org_id}/email-branding-pool/{branding_id}")

organisations_client = OrganisationsClient()


"""
GUI to simulate an origami robot.

This GUI file interacts with the main.py and module.py files.

"""

import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.animation as animation
import numpy as np
import module
from tkinter import filedialog
import pandas as pd
import time
import serial
import scipy.io as sio
import cv2.aruco as aruco
import os

import matplotlib.animation as animation

class GUI(tk.Frame):
    """GUI Class to create and interact with the GUI

    Args:
        tk (tk.Frame): tkinter library framework to create and compose GUI.
    """

    def __init__(self, master=None):
        """Initialisation of the GUI

        Args:
            master (tk.TK(), optional): Root of the GUI, allows to declare the GUI on a single thread. Defaults to None.
        """
        super().__init__(master)
        self.master = master
        self.grid()
        self.create_widgets()

        self.value_res = 0

    def create_widgets(self):
        """Create the GUI widgets
        """

        # Workspace widget
        self.label_show_workspace = tk.Label(self.master, text='Plot workspace')
        self.label_show_workspace.grid(row=0, column=0, padx=30)
        self.var_plot_ws = tk.IntVar()

        # Workspace activation through a checkbutton
        self.plot_workspace_button = tk.Checkbutton(self.master, command=self.add_workspace, selectcolor='black',
                                                    variable=self.var_plot_ws)
        self.plot_workspace_button.grid(row=0, column=1, padx=30)
        self.ws_plotted = False

        self.label_show_workspace = tk.Label(self.master, text='Resolution workspace')
        self.label_show_workspace.grid(row=1, column=0, padx=30)
        self.resolution_workspace = tk.Scale(self.master, from_=1, to=100, command=self.adapt_resolution,
                                             orient=tk.HORIZONTAL)
        self.resolution_workspace.grid(row=2, column=0,columnspan=2, sticky=tk.NSEW, padx=30)

        # Quit button
        self.quit = tk.Button(self.master, text='QUIT', command=self.quit_program)
        self.quit.grid(row=13, column=0)

        # Module generation
        self.module = module.Module(length_base_arms=6, length_base_between_arms=10, length_lower_arm=5,
                                    length_upper_arm=10, length_surface_arms=6, length_surface_between_arms=10,
                                    thickness=0, joint_radius=0.1, translate_x=0, translate_y=0)

        # Initial figure generation
        self.figure_canvas()
        self.module.plot_module(self.ax)
        self.fig_tk.draw

        # Possibility to connect module through Serial connection. Change port according to your OS and the port you are connecting your origami to.
        self.ser = None
        try:
            self.ser = serial.Serial('/dev/ttyACM0', timeout=None, baudrate=57600)
        except serial.SerialException:
            pass

        # Initialize rotation matrix to compute inverse kinematics.
        self.predicted_rotation_matrix = None

        # Update according to serial connection.
        self.update()

    def adapt_resolution(self, value):
        self.value_res = int(value)

    def quit_program(self):
        """Quit nicely the program closing the serial connection if needed.
        """
        if self.ser is not None:
            self.ser.close()
        self.master.destroy()

    def add_workspace(self):
        """Add workspace plot to simulation. Verify first if workspace is not plotted.
        """
        self.ws_plotted = not (self.ws_plotted);

    def update(self, workspace=False):
        """Update the simulation by computing a new rotation matrix according to sensors inputs.
        """
        if self.predicted_rotation_matrix is None:
            self.predicted_rotation_matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1]
        if self.ser is not None:
            # first, load our neural network structure that we exported from matlab.
            mat_contents = sio.loadmat('exported_ann_structure.mat', struct_as_record=False)

            structure = mat_contents['exported_ann_structure']

            cc = str(self.ser.readline())
            self.ser.flushInput()
            words = cc.split()  # parse the string for the ratios
            if len(words) == 7:
                r_rat = float(words[1])
                g_rat = float(words[3])
                b_rat = float(words[5])

                ### this is where we get the arduino data through serial:
                RGBratios = np.array(
                    [[r_rat, g_rat, b_rat]])  # use [[ ]] to make a 2d array, for compatible matrix multiplication.
                ###

                # now, using the neural network and an RGB ratios input triplet, predict the rotation matrix:
                self.predicted_rotation_matrix = \
                self.my_ann_evaluation(structure, np.transpose(RGBratios)).transpose().tolist()[0]
                self.predicted_rotation_matrix = list(self.predicted_rotation_matrix)

            # Inverse kinematics computation according to newly computed rotation matrix of the surface.
            self.module.inverse_kinematics(self.predicted_rotation_matrix)

        # Reset axis to draw updated module
        self.ax.clear()
        self.ax.axis('off')
        self.ax.set_xlim(15, -15)
        self.ax.set_ylim(-15, 15)
        self.ax.set_zlim(0, 20)
        if self.var_plot_ws.get() or self.ws_plotted:
            self.module.plot_workspace(self.ax, self.value_res)
            self.ws_plotted = True
        else:
            self.ws_plotted = False
        self.module.plot_module(self.ax)
        self.fig_tk.draw()

        # Call the update function every 1 ms
        self.after(100, self.update)

    def my_ann_evaluation(self, my_ann_structure, input):
        """Evaluation of ann structure to retrieve rotation matrix.

        Args:
            my_ann_structure (matlab matrix exported): Neural network
            input (np.array): 1x1x3 array containing R, G, B ratios.

        Returns:
            np.array: Rotation matrix with dimension 1x1x9
        """

        # extract fields as variables
        ymax = my_ann_structure[0, 0].input_ymax;
        ymin = my_ann_structure[0, 0].input_ymin;
        xmax = my_ann_structure[0, 0].input_xmax;
        xmin = my_ann_structure[0, 0].input_xmin;

        input_preprocessed = (ymax - ymin) * (input - xmin) / (xmax - xmin) + ymin;

        # Pass it through the ANN matrix multiplication
        y1 = np.tanh(np.matmul(my_ann_structure[0, 0].IW, input_preprocessed) + my_ann_structure[0, 0].b1);
        y2 = np.matmul(my_ann_structure[0, 0].LW, y1) + my_ann_structure[0, 0].b2;

        ymax = my_ann_structure[0, 0].output_ymax;
        ymin = my_ann_structure[0, 0].output_ymin;
        xmax = my_ann_structure[0, 0].output_xmax;
        xmin = my_ann_structure[0, 0].output_xmin;

        res = (y2 - ymin) * (xmax - xmin) / (ymax - ymin) + xmin;

        # return the result of the neural network:
        return res

    def figure_canvas(self):
        """Figure Canvas to embed on tkinter frame.
        """
        self.fig = plt.Figure(figsize=(20, 20), dpi=100)
        self.ax = self.fig.add_subplot(111, projection="3d")
        self.ax.axis('off')
        self.fig_tk = FigureCanvasTkAgg(self.fig, self.master)
        self.fig_tk.get_tk_widget().grid(row=0, column=2, rowspan=13)


def error(e):
    if e == 400:
        data = "Bad Request"
    elif e == 401:
        data = "Unauthorized. Please check your credentials " + str(e)
    elif e == 503:
        data = "Service temporarily unavailable " + str(e)
    elif e == 500:
        data = "Error executing methodName please raise an issue on github "+ str(e)
    else:
        data = "Error"
    return data


import json
import os.path
import urllib.request
import sqlite3

from datetime import datetime

if __name__ == '__main__':
    user_json = json.load(urllib.request.urlopen("https://ethtrader.github.io/donut.distribution/users.json"))

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(BASE_DIR, "../../database/donut-bot.db")
    db_path = os.path.normpath(db_path)

    with sqlite3.connect(db_path) as db:
        cursor = db.cursor()

        for user in user_json:
            print(f'user: {user["username"]} -- address: {user["address"]}')
            cursor.execute("INSERT INTO users (username, address, last_updated) VALUES (?, ?, ?)",
                           (user["username"], user["address"], datetime.now()))

        cursor.execute("INSERT INTO users (username, address, last_updated) VALUES (?, ?, ?)",
                       ['donut-bot', '0xa8C8c9e18C763805c91bcB720B2320aDe16a0BBf', datetime.now()])


import unittest
from collections import deque
import heapq

def arrayManipulationMem(n, queries):
    arr = [0 for i in range(n)]
    maximun = 0
    for item in queries:
        a = item[0] - 1
        b = item[1]
        value = item[2]
        for x in range(a, b):
            arr[x] += value
            maximun = max(arr[x], maximun)

    return maximun

def arrayManipulation(n, queries):
    maximum = 0
    current = 0

    starts = []
    ends = []

    for item in queries:
        starts.append((item[0], item[2]))
        ends.append((item[1], item[2]))

    heapq.heapify(starts)
    heapq.heapify(ends)

    while starts or ends:
        if starts and ends and starts[0][0] <= ends[0][0]:
            s = heapq.heappop(starts)
            current += s[1]
        else:
            e = heapq.heappop(ends)
            current -= e[1]
        maximum = max(maximum, current)

    return maximum

class Test(unittest.TestCase):

    def test_case(self):
        result = arrayManipulation(5, [[1, 2, 100], [2, 5, 100], [3, 4, 100]])
        self.assertEqual(200, result)

    def test_case_b(self):
        result = arrayManipulation(5, [[2, 6, 8], [3, 5, 7], [1, 8, 1], [5, 9, 15]])
        self.assertEqual(31, result)


def solution(answers):
    person1, person2, person3 = [1,2,3,4,5], [2,1,2,3,2,4,2,5], [3,3,1,1,2,2,4,4,5,5]
    persons = [person1, person2, person3]

    answer = []
    for person in persons:
        cycleNum, remainNum = len(answers) // len(person), len(answers) % len(person)
        method = (person * cycleNum) + person[:remainNum]

        count = 0
        for idx in range(len(answers)):
            correctNumber = answers[idx]

            if correctNumber == method[idx]:
                count+=1

        answer.append(count)

        maxPerson = [i+1 for i in range(len(answer)) if answer[i] == max(answer)]

    return maxPerson

완전탐색/모의고사.py


"""
    warriorbeat/api/utils/utils.py
    Various helper functions
"""

def deep_merge_lists(original, incoming):
    """
    Deep merge two lists. Modifies original.
    Reursively call deep merge on each correlated element of list.
    If item type in both elements are
     a. dict: call deep_merge_dicts on both values.
     b. list: Calls deep_merge_lists on both values.
     c. any other type: Value is overridden.
     d. conflicting types: Value is overridden.

    If length of incoming list is more that of original then extra values are appended.

    See: https://stackoverflow.com/a/50773244
    """
    common_length = min(len(original), len(incoming))
    for idx in range(common_length):
        if isinstance(original[idx], dict) and isinstance(incoming[idx], dict):
            deep_merge_dicts(original[idx], incoming[idx])

        elif isinstance(original[idx], list) and isinstance(incoming[idx], list):
            deep_merge_lists(original[idx], incoming[idx])

        else:
            original[idx] = incoming[idx]

    for idx in range(common_length, len(incoming)):
        original.append(incoming[idx])

def deep_merge_dicts(original, incoming):
    """
    Deep merge two dictionaries. Modfies original.
    For key conflicts if both values are:
     a. dict: Recursivley call deep_merge_dicts on both values.
     b. list: Calls deep_merge_lists on both values.
     c. any other type: Value is overridden.
     d. conflicting types: Value is overridden.

    See: https://stackoverflow.com/a/50773244
    """
    for key in incoming:
        if key in original:
            if isinstance(original[key], dict) and isinstance(incoming[key], dict):
                deep_merge_dicts(original[key], incoming[key])

            elif isinstance(original[key], list) and isinstance(incoming[key], list):
                deep_merge_lists(original[key], incoming[key])

            else:
                original[key] = incoming[key]
        else:
            original[key] = incoming[key]

def get_json_load_method(instance, json_data):
    """Determine to load json as object or string."""
    json_type = type(json_data)
    method = 'loads' if json_type is str else 'load'
    if json_type is str:
        json_opener = json_data[0]
        json_type = list if json_opener == '[' else dict
    method = getattr(instance, method)
    return (method, json_type)


# --------------------------------------------------------
# SSD @ Dragon
# Copyright(c) 2017 SeetaTech
# Written by Ting Pan
# Modified by Zhuang Liu
# --------------------------------------------------------

import numpy as np

import dragon.vm.caffe as caffe
import dragon.core.workspace as ws

from .generate_anchors import generate_anchors

class PriorBoxLayer(caffe.Layer):
    """Generate default boxes(anchors).

    This layer may be redundant during inference time.

    """
    def setup(self, bottom, top):
        layer_params = eval(self.param_str)
        self._step = layer_params.get('step', None)
        self._offset = layer_params.get('offset', 0.5)
        self._clip = layer_params.get('clip', False)
        min_size = layer_params.get('min_size', [])
        max_size = layer_params.get('max_size', [])
        if not isinstance(min_size, list): min_size = [min_size]
        if not isinstance(max_size, list): max_size = [max_size]
        if len(max_size) > 0: assert len(min_size) == len(max_size)
        ratios = layer_params.get('aspect_ratio', [])
        aspect_ratios = [1.0]
        flip = layer_params.get('flip', True)
        for aspect_ratio in ratios:
            if not aspect_ratio in aspect_ratios:
                aspect_ratios.append(aspect_ratio)
                if flip: aspect_ratios.append(1.0 / aspect_ratio)
        self._num_anchors = len(min_size) * len(aspect_ratios) + len(max_size)
        self._anchors = generate_anchors(min_size, max_size, aspect_ratios)

    def forward(self, bottom, top):
        feature_maps = ws.FetchTensor(bottom[0])
        im_info = ws.FetchTensor(bottom[1])
        map_height, map_width = feature_maps.shape[2:]

        # 1. generate base grids
        shift_x = (np.arange(0, map_width) + self._offset) * self._step
        shift_y = (np.arange(0, map_height) + self._offset) * self._step
        shift_x, shift_y = np.meshgrid(shift_x, shift_y)
        # by lz.
        shifts = np.vstack((shift_x.ravel(), shift_y.ravel(),
                            shift_x.ravel(), shift_y.ravel(),
                            shift_x.ravel(), shift_y.ravel(),
                            shift_x.ravel(), shift_y.ravel(),
                            shift_x.ravel(), shift_y.ravel(),
                            shift_x.ravel(), shift_y.ravel())).transpose()

        # 2. apply anchors on base grids
        # add A anchors (1, A, 12) to
        # cell K shifts (K, 1, 12) to get
        # shift anchors (K, A, 12)
        # reshape to (K * A, 4) shifted anchors
        A = self._num_anchors
        K = shifts.shape[0]  # K = map_h * map_w
        # by lz.
        all_anchors = (self._anchors.reshape((1, A, 12)) +
                       shifts.reshape((1, K, 12)).transpose((1, 0, 2)))
        all_anchors = all_anchors.reshape((K * A, 12)).astype(np.float32)

        all_anchors[:, 0::2] /= im_info[1] # normalize by width
        all_anchors[:, 1::2] /= im_info[0] # normalize by height

        # 3. clip if necessary (default is False)
        if self._clip:
            all_anchors = np.minimum(np.maximum(all_anchors, 0.0), 1.0)

        # feed the default boxes(anchors)
        ws.FeedTensor(top[0], all_anchors)


import os

def replaceInName(dirPath, mapping, prefix="", suffix=""):
	'''Dir must be path, mapping - a dict with string:replacemnt pairs, prefix and
	suffix are optional. Only one change per file per use'''
	for filename in os.listdir(dirPath):
		for key in mapping:
			if key in filename:
				new_name =  prefix + filename.replace(key, mapping[key]) + suffix
				os.rename(dirPath + filename, dirPath + new_name)


import paho.mqtt.client as paho
import json
import os, sys

def on_connect(client, userdata, rc, qos):
    client.subscribe("benyamna_sensors/temp", qos=1)

def on_message(client, userdata, msg):
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #find parent directory
    from main.models import Temperature,Esp #import django model Temperature
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
    jsonArray = json.loads(msg.payload)
    esp, created= Esp.objects.get_or_create(mac=jsonArray["who"])
    new = Temperature(valeur=jsonArray["value"], who=esp)
    new.save()

def on_disconnect(client, userdata, rc):
    client.loop_stop(force=False)
    if rc != 0:
        print("Unexpected disconnection.")
    else:
        print("Disconnected")

client = paho.Client()
client.on_connect = on_connect
# client.on_subscribe = on_subscribe
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)

# client.subscribe("benyamna_sensors/temp", qos=1)


services = []

def metacafe(self):
    id = self.match.group('metacafe_id')
    title = self.match.group('metacafe_title')
    width = 640
    height = 360
    if self.width:
        width = self.width
    if self.height:
        height = self.height
    return self.render('metacafe.html', {'id': id, 'title': title, 'width': width, 'height': height})

services.append({
        're': '^http://www.metacafe.com/(w|watch)/(?P<metacafe_id>\d+)/(?P<metacafe_title>[a-zA-Z0-9-_]+)',
        'func': metacafe
    })


from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import PermissionDenied
from django.contrib.auth import get_user_model
from django.conf import settings
import jwt

User = get_user_model()

class JWTAuthentication(BasicAuthentication):
    """ Deals with incoming requests; will be applied over every route
    and once they are through, it will determine what each can do next """

    def authenticate(self, request):
        # This will get any token value:
        header = request.headers.get('Authorization')
        # If there is no header we let them through but give no permissions
        if not header:
            return None

        # If a broken token is sent, permission denied
        if not header.startswith('Bearer'):
            raise PermissionDenied(detail='Invalid Authorization Token Format')

        # If all goes well, decode token:
        token = header.replace('Bearer ', '')
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            user = User.objects.get(pk=payload.get('sub'))

        # If token is invalid, permission denied
        except jwt.exceptions.InvalidTokenError:
            raise PermissionDenied(detail='Invalid Token')
        # if the profile does not exist, permission denied
        except User.DoesNotExist:
            raise PermissionDenied(detail='User Not Found')

        return (user, token)


from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static

from apps.chat.views import PublicChatView, RegistrationView, LoginView, UserListView, PrivateChatView

urlpatterns = [
    url('^public-chat/$', PublicChatView.as_view(), name='public-chat'),
    url('^register/', RegistrationView.as_view(), name='register'),
    url('^login/', LoginView.as_view(), name='login'),
    url('^users/', UserListView.as_view(), name='user-list'),
    url('^private/', PrivateChatView.as_view(), name='private-chat')
]

urlpatterns += [
    # url(r'^api-auth/', include('rest_framework.urls',
    #                            namespace='rest_framework')),
    url('^{swagger_root}/'.format(swagger_root=settings.SWAGGER_ROOT_FOLDER.strip('/')),
        include('rest_framework_swagger.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


from tkinter import *
from tkinter import messagebox

# creating a root widget (window)
root = Tk()
root.title('Message Boxes')
root.iconbitmap('..\\misc\\tech.ico')  # add user defined icon

"""
Different message popups available:
- showinfo
- showwarning
- showerror
- askquestion
- askokcancel
- askyesno
"""

def info():
    response = messagebox.showinfo("Title", "Popup message")
    lbl = Label(root, text=response)
    lbl.pack()

def warning():
    response = messagebox.showwarning("Title", "Popup message")
    lbl = Label(root, text=response)
    lbl.pack()

def error():
    response = messagebox.showerror("Title", "Popup message")
    lbl = Label(root, text=response)
    lbl.pack()

def askquestion():
    response = messagebox.askquestion("Title", "Popup message")
    lbl = Label(root, text=response)
    lbl.pack()

def askokcancel():
    response = messagebox.askokcancel("Title", "Popup message")
    lbl = Label(root, text=response)
    lbl.pack()

def askyesno():
    response = messagebox.askyesno("Title", "Popup message")
    lbl = Label(root, text=response)
    lbl.pack()

"""
Multiple buttons showcasing the different popups
"""

button = Button(root, text='Info Popup', command=info)
button.pack()

button = Button(root, text='Warning Popup', command=warning)
button.pack()

button = Button(root, text='Error Popup', command=error)
button.pack()

button = Button(root, text='Ask Question Popup', command=askquestion)
button.pack()

button = Button(root, text='Ask OK | Cancel Popup', command=askokcancel)
button.pack()

button = Button(root, text='Ask Yes | No Popup', command=askyesno)
button.pack()

# create a mainloop to run the root widget
root.mainloop()


import picamera
import time
import cv2
import sys
import os
import threading
import boto3
from botocore.exceptions import ClientError
import requests
import json

TOTAL_VIDEO_DURATION = 60 #in seconds
SINGLE_VIDEO_DURATION = 0.5

VIDEO_PATH = 'Videos/clip%03d.h264'

#AWS parameters
URL = "https://5zkt8bff7d.execute-api.us-east-1.amazonaws.com/default/cc-project-lambda"
S3_BUCKET_NAME = 'cc-project-videos'

threads = []
counter = 0

def capture_frame(video_name):
    vidcap = cv2.VideoCapture(video_name)
    success,image = vidcap.read()
    count = 0
    final_image = None
    while success:
        final_image = image
        success,image = vidcap.read()
        #print('Read a new frame: ', success)
        count += 1

    image_name = ''
    if final_image is not None:
        image_name = video_name.removesuffix('h264') + 'jpg'
        cv2.imwrite(image_name, final_image) # save frame as JPEG file
        #print(f'Saving the final frame number:{count} and name: {image_name}')
    return final_image, image_name

def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = os.path.basename(file_name)

    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, bucket, object_name)
        print(f'Uploaded file {file_name}')
    except ClientError as e:
        print(f'Exception occurred while uploading {file_name}', e)
        return False
    return True

def get_face_recognition_result(image_filename):
    with open(image_filename, 'rb') as f:
        data = f.read()
    res = requests.post(URL,
                         data=data,
                         headers={'Content-Type': 'image/jpeg'})
    return res.json()

def process_video(video_file_name, start_time):
    imageObj, image_file_name = capture_frame(video_file_name)
    if imageObj is not None and image_file_name != '':
        face_recog_result = get_face_recognition_result(image_file_name)
        latency = time.time() - start_time
        global counter
        counter += 1
        print(f'{counter} person recognized: {face_recog_result["name"]}, {face_recog_result["major"]}, {face_recog_result["year"]}')
        print("Latency: {:.2f} seconds.".format(latency))
    #---- use multithreading here
    #upload_file(video_file_name, S3_BUCKET_NAME)
    t = threading.Thread(target = upload_file, args = (video_file_name, S3_BUCKET_NAME))
    t.start()
    threads.append(t)

def capture_and_process_video(single_video_duration = SINGLE_VIDEO_DURATION, total_video_duration = TOTAL_VIDEO_DURATION):
    number_of_videos = int(total_video_duration / single_video_duration)
    #tic = time.perf_counter()
    #print (f'initial tic = {tic}')
    #initial_time = tic
    with picamera.PiCamera() as camera:
        for filename in camera.record_sequence(
                    VIDEO_PATH % i for i in range(number_of_videos)):
            print('Recording to %s' % filename)
            start_time = time.time()
            camera.wait_recording(single_video_duration)
            #---- use multithreading here
            #process_video(filename, start_time)  #PROCESSING
            t = threading.Thread(target = process_video, args=(filename, start_time))
            t.start()
            threads.append(t)
            # tic = time.perf_counter()
            # if tic - initial_time >= total_video_duration:
            #     print (f'final tic = {tic}')
            #     break

if __name__ == "__main__":

    single_video_duration = SINGLE_VIDEO_DURATION
    total_video_duration = TOTAL_VIDEO_DURATION

    n = len(sys.argv)
    if n >= 2:
        single_video_duration = float(sys.argv[1])
    if n >= 3:
        total_video_duration = float(sys.argv[2])

    #time_start = time.time()
    capture_and_process_video(single_video_duration, total_video_duration)

    for t in threads:
        t.join()

    print('Image Recognition Over!!')
    #print('Total code time:', (time.time() - time_start), 'seconds')


import requests
import json
from typing import List

def add_pilot(data, key: str) -> List:
    pilots = []
    for i_pilot in data[key]:
        request_pilot = requests.get(i_pilot)
        pilot = json.loads(request_pilot.text)
        new_pilot = {}
        for key in pilot.keys():
            if key in ('name', 'height', 'mass', 'homeworld'):
                new_pilot[key] = pilot[key]
        pilots.append(new_pilot)
    return pilots

new_data = {}
try:
    result = requests.get('https://swapi.dev/api/starships/10')
    if result.status_code == 200:
        data = json.loads(result.text)

        for key in data.keys():
            if key in ('name', 'max_atmosphering_speed', 'starship_class'):
                new_data[key] = data[key]
            elif key == 'pilots':
                new_data[key] = add_pilot(data, key)

        with open('starship_info.json', 'w') as file:
            json.dump(new_data, file, indent=4)
            print(json.dumps(new_data, indent=4))
    else:
        raise ValueError('Ошибка')
except ValueError as exc:
    print(exc)


import tensorflow as tf
import numpy as np
import h5py
from keras.utils import np_utils
from sklearn.metrics import accuracy_score
from tensorflow.keras.models import load_model
import pandas as pd
import os
import yaml
import argparse

path_csv = "./scores_mitbih.csv"
#Get paths dictionary
parser = argparse.ArgumentParser()
parser.add_argument('--yaml',type=str)
args = parser.parse_args()
path_yaml = args.yaml
print(path_yaml)
print(type(path_yaml))

with open(path_yaml,'r') as f :
    paths = yaml.load(f, Loader=yaml.FullLoader)

path_mitbih = os.path.join(paths["MITBIH"]["Data"], "mitbih_test.csv")

#Get data
df_test = pd.read_csv(path_mitbih, header=None)
Y_test = np.array(df_test[187].values).astype(np.int8)
Y = Y_test
Y_test = np_utils.to_categorical(Y_test)

X_test = np.array(df_test[list(range(187))].values)[..., np.newaxis]
del df_test

names = list(paths["MITBIH"]["Models"].keys())
path = list(paths["MITBIH"]["Models"].values())

models = []
accs = []
d = dict()

#Get models
for i in range(len(path)) :
    print(path[i])
    models.append(load_model(filepath=path[i]))
    print(names[i]," done")

#Get predictions for test dataset for every model
for i in range(len(models)):
    predictions = models[i].predict(X_test)
    predictions = np.argmax(predictions,axis=-1)
    #Save accuracy
    d[names[i]] = accuracy_score(predictions, Y)

d = pd.DataFrame(d,index=["Accuracy"])
print(d)
#d.to_csv(path_csv)


from flask import Flask, request
import RPi.GPIO as GPIO
import time

app = Flask(__name__)

red_pin = 5
green_pin = 6
blue_pin = 13
ON = 0
OFF = 1  # for some reason relay is backwards, ON or 1 means OFF

GPIO.setmode(GPIO.BCM)
GPIO.setup(red_pin, GPIO.OUT)  # red pin, controls 1st relay
GPIO.setup(green_pin, GPIO.OUT)  # green pin, controls 4th relay (second relay appears broken)
GPIO.setup(blue_pin, GPIO.OUT)  # blue pin, controls 3rd relay

@app.route('/')
def test():
    print('started on')
    return 'Home Page of 8 channel relay control'

@app.route('/red', methods=['GET', 'POST'])
def red():
    print('turning lights red')
    if request.method == 'POST' or request.method == 'GET':
        GPIO.output(red_pin, ON)
        GPIO.output(green_pin, OFF)
        GPIO.output(blue_pin, OFF)
        print('done')
    return 'red'

@app.route('/green', methods=['GET', 'POST'])
def green():
    print('turning lights green')
    if request.method == 'POST' or request.method == 'GET':
        GPIO.output(red_pin, OFF)
        GPIO.output(green_pin, ON)
        GPIO.output(blue_pin, OFF)
        print('done')
    return 'green'

@app.route('/blue', methods=['GET', 'POST'])
def blue():
    print('turning lights blue')
    if request.method == 'POST' or request.method == 'GET':
        GPIO.output(red_pin, OFF)
        GPIO.output(green_pin, OFF)
        GPIO.output(blue_pin, ON)
        print('done')
    return 'blue'

@app.route('/white', methods=['GET', 'POST'])
def white():
    print('turning lights white')
    if request.method == 'POST' or request.method == 'GET':
        GPIO.output(red_pin, ON)
        GPIO.output(green_pin, ON)
        GPIO.output(blue_pin, ON)
        print('done')
    return 'white'

@app.route('/all_off', methods=['GET', 'POST'])
def all_off():
    print('turning lights off')
    if request.method == 'POST' or request.method == 'GET':
        GPIO.output(red_pin, OFF)
        GPIO.output(green_pin, OFF)
        GPIO.output(blue_pin, OFF)
        print('done')
    return 'off'

@app.route('/emergency_off', methods=['GET', 'POST'])
def emergency_off():
    print('program coming to an emergency stop')
    if request.method == 'POST' or request.method == 'GET':
        GPIO.output(red_pin, OFF)
        GPIO.output(green_pin, OFF)
        GPIO.output(blue_pin, OFF)
        GPIO.cleanup()
        print('GPIO pin have been cleaned')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)


import matplotlib.pyplot as plt

cluster_no = [3, 4, 5, 6]
time_jobs = [2.050669, 2.083345, 2.038026, 2.058638]
time_food = [0.102816, 0.100737, 0.100021, 0.101329]

plt.plot(cluster_no, time_jobs, color='g', label='Joburi')
plt.plot(cluster_no, time_food, color='c', label='Mâncare')

plt.xlabel("Număr de clustere")
plt.ylabel("Timpi de Execuție (s)")

plt.legend()
plt.show()