from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import time
import torch
import torch.utils.model_zoo as model_zoo
from torch.nn.parameter import Parameter
import numpy as np
from datetime import datetime
import pickle as pkl

# imports
from wsddn import WSDDN
from voc_dataset import *
import wandb
from utils import nms, tensor_to_PIL, compute_ap, get_box_data_caption
from PIL import Image, ImageDraw
from task_1 import AverageMeter, save_checkpoint
from mAP import calculate_map

os.environ['CUDA_LAUNCH_BLOCKING'] = '1'

# hyper-parameters
# ------------
start_step = 0
end_step = 20000
lr_decay_steps = 2 * 5000
lr_decay = 7. / 10
rand_seed = 1024

lr = 0.001
momentum = 0.9
weight_decay = 0.0005
# ------------

#------------
USE_WANDB = True
USE_WANDB_IMAGE = True
#------------

if rand_seed is not None:
    np.random.seed(rand_seed)

# load datasets and create dataloaders

# Not sure if the split terms are right. Need to take a look again.
train_dataset = VOCDataset(split='trainval', image_size=512, return_gt=True)
val_dataset = VOCDataset(split='test', image_size=512, return_gt=True)

train_loader = torch.utils.data.DataLoader(
    train_dataset,
    batch_size=1,   # batchsize is one for this implementation
    shuffle=False,
    num_workers=4,
    pin_memory=True,
    sampler=None,
    drop_last=True)

val_loader = torch.utils.data.DataLoader(
    val_dataset,
    batch_size=1,
    shuffle=False,
    num_workers=4,
    pin_memory=True,
    drop_last=True)

# Create network and initialize
net = WSDDN(classes=train_dataset.CLASS_NAMES)
print(net)

if os.path.exists('pretrained_alexnet.pkl'):
    pret_net = pkl.load(open('pretrained_alexnet.pkl', 'rb'))
else:
    pret_net = model_zoo.load_url(
        'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth')
    pkl.dump(pret_net, open('pretrained_alexnet.pkl', 'wb'),
             pkl.HIGHEST_PROTOCOL)
own_state = net.state_dict()

for name, param in pret_net.items():
    print(name)
    if name not in own_state:
        continue
    if isinstance(param, Parameter):
        param = param.data
    try:
        own_state[name].copy_(param)
        print('Copied {}'.format(name))
    except:
        print('Did not find {}'.format(name))
        continue

# Move model to GPU and set train mode
net.load_state_dict(own_state)
net.cuda()
net.train()

# TODO: Create optimizer for network parameters from conv2 onwards
# (do not optimize conv1)

optimizer = torch.optim.SGD(list(net.parameters())[1:],
                            lr=lr,
                            momentum=momentum,
                            weight_decay=weight_decay)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer,
                                            step_size=lr_decay_steps,
                                            gamma=lr_decay)

output_dir = "./task_2/"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# training
train_loss = 0
tp, tf, fg, bg = 0., 0., 0, 0
step_cnt = 0
re_cnt = False
disp_interval = 500
val_interval = 1500
n_epochs = 5

def test_net(model, val_loader=None, thresh=0.045):
    """
    tests the networks and visualize the detections
    thresh is the confidence threshold
    """

    batch_time = AverageMeter()
    data_time = AverageMeter()
    losses = AverageMeter()

    labels = []
    cls_probs = []

    end = time.time()

    all_bboxes = []
    all_scores = []
    all_classes = []
    all_gt_boxes = []
    all_gt_classes = []

    for i, data in enumerate(val_loader):

        # if i == 501:
        #   break

        data_time.update(time.time() - end)

        # one batch = data for one image
        image           = data['image'].cuda()
        target          = data['label'].cuda()
        wgt             = data['wgt'].cuda()
        rois            = data['rois'].cuda()
        gt_boxes        = data['gt_boxes']
        gt_class_list   = data['gt_classes']

        #TODO: perform forward pass, compute cls_probs
        cls_roi_probs = net(image, rois.float(), target).squeeze(0)

        class_bboxes_i = []
        class_scores_i = []
        classes_i = []

        # print(gt_class_list)
        # print(gt_boxes)

        # Abusing the fact that there's just a single image per batch.
        all_gt_boxes.append(torch.Tensor(gt_boxes))
        all_gt_classes.append(torch.Tensor(gt_class_list))

        # TODO: Iterate over each class (follow comments)
        for class_num in range(20):
            # get valid rois and cls_scores based on thresh
            # print(cls_roi_probs.shape)
            scores = cls_roi_probs[:, class_num]
            # print(scores.shape)
            bboxes = rois[0, scores > thresh]
            scores = scores[scores > thresh]

            # use NMS to get boxes and scores
            bboxes, scores = nms(bboxes, scores)

        # Everything on cpu.
        # bboxes (_type_): A (M, N, 4) tensor.
        # scores (_type_): A (M, N,) tensor.
        # preds : A (M, N) tensor indicating class.
        # gt_boxes (_type_): List of M (K_i, 4) tensors. Currently a 3d list
        # gt_classes : List of M (K_i,) tensors. Currently a 2d list.

            class_bboxes_i.extend(bboxes.cpu().detach().numpy().tolist())
            class_scores_i.extend(scores.cpu().detach().numpy().tolist())
            classes_i.extend((np.ones_like(scores.cpu().detach().numpy()) * \
                class_num).astype(np.int).tolist())

        all_bboxes.append(torch.Tensor(class_bboxes_i))
        all_scores.append(torch.Tensor(class_scores_i))
        all_classes.append(torch.Tensor(classes_i))

        if i in images_to_plot and USE_WANDB_IMAGE:
            rois_image = wandb.Image(image.cpu().detach(),
                                     boxes={
                                        "predictions": {
                                            "box_data": get_box_data_caption(classes_i,
                                                                             class_bboxes_i,
                                                                             class_scores_i,
                                                                             val_dataset.CLASS_NAMES),
                                            "class_labels": class_id_to_label,
                                        },
                                      })
            wandb.log({f"val/Bounding Boxes_{i}": rois_image})

        batch_time.update(time.time() - end)
        losses.update(net.loss.item())
        end = time.time()

        cls_probs.append(torch.sigmoid(torch.sum(cls_roi_probs, dim=0)).cpu().detach())
        labels.append(target.squeeze(0).cpu().detach())

        if i % disp_interval == 0:
            print('Test: [{0}/{1}]\t'
                  'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                  'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'.format(
                      i,
                      len(train_loader),
                      batch_time=batch_time,
                      data_time=data_time,))

        del data, target, image, rois, gt_boxes, gt_class_list, bboxes, scores

    #TODO: visualize bounding box predictions when required
    #TODO: Calculate mAP on test set

    return calculate_map(all_bboxes,
                         all_scores,
                         all_classes,
                         all_gt_boxes,
                         all_gt_classes)

batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()

class_id_to_label = dict(enumerate(train_dataset.CLASS_NAMES))

if USE_WANDB:
    wandb.init(project='vlr-hw2')
    wandb.watch(net, log_freq=2000)
    wandb.define_metric("train/step")
    wandb.define_metric("train/*", step_metric="train/step")

    # wandb.define_metric("val/step")
    # wandb.define_metric("val/*", step_metric="val/step")

images_to_plot = [0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500]

for epoch in range(n_epochs):

    end = time.time()

    for i, data in enumerate(train_loader):

        data_time.update(time.time() - end)

        #TODO: get one batch and perform forward pass
        # one batch = data for one image
        image           = data['image'].cuda()
        target          = data['label'].cuda()
        wgt             = data['wgt'].cuda()
        rois            = data['rois'].cuda()
        gt_boxes        = data['gt_boxes']
        gt_class_list   = data['gt_classes']

        #TODO: perform forward pass - take care that proposal values should be in pixels for the fwd pass
        # also convert inputs to cuda if training on GPU

        out = net(image, rois.float(), target)

        # backward pass and update
        loss = net.loss
        train_loss += loss.item()
        step_cnt += 1

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        batch_time.update(time.time() - end)
        losses.update(loss.item())
        end = time.time()

        if i % disp_interval == 0:

            print('Epoch: [{0}][{1}/{2}]\t'
                  'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                  'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
                  'Loss {loss.val:.4f} ({loss.avg:.4f})\t'.format(
                      epoch,
                      i,
                      len(train_loader),
                      batch_time=batch_time,
                      data_time=data_time,
                      loss=losses,))

            # net.eval()
            # map, aps = test_net(net, val_loader)
            # print("AP ", aps)
            # print("mAP", map)
            # net.train()

            if USE_WANDB:
                wandb.log({'train/step': epoch * len(train_loader) + i})
                wandb.log({'train/loss_avg': losses.avg})
                wandb.log({'train/loss_val': losses.val})
                wandb.log({'train/LR': optimizer.param_groups[0]['lr']})

        if i in images_to_plot and USE_WANDB_IMAGE:

            conf_thresh = 0.045

            class_probs = torch.sigmoid(torch.sum(out, dim=0))

            class_bboxes = []
            class_scores = []
            classes = []

            # TODO: Iterate over each class (follow comments)
            for class_num in range(20):
                # get valid rois and cls_scores based on thresh
                scores_i = out[:, class_num]
                # print(scores.shape)
                bboxes_i = rois[0, scores_i > conf_thresh]
                scores_i = scores_i[scores_i > conf_thresh]

                # use NMS to get boxes and scores
                bboxes_i, scores_i = nms(bboxes_i, scores_i)

                class_bboxes.extend(bboxes_i.cpu().detach().numpy().tolist())
                class_scores.extend(scores_i.cpu().detach().numpy().tolist())
                classes.extend((np.ones_like(scores_i.cpu().detach().numpy()) * \
                    class_num).astype(np.int).tolist())

            rois_image = wandb.Image(image.cpu().detach(),
                                     boxes={
                                        "predictions": {
                                            "box_data": get_box_data_caption(classes,
                                                                             class_bboxes,
                                                                             class_scores,
                                                                             train_dataset.CLASS_NAMES),
                                            "class_labels": class_id_to_label,
                                        },
                                     })

            wandb.log({f"train/Bounding Boxes_{i}": rois_image})

    net.eval()
    map, aps = test_net(net, val_loader)
    print("AP ", aps)
    print("mAP", map)
    net.train()

    classes = list(range(0, 20, 2))

    if USE_WANDB:

        wandb.log({'val/map': map})

        for i in classes:
            wandb.log({f'val/ap_{i}_{VOCDataset.CLASS_NAMES[i]}': aps[i]})

        #TODO: Perform all visualizations here
        #The intervals for different things are defined in the handout

save_checkpoint({
        'epoch': n_epochs,
        'state_dict': net.state_dict(),
        'optimizer': optimizer.state_dict(),
    },
    True)


SIZE = int(input("Please enter the size of the matrix to be added: "))
board1 = []
board2 = []
result_board = []

for y in range(SIZE):
        board1.append([])
        for x in range(SIZE):
                user_num = input(f'Please enter input for [{y}][{x}] on matrix 1: ')
                board1[y].append(user_num)

for row in board1:
        for column in row:
                print(f'{column}  ', end="")
        print("\n")

for y in range(SIZE):
        board2.append([])
        for x in range(SIZE):
                user_num = input(f'Please enter input for [{y}][{x}] on matrix 2: ')
                board2[y].append(user_num)

for row in board2:
        for column in row:
                print(f'{column}  ', end="")
        print("\n")

for y in range(SIZE):
        result_board.append([])
        for x in range(SIZE):
                new_sum = int(board1[x][y]) + int(board2[x][y])
                result_board[y].append(new_sum)

print("The result is sum between the two matrix are: \n")
for row in result_board:
        for column in row:
                print(f'{column}  ', end="")
        print("\n")


import linecache as li
import re
import numpy
import catch as ca

def cellparameters(file):
    with open(file) as f:
        line = f.readlines()
        for i in range(0,len(line)):
            if re.findall('Begin ', line[i]):
                b=i+4
    return b

def inputcellparameters(file):
    with open(file) as f:
        line = f.readlines()
        for i in range(0,len(line)):
            if re.findall('CELL_PARAMETERS',line[i]):
                c=i
    return c

def nat(file):
    with open(file) as f:
        line= f.readlines()
        for i in range(0,len(line)):
            if re.findall('nat',line[i]):
                c=i
                count=line[i]
                a=count.split()
                b=a[2]
    return b

def ntype(file):
    with open(file) as f:
        line= f.readlines()
        for i in range(0,len(line)):
            if re.findall('ntyp',line[i]):
                c=i
                count=line[i]
                a=count.split()
                bbb=a[2]
    return bbb

def kp(file):
    with open(file) as f:
        line= f.readlines()
        for i in range(0,len(line)):
            if re.findall('K_POINTS',line[i]):
                count = line[i+1]
                x=count.split()
                a=int(x[0])
                b=int(x[1])
                c=int(x[2])
    return a,b,c

def pp(file):
    with open(file) as f:
        line= f.readlines()
        for i in range(0,len(line)):
            if re.findall('pseudo_dir',line[i]):
                c=i
    return c

def calculation(file):
    with open(file) as f:
        line=f.readlines()
        for i in range(0,len(line)):
            if re.findall('calculation', line[i]):
                c=i
    return c

def create_scfin(vcin,vcout,targetin):
    a=cellparameters(vcout)
    calline=calculation(vcin)
    numberat=int(nat(vcin))
    numbertype=int(ntype(vcin))
    b=inputcellparameters(vcin)
    ppdir=pp(vcin)
    with open(vcout) as vcsout:
        vc_out=vcsout.readlines()

    with open('vclocation') as hahaha:
        lineline=hahaha.readlines()
        scfkphangshu=ca.scfkp('vclocation')
    with open(vcin) as vcsin:
        line=vcsin.readlines()
        line[b-2]=lineline[scfkphangshu]+'\n'
        line[calline]='    calculation = "scf"\n'
        for n in range(b,b+4):
            line[n]=vc_out[a]
            a=a+1
        for x in range(b+7+numbertype,b+8+numbertype+numberat):
            line[x]=vc_out[a+1]
            a=a+1

    with open(targetin,'w') as scfin:
        for i in range(0,len(line)):
            scfin.write(line[i])


# Пользователь с клавиатуры вводит значения в список.
# После чего запускаются две потока.
# Первый поток находит максимум в списке.
# Второй поток находит минимум в списке.
# Результаты вычислений выводятся на экран.

import threading

# any_numbers = list(int(input()))
# print(any_numbers)

# def get_max(args):
#     print(f"Max = {max(args)}")

# def get_min(args):
#     print(f"Min = {min(args)}")

# th1 = threading.Thread(target=get_max, args=any_numbers).start()
# th2 = threading.Thread(target=get_min, args=any_numbers).start()

# print(th1)
# print(th2)

# Пользователь с клавиатуры вводит значения в список.
# После чего запускаются две потока.
# Первый поток находит сумму элементов в списке.
# Второй поток находит среднеарифметическое в списке.
# Результаты вычислений выводятся на экран.

# while True:
#     numbers = input("Введите числа через пробел: ")

#     try:
#         numbers = list(map(int, numbers.split()))
#     except ValueError:
#         print("Произошла ошибка!")
#         continue

#     break

# def get_sum(numbers):
#     print(f"Sum = {sum(numbers)}")

# def get_avg(numbers):
#     print(f"Avg = {sum(numbers) / len(numbers)}")

# th1 = threading.Thread(target=get_sum, args=(numbers, )).start()
# th2 = threading.Thread(target=get_avg, args=(numbers, )).start()

# print(th1)
# print(th2)

# Пользователь с клавиатуры вводит путь к файлу,
# содержащему набор чисел. После чего запускаются две потока.
# Первый поток создает новый файл,
# в который запишет только четные элементы списка.
# Второй поток создает новый файл,
# в который запишет только нечетные элементы списка.
# Количество четных и нечетных элементов выводится на экран.

path = input()

def get_file(path):
    with open(path, "r") as file:
        data = file.read()
    return [int(i) for i in data.split(", ")]

def even():
    data = get_file(path)

    with open("even_numbers.txt", "w") as file:
        num = [i for i in data if i % 2 == 0]
        file.write(str(num))
        print(f"Even numbers len: {len(num)}")

def odd():
    data = get_file(path)

    with open("odd_numbers.txt", "w") as file:
        num = [i for i in data if i % 2 != 0]
        file.write(str(num))
        print(f"Odd numbers len: {len(num)}")

th1 = threading.Thread(target=even)
th2 = threading.Thread(target=odd)
th1.start()
th2.start()


#
# @lc app=leetcode id=1519 lang=python3
#
# [1519] Number of Nodes in the Sub-Tree With the Same Label
#

# @lc code=start
class Solution:
    def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
        c = defaultdict(int)
        graph = defaultdict(list)

        ans = [0] * n
        for x, y in edges:
            graph[x].append(y)
            graph[y].append(x)

        def dfs(node, parent):
            lc = c[labels[node]]
            for neighbor in graph[node]:
                if neighbor != parent:
                    dfs(neighbor, node)
            c[labels[node]] += 1
            ans[node] = c[labels[node]] - lc

        dfs(0, -1)
        return ans

# @lc code=end


import os
import json
import random

import requests

IS_FETCH_REQUIRED = os.getenv("IS_FETCH_REQUIRED", False)
QUESTIONS_URL = os.getenv("QUESTIONS_URL")

SUBJECT_UKR = "ukr"
SUBJECT_MATH = "math"
SUBJECT_HIS = "his"
SUBJECT_GEO = "geo"
SUBJECT_BIO = "bio"
SUBJECT_PHYS = "phys"
SUBJECT_CHEM = "chem"
SUPPORTED_SUBJECTS_CODES = [
    SUBJECT_UKR,
    SUBJECT_MATH,
    SUBJECT_HIS,
    SUBJECT_GEO,
    SUBJECT_BIO,
    SUBJECT_PHYS,
    SUBJECT_CHEM,
]

class QuestionNotFoundError(Exception):
    """Custom exception should be raised when question with given id is not found."""

    pass

class QuestionsService:
    """Class designed for questions manipulations: load, check answers, etc."""

    @staticmethod
    def load_questions():
        if not IS_FETCH_REQUIRED:
            with open("questions.json", "r") as f:
                return json.loads(f.read())

        response = requests.get(QUESTIONS_URL)
        return json.loads(response.content)

    @staticmethod
    def load_random_question(subject=SUBJECT_UKR):
        question_id = random.choice(QUESTIONS[subject])
        question_data = QUESTIONS_MAP[question_id]
        return question_data

    @staticmethod
    def load_question_by_id(q_id):
        try:
            return QUESTIONS_MAP[int(q_id)]
        except (KeyError, ValueError):
            raise QuestionNotFoundError

    @staticmethod
    def check_answers(question, user_choices):
        correct_choices = [
            choice["id"] for choice in question["choices"] if choice["is_correct"]
        ]
        return sorted(correct_choices) == sorted(user_choices)

QUESTIONS_FROM_SERVER = QuestionsService.load_questions()

QUESTIONS = {}
QUESTIONS_MAP = {}

for code in SUPPORTED_SUBJECTS_CODES:
    QUESTIONS[code] = [q["id"] for q in QUESTIONS_FROM_SERVER if q["subject"] == code]

QUESTIONS_MAP = {q["id"]: q for q in QUESTIONS_FROM_SERVER}


# -*- coding: utf-8 -*-
"""
A routing layer for the onboarding bot tutorial built using
[Slack's Events API](https://api.slack.com/events-api) in Python
"""
import os
import requests
import jinja2
import jinja2_sanic
from sanic import Sanic
from sanic.response import json, text

from bot import pyBot
from handler import event_handler

app = Sanic()

jinja2_sanic.setup(
    app,
    loader=jinja2.FileSystemLoader(searchpath="templates")
)

@app.listener('before_server_start')
async def start(app, loop):
    users = requests.get("https://slack.com/api/users.list", params={"token": os.environ.get("SLACK_BOT_TOKEN")}).json()
    if "members" in users:
        app.users = {member.pop("id"): member for member in users.get("members", [])}

@app.route("/")
async def test(request):
    return json({"hello": "world"})

@app.route("/stats", methods=["POST"])
def stats(request):
    return

@app.route("/moveuser", methods=["POST"])
def moveuser(request):
    form = request.form
    username = form.get("user_name")
    return json({"hello": "world"})

@app.route("/ban", methods=["POST"])
def moveuser(request):
    form = request.form
    return json({"hello": "world"})

@app.route("/install", methods=["GET"])
async def pre_install(request):
    """This route renders the installation page with 'Add to Slack' button."""
    # Since we've set the client ID and scope on our Bot object, we can change
    # them more easily while we're developing our app.
    client_id = pyBot.oauth["client_id"]
    scope = pyBot.oauth["scope"]
    # Our template is using the Jinja templating language to dynamically pass
    # our client id and scope
    return jinja2_sanic.render_template("install.html", request, dict(client_id=client_id, scope=scope))

@app.route("/thanks", methods=["GET", "POST"])
async def thanks(request):
    """
    This route is called by Slack after the user installs our app. It will
    exchange the temporary authorization code Slack sends for an OAuth token
    which we'll save on the bot object to use later.
    To let the user know what's happened it will also render a thank you page.
    """
    # Let's grab that temporary authorization code Slack's sent us from
    # the request's parameters.
    code_arg = request.args.get('code')
    # The bot's auth method to handles exchanging the code for an OAuth token
    pyBot.auth(code_arg)
    return jinja2_sanic.render_template("thanks.html", request, {})

@app.route("/listening", methods=["GET", "POST"])
async def hears(request):
    """
    This route listens for incoming events from Slack and uses the event
    handler helper function to route events to our Bot.
    """
    slack_event = request.json

    # ============= Slack URL Verification ============ #
    # In order to verify the url of our endpoint, Slack will send a challenge
    # token in a request and check for this token in the response our endpoint
    # sends back.
    #       For more info: https://api.slack.com/events/url_verification
    if "challenge" in slack_event:
        return json(slack_event["challenge"], 200)

    # ============ Slack Token Verification =========== #
    # We can verify the request is coming from Slack by checking that the
    # verification token in the request matches our app's settings
    if pyBot.verification != slack_event.get("token"):
        message = "Invalid Slack verification token: %s \npyBot has: \
                   %s\n\n" % (slack_event["token"], pyBot.verification)
        # By adding "X-Slack-No-Retry" : 1 to our response headers, we turn off
        # Slack's automatic retries during development.
        text(message, 403, {"X-Slack-No-Retry": 1})

    # ====== Process Incoming Events from Slack ======= #
    # If the incoming request is an Event we've subscribed to
    if "event" in slack_event:
        event_type = slack_event["event"]["type"]
        # Then handle the event by event_type and have your bot respond
        return event_handler(request, event_type, slack_event)
    # If our bot hears things that are not events we've subscribed to,
    # send a quirky but helpful error response
    return text("[NO EVENT IN SLACK REQUEST] These are not the droids\
                         you're looking for.", 404, {"X-Slack-No-Retry": 1})

if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=int(os.environ.get('PORT', 8000)),
        workers=int(os.environ.get('WEB_CONCURRENCY', 1)),
        debug=bool(os.environ.get('DEBUG', ''))
    )


import cs50
from array import array
print("Number: ", end="")
number = cs50.get_int()
digits = array('i')
n = number
x = number
counter = 0
c = 0
s = 0
z = 1
while n > 0:
    n = n // 10
    counter += 1
# print(counter)
for i in range(counter):
    z *= 10
z /= 10
# print(z)
v = number
v = v // z
# print(v)
if v == 3:
    stat = 1
elif v == 5:
    stat = 2
elif v == 4:
    stat = 3
else:
    stat = 4
# print(stat)
while c < counter // 2:
    temp = ((x % 100) // 10) * 2
    # print(temp)
    if temp // 10 > 0:
        digits.append(temp // 10)
        # print(temp//10)
        digits.append(temp % 10)
        # print(temp%10)
    else:
        digits.append(temp)
    x = x // 100
    # print(x)
    c += 1
    # print(c)
for n in digits:
    s += n
c = 0
if counter % 2 == 1:
    a = counter // 2 + 1
else:
    a = counter // 2
d = array('i')
while c < a:
    temp = number % 10
    d.append(temp)
    number = number // 100
    c += 1
for n in d:
    s += n
# print(s)
if s % 10 == 0:
    # print(1)
    if stat == 1:
        print("AMEX")
    elif stat == 2:
        print("MASTERCARD")
    elif stat == 3:
        print("VISA")
    else:
        print("INVALID")
else:
    #print (2)
    print("INVALID")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Разработайте аналог утилиты tree в Linux. Используйте возможности модуля argparse для
управления отображением дерева каталогов файловой системы. Добавьте дополнительные
уникальные возможности в данный программный продукт.
"""

import argparse
import pathlib
import collections
from colorama import Fore
from datetime import datetime

def tree(directory):
    print(Fore.RED + f'/ {directory}')
    for path in sorted(directory.rglob('*')):
        depth = len(path.relative_to(directory).parts)
        spacer = ' ' * depth
        if path.suffix == ".exe":
            print(Fore.BLUE + f'{spacer} ++ {path.name}')
        if path.suffix == ".py":
            print(Fore.LIGHTGREEN_EX + f'{spacer} ++ {path.name}')
        if path.suffix == (".txt" or ".html"):
            print(Fore.WHITE + f'{spacer} ++ {path.name}')
        if path.suffix == ".docx":
            print(Fore.RED + f'{spacer} ++ {path.name}')
        if path.suffix == ".dll":
            print(Fore.CYAN + f'{spacer} ++ {path.name}')
        if path.suffix == ".lib":
            print(Fore.MAGENTA + f'{spacer} ++ {path.name}')
        if path.suffix == ".pdf":
            print(Fore.GREEN + f'{spacer} ++ {path.name}')
        if path.suffix == "":
            print(Fore.LIGHTYELLOW_EX + f'{spacer} / {path.name}')

def main(command_line=None):

    # Создать основной парсер командной строки.

    parser = argparse.ArgumentParser()
    parser.add_argument('tree', action="store", help='Main command')
    parser.add_argument('-c', '--command', action="store", help='additional command')
    parser.add_argument('-t', '--type', action="store", help='search type of file')
    args = parser.parse_args()
    if args.command == "curr":
        print(tree(pathlib.Path.cwd()))
    if args.command == "home":
        print(tree(pathlib.Path.home()))
    if args.command == "count":
        print(collections.Counter(p.suffix for p in pathlib.Path.cwd().iterdir()))
    if args.command == "type":
        print(collections.Counter(p.suffix for p in pathlib.Path.cwd().glob(f'*.{args.type}*')))
    if args.command == "last":
        time, file_path = max((f.stat().st_mtime, f) for f in pathlib.Path.cwd().iterdir())
        print(datetime.fromtimestamp(time), file_path)

if __name__ == '__main__':
    main()


import operator
from collections import deque
from functools import reduce

class Monkey:
    monkeys = []
    common_divider = 1
    worry_level_divider = 1

    def __init__(self, items, sign, operation_arg, test, test_results):
        self.index = len(Monkey.monkeys)
        self.items = deque(items)
        self.operator = sign
        self.operation_arg = operation_arg
        self.test = test
        self.test_results = test_results
        self.inspected = 0
        Monkey.monkeys.append(self)

    def __add__(self, other):
        self.items.append(other % Monkey.common_divider)
        return self

    def __repr__(self):
        return f'< Monkey {self.index}: items {self.items}, inspected {self.inspected} >'

    def inspect(self):
        for i in range(len(self.items)):
            self.inspected += 1
            cur = self.items.popleft()

            arg = cur
            if self.operation_arg is not None:
                arg = self.operation_arg

            if self.operator == '*':
                cur *= arg
            else:
                cur += arg

            cur //= Monkey.worry_level_divider
            Monkey.monkeys[self.test_results[cur % self.test == 0]] += cur

    @classmethod
    def round(cls):
        for monkey in cls.monkeys:
            monkey.inspect()

    @classmethod
    def calc_dividers(cls, value=1):
        cls.worry_level_divider = value
        cls.common_divider = reduce(operator.mul, map(lambda monkey: monkey.test, cls.monkeys))

    @staticmethod
    def parse(inp):
        Monkey.monkeys.clear()
        cur_ind = 0
        while cur_ind < len(inp):
            items = map(int, inp[cur_ind + 1].split(':')[1].strip().split(','))
            expression = inp[cur_ind + 2].split('=')[1].strip().split()
            assert expression[0] == 'old'
            sign = expression[1]
            operation_arg = int(expression[2]) if expression[2].isnumeric() else None

            test = int(inp[cur_ind + 3].split()[-1])
            test_results = {
                True: int(inp[cur_ind + 4].split()[-1]),
                False: int(inp[cur_ind + 5].split()[-1])
            }

            Monkey(items, sign, operation_arg, test, test_results)
            cur_ind += 7

def part_one(inp):
    Monkey.parse(inp)
    Monkey.calc_dividers(3)
    for i in range(20):
        Monkey.round()

    inspected = list(sorted(map(lambda monkey: monkey.inspected, Monkey.monkeys), reverse=True))
    return inspected[0] * inspected[1]

def part_two(inp):
    Monkey.parse(inp)
    Monkey.calc_dividers()
    for i in range(10000):
        Monkey.round()

    inspected = list(sorted(map(lambda monkey: monkey.inspected, Monkey.monkeys), reverse=True))
    return inspected[0] * inspected[1]

def main():
    with open(r'd11_input.txt') as fin:
        inp = fin.read().splitlines()

    print(part_one(inp))
    print(part_two(inp))

if __name__ == '__main__':
    main()


import os
import numpy as np
from PIL import Image

def crop_abilities(path_screens:str, path_out:str, select_ability_new_ui=True):
    if not os.path.exists(path_out): os.makedirs(path_out)
    #if both exists
    w, h = 1080, 1920

    if select_ability_new_ui:
        sw, sh = 195, 195
        y1 = 810
        x1, x2, x3 = 105, 441, 777
    else:
        sw, sh = 239, 239
        y1 = 1157
        x1, x2, x3 = 90, 420, 750

    c1 = (x1, y1, x1+sw, y1+sh)
    c2 = (x2, y1, x2+sw, y1+sh)
    c3 = (x3, y1, x3+sw, y1+sh)

    c = 66
    for fn in os.listdir(path_screens):
        path = os.path.join(path_screens, fn)
        with Image.open(path) as im:
            #img_np = np.array(img.getdata())
            cr1 = im.crop(c1)
            cr1.save(os.path.join(path_out, "ability_{}.png".format(c)), 'PNG')
            c+=1
            cr2 = im.crop(c2)
            cr2.save(os.path.join(path_out, "ability_{}.png".format(c)), 'PNG')
            c += 1
            cr3 = im.crop(c3)
            cr3.save(os.path.join(path_out, "ability_{}.png".format(c)), 'PNG')
            c += 1

if __name__ == '__main__':
    crop_abilities(path_screens='..\\datas\\1080x1920\\abilities_sc', path_out='..\\datas\\1080x1920\\abilities_new',
                   select_ability_new_ui=True)


import pytest

from vakt.rules.logic import *
from vakt.rules.base import Rule
from vakt.rules.operator import Greater, Less, Eq
from vakt.rules.inquiry import ActionEqual
from vakt.rules.list import In
from vakt.guard import Inquiry

@pytest.mark.parametrize('against, result', [
    ('', False),
    ('a', True),
    ([], False),
    ([1], True),
    (0, False),
    (1, True),
    (None, False),
    (1 < 90, True),
    (1 > 90, False),
    (lambda: True, True),
    (lambda: False, False),
])
def test_truthy_satisfied(against, result):
    assert result == Truthy().satisfied(against)
    # test after (de)serialization
    jsn = Truthy().to_json()
    assert result == Rule.from_json(jsn).satisfied(against)

@pytest.mark.parametrize('against, result', [
    ('', True),
    ('a', False),
    ([], True),
    ([1], False),
    (0, True),
    (1, False),
    (None, True),
    (1 < 90, False),
    (1 > 90, True),
    (lambda: True, False),
    (lambda: False, True),
])
def test_falsy_satisfied(against, result):
    assert result == Falsy().satisfied(against)
    # test after (de)serialization
    jsn = Falsy().to_json()
    assert result == Rule.from_json(jsn).satisfied(against)

def test_and_or_rules_bad_args():
    expected_msg = "Arguments should be of Rule class or it's derivatives"
    with pytest.raises(TypeError) as excinfo:
        And(Inquiry())
    assert expected_msg in str(excinfo.value)
    with pytest.raises(TypeError) as excinfo:
        Or(Inquiry(), 123)
    assert expected_msg in str(excinfo.value)

@pytest.mark.parametrize('rules, what, inquiry, result', [
    ([], 1, None, False),
    ([Greater(-1)], 1, None, True),
    ([Greater(55)], 1, None, False),
    ([Greater(-1), Less(10)], 1, None, True),
    ([Greater(-1), Less(10), Eq(700)], 1, None, False),
    ([Eq('read'), In('read', 'write'), ActionEqual()], 'read', Inquiry(action='read'), True),
    ([Eq('read'), In('write'), ActionEqual()], 'read', Inquiry(action='read'), False),
])
def test_and_rule(rules, what, inquiry, result):
    r = And(*rules)
    assert result == r.satisfied(what, inquiry)
    # test after (de)serialization
    assert result == Rule.from_json(And(*rules).to_json()).satisfied(what, inquiry)

@pytest.mark.parametrize('rules, what, inquiry, result', [
    ([], 1, None, False),
    ([Greater(-1)], 1, None, True),
    ([Greater(55)], 1, None, False),
    ([Greater(-1), Less(10)], 1, None, True),
    ([Less(10), Eq(700)], 1, None, True),
    ([Eq(700), Less(10)], 1, None, True),
    ([Eq('read'), In('read', 'write'), ActionEqual()], 'read', Inquiry(action='read'), True),
    ([Eq('read'), In('write'), ActionEqual()], 'read', Inquiry(action='read'), True),
])
def test_or_rule(rules, what, inquiry, result):
    r = Or(*rules)
    assert result == r.satisfied(what, inquiry)
    # test after (de)serialization
    assert result == Rule.from_json(Or(*rules).to_json()).satisfied(what, inquiry)

def test_or_rule_uses_short_circuit_but_and_rule_does_not():
    x = []
    def get_inc(x):
        def inc():
            x.append(1)
            return True
        return inc
    f = get_inc(x)
    rules = [
        Eq(f),
        Truthy()
    ]
    # test Or
    r = Or(*rules)
    assert r.satisfied(f, None)
    assert r.satisfied(f, None)
    assert 0 == len(x)
    # test And
    r = And(*rules)
    assert r.satisfied(f, None)
    assert 1 == len(x)
    assert r.satisfied(f, None)
    assert 2 == len(x)

def test_not_rule_bad_args():
    expected_msg = "Arguments should be of Rule class or it's derivatives"
    with pytest.raises(TypeError) as excinfo:
        Not(123)
    assert expected_msg in str(excinfo.value)
    with pytest.raises(TypeError) as excinfo:
        Not([Greater(-1)])
    assert expected_msg in str(excinfo.value)

@pytest.mark.parametrize('rule, what, inquiry, result', [
    (Greater(-1), 1, None, False),
    (Greater(55), 1, None, True),
    (Less(10), 1, None, False),
    (Eq(10), 10, None, False),
    (Eq(10), 11, None, True),
    (ActionEqual(), 'read', Inquiry(action='read'), False),
    (ActionEqual(), 'write', Inquiry(action='read'), True),
])
def test_not_rule(rule, what, inquiry, result):
    r = Not(rule)
    assert result == r.satisfied(what, inquiry)
    # test after (de)serialization
    assert result == Rule.from_json(Not(rule).to_json()).satisfied(what, inquiry)

@pytest.mark.parametrize('what', [
    1,
    'str',
    9.0,
    False,
    True,
])
def test_any_and_neither_rules(what):
    assert Any().satisfied(what)
    assert not Neither().satisfied(what)
    # test after (de)serialization
    assert Rule.from_json(Any().to_json()).satisfied(what)
    assert not Rule.from_json(Neither().to_json()).satisfied(what)


from captum.attr import GuidedGradCam, LayerAttribution, LayerGradCam, Occlusion
from captum.attr import visualization as viz
from einops import rearrange

from deepdrive_course.utils import torch_normalize_img

def visualize_attributions(attributions, img):
    img_normalized = torch_normalize_img(img)
    img_normalized_np = rearrange(img_normalized, "c h w -> h w c").numpy()
    attributions_np = rearrange(attributions, "1 c h w -> h w c").detach().cpu().numpy()

    return viz.visualize_image_attr_multiple(
        attributions_np,
        img_normalized_np,
        methods=["original_image", "heat_map", "blended_heat_map", "heat_map", "blended_heat_map"],
        signs=["all", "positive", "positive", "negative", "negative"],
        titles=["Original", "Positive heatmap", "Positive blended", "Negative heatmap", "Negative blended"],
        use_pyplot=False,
        fig_size=(10, 3.5),
    )

def gradcam_analysis(img, label, model, layer):
    img = img.clone()
    gradcam = LayerGradCam(model, layer)
    attributions = gradcam.attribute(img.unsqueeze(0), label)
    upsampled_attributions = LayerAttribution.interpolate(attributions, img.shape[1:3])

    return visualize_attributions(upsampled_attributions, img)

def guided_gradcam_analysis(img, label, model, layer):
    img = img.clone()
    guided_gradcam = GuidedGradCam(model, layer)
    attributions = guided_gradcam.attribute(img.unsqueeze(0), label)

    return visualize_attributions(attributions, img)

def occlusion_analysis(img, label, model, window=(3, 3, 3), strides=(3, 1, 1)):
    img = img.clone()
    ablator = Occlusion(model)
    attributions = ablator.attribute(img.unsqueeze(0), target=label, sliding_window_shapes=window, strides=strides)

    return visualize_attributions(attributions, img)


import os
import random
# customized
import sys
from typing import NamedTuple, Sequence

import cv2
import numpy as np
import torch
from PIL import Image
from pytorch3d.io import save_obj
from pytorch3d.ops import interpolate_face_attributes
from pytorch3d.renderer import (AmbientLights, MeshRasterizer,
                                MeshRendererWithFragments,
                                RasterizationSettings, SoftPhongShader,
                                TexturesUV)
from pytorch3d.renderer.mesh.shader import ShaderBase
from torchvision import transforms
from tqdm import tqdm

from modelscope.models.cv.text_texture_generation.lib2.camera import \
    init_camera
from modelscope.models.cv.text_texture_generation.lib2.init_view import *
from modelscope.models.cv.text_texture_generation.lib2.viusel import (
    visualize_outputs, visualize_quad_mask)

sys.path.append('.')

class BlendParams(NamedTuple):
    sigma: float = 1e-4
    gamma: float = 1e-4
    background_color: Sequence = (1, 1, 1)

class FlatTexelShader(ShaderBase):

    def __init__(self,
                 device='cpu',
                 cameras=None,
                 lights=None,
                 materials=None,
                 blend_params=None):
        super().__init__(device, cameras, lights, materials, blend_params)

    def forward(self, fragments, meshes, **_kwargs):
        texels = meshes.sample_textures(fragments)
        texels[(fragments.pix_to_face == -1), :] = 0
        return texels.squeeze(-2)

def init_soft_phong_shader(camera, blend_params, device):
    lights = AmbientLights(device=device)
    shader = SoftPhongShader(
        cameras=camera,
        lights=lights,
        device=device,
        blend_params=blend_params)

    return shader

def init_flat_texel_shader(camera, device):
    shader = FlatTexelShader(cameras=camera, device=device)
    return shader

def init_renderer(camera, shader, image_size, faces_per_pixel):
    raster_settings = RasterizationSettings(
        image_size=image_size, faces_per_pixel=faces_per_pixel)
    renderer = MeshRendererWithFragments(
        rasterizer=MeshRasterizer(
            cameras=camera, raster_settings=raster_settings),
        shader=shader)

    return renderer

@torch.no_grad()
def render(mesh, renderer, pad_value=10):

    def phong_normal_shading(meshes, fragments) -> torch.Tensor:
        faces = meshes.faces_packed()  # (F, 3)
        vertex_normals = meshes.verts_normals_packed()  # (V, 3)
        faces_normals = vertex_normals[faces]
        pixel_normals = interpolate_face_attributes(fragments.pix_to_face,
                                                    fragments.bary_coords,
                                                    faces_normals)

        return pixel_normals

    def similarity_shading(meshes, fragments):
        faces = meshes.faces_packed()  # (F, 3)
        vertex_normals = meshes.verts_normals_packed()  # (V, 3)
        faces_normals = vertex_normals[faces]
        vertices = meshes.verts_packed()  # (V, 3)
        face_positions = vertices[faces]
        view_directions = torch.nn.functional.normalize(
            (renderer.shader.cameras.get_camera_center().reshape(1, 1, 3)
             - face_positions),
            p=2,
            dim=2)
        cosine_similarity = torch.nn.CosineSimilarity(dim=2)(faces_normals,
                                                             view_directions)
        pixel_similarity = interpolate_face_attributes(
            fragments.pix_to_face, fragments.bary_coords,
            cosine_similarity.unsqueeze(-1))

        return pixel_similarity

    def get_relative_depth_map(fragments, pad_value=pad_value):
        absolute_depth = fragments.zbuf[..., 0]  # B, H, W
        no_depth = -1

        depth_min, depth_max = absolute_depth[absolute_depth != no_depth].min(
        ), absolute_depth[absolute_depth != no_depth].max()
        target_min, target_max = 50, 255

        depth_value = absolute_depth[absolute_depth != no_depth]
        depth_value = depth_max - depth_value  # reverse values

        depth_value /= (depth_max - depth_min)
        depth_value = depth_value * (target_max - target_min) + target_min

        relative_depth = absolute_depth.clone()
        relative_depth[absolute_depth != no_depth] = depth_value
        relative_depth[absolute_depth == no_depth] = pad_value

        return relative_depth

    images, fragments = renderer(mesh)
    normal_maps = phong_normal_shading(mesh, fragments).squeeze(-2)
    similarity_maps = similarity_shading(mesh, fragments).squeeze(-2)  # -1 - 1
    depth_maps = get_relative_depth_map(fragments)

    # normalize similarity mask to 0 - 1
    similarity_maps = torch.abs(similarity_maps)  # 0 - 1

    # HACK erode, eliminate isolated dots
    non_zero_similarity = (similarity_maps > 0).float()
    non_zero_similarity = (non_zero_similarity * 255.).cpu().numpy().astype(
        np.uint8)[0]
    non_zero_similarity = cv2.erode(
        non_zero_similarity, kernel=np.ones((3, 3), np.uint8), iterations=2)
    non_zero_similarity = torch.from_numpy(non_zero_similarity).to(
        similarity_maps.device).unsqueeze(0) / 255.
    similarity_maps = non_zero_similarity.unsqueeze(-1) * similarity_maps
    return images, normal_maps, similarity_maps, depth_maps, fragments

@torch.no_grad()
def check_visible_faces(mesh, fragments):
    pix_to_face = fragments.pix_to_face
    visible_map = pix_to_face.unique()  # (num_visible_faces)
    return visible_map

def get_all_4_locations(values_y, values_x):
    y_0 = torch.floor(values_y)
    y_1 = torch.ceil(values_y)
    x_0 = torch.floor(values_x)
    x_1 = torch.ceil(values_x)

    return torch.cat([y_0, y_0, y_1, y_1],
                     0).long(), torch.cat([x_0, x_1, x_0, x_1], 0).long()

def compose_quad_mask(new_mask_image, update_mask_image, old_mask_image,
                      device):
    """
        compose quad mask:
            -> 0: background
            -> 1: old
            -> 2: update
            -> 3: new
    """

    new_mask_tensor = transforms.ToTensor()(new_mask_image).to(device)
    update_mask_tensor = transforms.ToTensor()(update_mask_image).to(device)
    old_mask_tensor = transforms.ToTensor()(old_mask_image).to(device)

    all_mask_tensor = new_mask_tensor + update_mask_tensor + old_mask_tensor

    quad_mask_tensor = torch.zeros_like(all_mask_tensor)
    quad_mask_tensor[old_mask_tensor == 1] = 1
    quad_mask_tensor[update_mask_tensor == 1] = 2
    quad_mask_tensor[new_mask_tensor == 1] = 3

    return old_mask_tensor, update_mask_tensor, new_mask_tensor, all_mask_tensor, quad_mask_tensor

def compute_view_heat(similarity_tensor, quad_mask_tensor):
    num_total_pixels = quad_mask_tensor.reshape(-1).shape[0]
    heat = 0
    for idx in QUAD_WEIGHTS:
        heat += (quad_mask_tensor
                 == idx).sum() * QUAD_WEIGHTS[idx] / num_total_pixels

    return heat

def select_viewpoint(selected_view_ids,
                     view_punishments,
                     mode,
                     dist_list,
                     elev_list,
                     azim_list,
                     sector_list,
                     view_idx,
                     similarity_texture_cache,
                     exist_texture,
                     mesh,
                     faces,
                     verts_uvs,
                     image_size,
                     faces_per_pixel,
                     init_image_dir,
                     mask_image_dir,
                     normal_map_dir,
                     depth_map_dir,
                     similarity_map_dir,
                     device,
                     use_principle=False):
    if mode == 'sequential':

        num_views = len(dist_list)

        dist = dist_list[view_idx % num_views]
        elev = elev_list[view_idx % num_views]
        azim = azim_list[view_idx % num_views]
        sector = sector_list[view_idx % num_views]

        selected_view_ids.append(view_idx % num_views)

    elif mode == 'heuristic':

        if use_principle and view_idx < 6:

            selected_view_idx = view_idx

        else:

            selected_view_idx = None
            max_heat = 0

            print('=> selecting next view...')
            view_heat_list = []
            for sample_idx in tqdm(range(len(dist_list))):

                view_heat, *_ = render_one_view_and_build_masks(
                    dist_list[sample_idx], elev_list[sample_idx],
                    azim_list[sample_idx], sample_idx, sample_idx,
                    view_punishments, similarity_texture_cache, exist_texture,
                    mesh, faces, verts_uvs, image_size, faces_per_pixel,
                    init_image_dir, mask_image_dir, normal_map_dir,
                    depth_map_dir, similarity_map_dir, device)

                if view_heat > max_heat:
                    selected_view_idx = sample_idx
                    max_heat = view_heat

                view_heat_list.append(view_heat.item())

            print(view_heat_list)
            print('select view {} with heat {}'.format(selected_view_idx,
                                                       max_heat))

        dist = dist_list[selected_view_idx]
        elev = elev_list[selected_view_idx]
        azim = azim_list[selected_view_idx]
        sector = sector_list[selected_view_idx]

        selected_view_ids.append(selected_view_idx)

        view_punishments[selected_view_idx] *= 0.01

    elif mode == 'random':

        selected_view_idx = random.choice(range(len(dist_list)))

        dist = dist_list[selected_view_idx]
        elev = elev_list[selected_view_idx]
        azim = azim_list[selected_view_idx]
        sector = sector_list[selected_view_idx]

        selected_view_ids.append(selected_view_idx)

    else:
        raise NotImplementedError()

    return dist, elev, azim, sector, selected_view_ids, view_punishments

@torch.no_grad()
def build_backproject_mask(mesh, faces, verts_uvs, cameras, reference_image,
                           faces_per_pixel, image_size, uv_size, device):
    # construct pixel UVs
    renderer_scaled = init_renderer(
        cameras,
        shader=init_soft_phong_shader(
            camera=cameras, blend_params=BlendParams(), device=device),
        image_size=image_size,
        faces_per_pixel=faces_per_pixel)
    fragments_scaled = renderer_scaled.rasterizer(mesh)

    # get UV coordinates for each pixel
    faces_verts_uvs = verts_uvs[faces.textures_idx]

    pixel_uvs = interpolate_face_attributes(fragments_scaled.pix_to_face,
                                            fragments_scaled.bary_coords,
                                            faces_verts_uvs)  # NxHsxWsxKx2
    pixel_uvs = pixel_uvs.permute(0, 3, 1, 2, 4).reshape(-1, 2)

    texture_locations_y, texture_locations_x = get_all_4_locations(
        (1 - pixel_uvs[:, 1]).reshape(-1) * (uv_size - 1),
        pixel_uvs[:, 0].reshape(-1) * (uv_size - 1))

    K = faces_per_pixel

    texture_values = torch.from_numpy(
        np.array(reference_image.resize(
            (image_size, image_size)))).float() / 255.
    texture_values = texture_values.to(device).unsqueeze(0).expand(
        [4, -1, -1, -1]).unsqueeze(0).expand([K, -1, -1, -1, -1])

    # texture
    texture_tensor = torch.zeros(uv_size, uv_size, 3).to(device)
    texture_tensor[texture_locations_y,
                   texture_locations_x, :] = texture_values.reshape(-1, 3)

    return texture_tensor[:, :, 0]

@torch.no_grad()
def build_diffusion_mask(mesh_stuff,
                         renderer,
                         exist_texture,
                         similarity_texture_cache,
                         target_value,
                         device,
                         image_size,
                         smooth_mask=False,
                         view_threshold=0.01):
    mesh, faces, verts_uvs = mesh_stuff
    mask_mesh = mesh.clone()  # NOTE in-place operation - DANGER!!!

    # visible mask => the whole region
    exist_texture_expand = exist_texture.unsqueeze(0).unsqueeze(-1).expand(
        -1, -1, -1, 3).to(device)
    mask_mesh.textures = TexturesUV(
        maps=torch.ones_like(exist_texture_expand),
        faces_uvs=faces.textures_idx[None, ...],
        verts_uvs=verts_uvs[None, ...],
        sampling_mode='nearest')
    # visible_mask_tensor, *_ = render(mask_mesh, renderer)
    visible_mask_tensor, _, similarity_map_tensor, *_ = render(
        mask_mesh, renderer)
    # faces that are too rotated away from the viewpoint will be treated as invisible
    valid_mask_tensor = (similarity_map_tensor >= view_threshold).float()
    visible_mask_tensor *= valid_mask_tensor

    # nonexist mask <=> new mask
    exist_texture_expand = exist_texture.unsqueeze(0).unsqueeze(-1).expand(
        -1, -1, -1, 3).to(device)
    mask_mesh.textures = TexturesUV(
        maps=1 - exist_texture_expand,
        faces_uvs=faces.textures_idx[None, ...],
        verts_uvs=verts_uvs[None, ...],
        sampling_mode='nearest')
    new_mask_tensor, *_ = render(mask_mesh, renderer)
    new_mask_tensor *= valid_mask_tensor

    # exist mask => visible mask - new mask
    exist_mask_tensor = visible_mask_tensor - new_mask_tensor
    exist_mask_tensor[
        exist_mask_tensor < 0] = 0  # NOTE dilate can lead to overflow

    # all update mask
    mask_mesh.textures = TexturesUV(
        maps=(
            similarity_texture_cache.argmax(0) == target_value
            # # only consider the views that have already appeared before
            # similarity_texture_cache[0:target_value+1].argmax(0) == target_value
        ).float().unsqueeze(0).unsqueeze(-1).expand(-1, -1, -1, 3).to(device),
        faces_uvs=faces.textures_idx[None, ...],
        verts_uvs=verts_uvs[None, ...],
        sampling_mode='nearest')
    all_update_mask_tensor, *_ = render(mask_mesh, renderer)

    # current update mask => intersection between all update mask and exist mask
    update_mask_tensor = exist_mask_tensor * all_update_mask_tensor

    # keep mask => exist mask - update mask
    old_mask_tensor = exist_mask_tensor - update_mask_tensor

    # convert
    new_mask = new_mask_tensor[0].cpu().float().permute(2, 0, 1)
    new_mask = transforms.ToPILImage()(new_mask).convert('L')

    update_mask = update_mask_tensor[0].cpu().float().permute(2, 0, 1)
    update_mask = transforms.ToPILImage()(update_mask).convert('L')

    old_mask = old_mask_tensor[0].cpu().float().permute(2, 0, 1)
    old_mask = transforms.ToPILImage()(old_mask).convert('L')

    exist_mask = exist_mask_tensor[0].cpu().float().permute(2, 0, 1)
    exist_mask = transforms.ToPILImage()(exist_mask).convert('L')

    return new_mask, update_mask, old_mask, exist_mask

@torch.no_grad()
def render_one_view(mesh, dist, elev, azim, image_size, faces_per_pixel,
                    device):
    # render the view
    # print(image_size)
    cameras = init_camera(dist, elev, azim, image_size, device)
    renderer = init_renderer(
        cameras,
        shader=init_soft_phong_shader(
            camera=cameras, blend_params=BlendParams(), device=device),
        image_size=image_size,
        faces_per_pixel=faces_per_pixel)

    init_images_tensor, normal_maps_tensor, similarity_tensor, depth_maps_tensor, fragments = render(
        mesh, renderer)
    # print(init_images_tensor.shape, torch.max(init_images_tensor), torch.min(init_images_tensor))
    cv2.imwrite('img.png',
                (np.array(init_images_tensor.squeeze(0)[:, :, :3].cpu())
                 * 255).astype(np.uint8))
    return (cameras, renderer, init_images_tensor, normal_maps_tensor,
            similarity_tensor, depth_maps_tensor, fragments)

@torch.no_grad()
def build_similarity_texture_cache_for_all_views(mesh, faces, verts_uvs,
                                                 dist_list, elev_list,
                                                 azim_list, image_size,
                                                 image_size_scaled, uv_size,
                                                 faces_per_pixel, device):
    num_candidate_views = len(dist_list)
    similarity_texture_cache = torch.zeros(num_candidate_views, uv_size,
                                           uv_size).to(device)

    print('=> building similarity texture cache for all views...')
    for i in tqdm(range(num_candidate_views)):
        cameras, _, _, _, similarity_tensor, _, _ = render_one_view(
            mesh, dist_list[i], elev_list[i], azim_list[i], image_size,
            faces_per_pixel, device)

        similarity_texture_cache[i] = build_backproject_mask(
            mesh, faces, verts_uvs, cameras,
            transforms.ToPILImage()(similarity_tensor[0, :, :,
                                                      0]).convert('RGB'),
            faces_per_pixel, image_size_scaled, uv_size, device)

    return similarity_texture_cache

@torch.no_grad()
def render_one_view_and_build_masks(dist,
                                    elev,
                                    azim,
                                    selected_view_idx,
                                    view_idx,
                                    view_punishments,
                                    similarity_texture_cache,
                                    exist_texture,
                                    mesh,
                                    faces,
                                    verts_uvs,
                                    image_size,
                                    faces_per_pixel,
                                    init_image_dir,
                                    mask_image_dir,
                                    normal_map_dir,
                                    depth_map_dir,
                                    similarity_map_dir,
                                    device,
                                    save_intermediate=False,
                                    smooth_mask=False,
                                    view_threshold=0.01):
    # render the view
    (cameras, renderer, init_images_tensor, normal_maps_tensor,
     similarity_tensor, depth_maps_tensor,
     fragments) = render_one_view(mesh, dist, elev, azim, image_size,
                                  faces_per_pixel, device)

    init_image = init_images_tensor[0].cpu()
    init_image = init_image.permute(2, 0, 1)
    init_image = transforms.ToPILImage()(init_image).convert('RGB')

    normal_map = normal_maps_tensor[0].cpu()
    normal_map = normal_map.permute(2, 0, 1)
    normal_map = transforms.ToPILImage()(normal_map).convert('RGB')

    depth_map = depth_maps_tensor[0].cpu().numpy()
    depth_map = Image.fromarray(depth_map).convert('L')

    similarity_map = similarity_tensor[0, :, :, 0].cpu()
    similarity_map = transforms.ToPILImage()(similarity_map).convert('L')

    flat_renderer = init_renderer(
        cameras,
        shader=init_flat_texel_shader(camera=cameras, device=device),
        image_size=image_size,
        faces_per_pixel=faces_per_pixel)
    new_mask_image, update_mask_image, old_mask_image, exist_mask_image = build_diffusion_mask(
        (mesh, faces, verts_uvs),
        flat_renderer,
        exist_texture,
        similarity_texture_cache,
        selected_view_idx,
        device,
        image_size,
        smooth_mask=smooth_mask,
        view_threshold=view_threshold)
    # NOTE the view idx is the absolute idx in the sample space (i.e. `selected_view_idx`)
    # it should match with `similarity_texture_cache`

    (old_mask_tensor, update_mask_tensor, new_mask_tensor, all_mask_tensor,
     quad_mask_tensor) = compose_quad_mask(new_mask_image, update_mask_image,
                                           old_mask_image, device)

    view_heat = compute_view_heat(similarity_tensor, quad_mask_tensor)
    view_heat *= view_punishments[selected_view_idx]

    # save intermediate results
    if save_intermediate:
        init_image.save(
            os.path.join(init_image_dir, '{}.png'.format(view_idx)))
        normal_map.save(
            os.path.join(normal_map_dir, '{}.png'.format(view_idx)))
        depth_map.save(os.path.join(depth_map_dir, '{}.png'.format(view_idx)))
        similarity_map.save(
            os.path.join(similarity_map_dir, '{}.png'.format(view_idx)))

        new_mask_image.save(
            os.path.join(mask_image_dir, '{}_new.png'.format(view_idx)))
        update_mask_image.save(
            os.path.join(mask_image_dir, '{}_update.png'.format(view_idx)))
        old_mask_image.save(
            os.path.join(mask_image_dir, '{}_old.png'.format(view_idx)))
        exist_mask_image.save(
            os.path.join(mask_image_dir, '{}_exist.png'.format(view_idx)))

        visualize_quad_mask(mask_image_dir, quad_mask_tensor, view_idx,
                            view_heat, device)

    return (view_heat, renderer, cameras, fragments, init_image, normal_map,
            depth_map, init_images_tensor, normal_maps_tensor,
            depth_maps_tensor, similarity_tensor, old_mask_image,
            update_mask_image, new_mask_image, old_mask_tensor,
            update_mask_tensor, new_mask_tensor, all_mask_tensor,
            quad_mask_tensor)

def save_full_obj(output_dir, obj_name, verts, faces, verts_uvs, faces_uvs,
                  projected_texture, device):
    print('=> saving OBJ file...')
    texture_map = transforms.ToTensor()(projected_texture).to(device)
    texture_map = texture_map.permute(1, 2, 0)
    obj_path = os.path.join(output_dir, obj_name)

    save_obj(
        obj_path,
        verts=verts,
        faces=faces,
        decimal_places=5,
        verts_uvs=verts_uvs,
        faces_uvs=faces_uvs,
        texture_map=texture_map)

@torch.no_grad()
def backproject_from_image(mesh, faces, verts_uvs, cameras, reference_image,
                           new_mask_image, update_mask_image, init_texture,
                           exist_texture, image_size, uv_size, faces_per_pixel,
                           device):
    # construct pixel UVs
    renderer_scaled = init_renderer(
        cameras,
        shader=init_soft_phong_shader(
            camera=cameras, blend_params=BlendParams(), device=device),
        image_size=image_size,
        faces_per_pixel=faces_per_pixel)
    fragments_scaled = renderer_scaled.rasterizer(mesh)

    # get UV coordinates for each pixel
    faces_verts_uvs = verts_uvs[faces.textures_idx]

    pixel_uvs = interpolate_face_attributes(fragments_scaled.pix_to_face,
                                            fragments_scaled.bary_coords,
                                            faces_verts_uvs)  # NxHsxWsxKx2
    pixel_uvs = pixel_uvs.permute(0, 3, 1, 2,
                                  4).reshape(pixel_uvs.shape[-2],
                                             pixel_uvs.shape[1],
                                             pixel_uvs.shape[2], 2)

    # the update mask has to be on top of the diffusion mask
    new_mask_image_tensor = transforms.ToTensor()(new_mask_image).to(
        device).unsqueeze(-1)
    update_mask_image_tensor = transforms.ToTensor()(update_mask_image).to(
        device).unsqueeze(-1)

    project_mask_image_tensor = torch.logical_or(
        update_mask_image_tensor, new_mask_image_tensor).float()
    project_mask_image = project_mask_image_tensor * 255.
    project_mask_image = Image.fromarray(
        project_mask_image[0, :, :, 0].cpu().numpy().astype(np.uint8))

    project_mask_image_scaled = project_mask_image.resize(
        (image_size, image_size), )
    # Image.Resampling.NEAREST
    # )
    project_mask_image_tensor_scaled = transforms.ToTensor()(
        project_mask_image_scaled).to(device)

    pixel_uvs_masked = pixel_uvs[project_mask_image_tensor_scaled == 1]

    texture_locations_y, texture_locations_x = get_all_4_locations(
        (1 - pixel_uvs_masked[:, 1]).reshape(-1) * (uv_size - 1),
        pixel_uvs_masked[:, 0].reshape(-1) * (uv_size - 1))

    K = pixel_uvs.shape[0]
    project_mask_image_tensor_scaled = project_mask_image_tensor_scaled[:,
                                                                        None, :, :,
                                                                        None].repeat(
                                                                            1,
                                                                            4,
                                                                            1,
                                                                            1,
                                                                            3)

    texture_values = torch.from_numpy(
        np.array(reference_image.resize((image_size, image_size))))
    texture_values = texture_values.to(device).unsqueeze(0).expand(
        [4, -1, -1, -1]).unsqueeze(0).expand([K, -1, -1, -1, -1])

    texture_values_masked = texture_values.reshape(
        -1, 3)[project_mask_image_tensor_scaled.reshape(-1, 3) == 1].reshape(
            -1, 3)

    # texture
    texture_tensor = torch.from_numpy(np.array(init_texture)).to(device)
    texture_tensor[texture_locations_y,
                   texture_locations_x, :] = texture_values_masked

    init_texture = Image.fromarray(texture_tensor.cpu().numpy().astype(
        np.uint8))

    # update texture cache
    exist_texture[texture_locations_y, texture_locations_x] = 1

    return init_texture, project_mask_image, exist_texture


"""
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.

Two nodes of a binary tree are cousins if they have the same depth, but have different parents.

We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.

Return true if and only if the nodes corresponding to the values x and y are cousins.

Example 1:

Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:

Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false

Note:

The number of nodes in the tree will be between 2 and 100.
Each node has a unique integer value from 1 to 100.

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/cousins-in-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""
import collections

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
        """
        思路：广度优先搜索（队列）
        1. 定义为堂兄弟，如果给定的两个数正好是左右节点，返回FALSE
        2. 如果某一层出现了一个，返回FALSE
        3. 如果某一层出现了两个，返回TRUE
        """
        if not root:
            return False
        queue = collections.deque()
        queue.append(root)
        while queue:
            count = 0
            for i in range(len(queue)):
                root = queue.popleft()
                if root.left and root.right:
                    if x in [root.left.val, root.right.val] and y in [root.left.val, root.right.val]:
                        return False
                if root.left:
                    queue.append(root.left)
                    if x == root.left.val or y == root.left.val:
                        count += 1
                if root.right:
                    queue.append(root.right)
                    if x == root.right.val or y == root.right.val:
                        count += 1
                if count == 2:
                    return True
                if count == 1:
                    return False
        return False

    def isCousins2(self, root: TreeNode, x: int, y: int) -> bool:
        """
        仿造官方题解
        1、
        """
        depth = {}
        father = {}

        def dfs(root, layer, pre):
            if not root:
                return
            depth[root.val] = layer
            father[root.val] = pre.val if pre else 0

            if root.left:
                dfs(root.left, layer + 1, root)

            if root.right:
                dfs(root.right, layer + 1, root)

        dfs(root, 0, None)
        return depth[x] == depth[y] and father[x] != father[y]

    def isCousins3(self, root, x, y):
        """
        官方题解思路：dfs+记忆化
        1. 利用两个dict记录每个节点的父节点和所在的层次
        2. 比较x,y所在层次以及父节点是否相同
        """
        parent = {}
        depth = {}

        def dfs(node, par=None):
            if node:
                depth[node.val] = 1 + depth[par.val] if par else 0
                parent[node.val] = par
                dfs(node.left, node)
                dfs(node.right, node)

        dfs(root)
        return depth[x] == depth[y] and parent[x] != parent[y]

LeetCode/树(Binary Tree)/993. Cousins in Binary Tree.py


import hashlib
import tkinter as tk
from PIL import Image, ImageFile, ImageTk
ImageFile.LOAD_TRUNCATED_IMAGES = True
import os
import datetime
import pickle
import random

#Updating to do resurrect slideshow only -- REM -- 2022-11-16

#TODO
#    Make this class general enough to use for both import and slideshow
    #for import, text input bar sets tags for the current image
    #for slideshow, text input bar restarts slideshow with new search terms
    #fix final skipped file in a batch of duplicates getting tag input anyway
    #for import, sort inbox files by timestamp

#NUDADBDIR = os.path.dirname(os.path.abspath(sys.argv[0])) + '/nudaDBDir/'        #this gets the directory of the python script
NUDADBDIR = os.getcwd() + '/nudaDBDir/'                            #this gets the current working directory
#print NUDADBDIR
#NUDADBTABLE = os.path.dirname(os.path.abspath(sys.argv[0])) + '/nudaDBTable.txt'
NUDADBTABLE = os.getcwd() + '/nudaDBTable.txt'
MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
DELAY = 5000    #time delay to display each image in milliseconds

def getFilesMatchingAllTags(listOfTags, pickleFileName):
    #SLIDESHOW VERSION, RETURN LIST OF STRINGS, NOT LIST OF TUPLES
    #HARDCODE RETURN ONLY IMAGES
    listOfTags.append("image")
    with open(pickleFileName,"rb") as pickleFile:
        tagDict = pickle.load(pickleFile)
    aFileList = []
    outputList = []
    #get all files matching first tag
    for result in tagDict[listOfTags[0]]:
        aFileList.append(result)
    #loop through other tags, keeping only files which match
    for tag in listOfTags[1:]:
        aFileList = [f for f in aFileList if f in tagDict[tag]]
    #loop through final list, sorting image, video, and other, and specifying ext
    #for result in aFileList:
    #    ext = result.split('.')[-1]
    #    if result in tagDict['image']:
    #        outputList.append((result,'image',ext))
    #    elif result in tagDict['video']:
    #        outputList.append((result,'video',ext))
    #    else:
    #        outputlist.append((result,'other',ext))
    print(f"Found {len(aFileList)} Images matching tags: {listOfTags}")
    return aFileList

def getImagesMatchingTags(listOfTags, pickleFileName):
    with open(pickleFileName,"rb") as pickleFile:
        tagDict = pickle.load(pickleFile)
    imagelist = []
    for tag in listOfTags:
        for result in tagDict[tag]:
            imagelist.append(result)
    return imagelist

class slideShowClass:
    #def __init__(self,master,listOfImagePaths,showOrImport):
    def __init__(self,master,listOfImagePaths, pickleFileName):
        self.master = master
        self.listOfImagePaths = listOfImagePaths
        self.pickleFileName = pickleFileName
        self.input_strings = []
        self.currentInputIndex = 0
        self.afterID = None
        self.currentImageIndex = -1
        self.rotations = {3: 180, 6: 270, 8: 90}
        #self.currentImage = ImageTk.PhotoImage(self.makeThumb(self.listOfImagePaths[0]))
        self.currentImage = None
        self.currentImageOriginal = None
        self.fullscreenState = True

        #self.sortImageListByTimeStamp()
        self.sortImageListByShuffle()

        master.title("Slide Show")
        master.geometry(str(round(0.9*master.winfo_screenwidth()))+'x'+str(round(0.9*master.winfo_screenheight())))
        master.configure(background='black')
        self.master.attributes("-fullscreen", self.fullscreenState)

        self.showpanel = tk.Label(master, image=self.currentImage)
        self.showpanel.pack(fill='both', expand='yes')
        self.showpanel.config(bg="black")

        self.Hints = tk.Text(master, height=1)
        self.Hints.insert(tk.INSERT, "Previous (Page Up)_____Next (Page Down)_____")
        self.Hints.insert(tk.END,"Exit (Ctrl-w)")
        self.Hints.pack()

        self.textbox = tk.Entry(master)
        self.textbox.focus()
        self.textbox.bind("<Return>", self.new_search)
        self.textbox.bind("<Next>", self.show_next)    #Page Down
        self.textbox.bind("<Prior>", self.show_prev)    #Page Up
        self.textbox.bind("<Up>", self.input_hist_prev)
        self.textbox.bind("<Down>", self.input_hist_next)
        self.textbox.bind("<Control-Key-w>", self.show_stop)
        self.textbox.bind("<Escape>", self.fullscreen_off)
        self.textbox.bind("<F11>", self.toggle_fullscreen)
        self.textbox.pack(side='bottom', fill='x', expand=True)

        self.show_next()

    def sortImageListByShuffle(self, event=None):
        random.shuffle(self.listOfImagePaths)

    def sortImageListByTimeStamp(self, event=None):
        idummy = 1
        tempList = self.listOfImagePaths
        stamps = []
        for impath in tempList:
            aImage = Image.open(impath)
            try:
                fullexif=aImage._getexif()
                aTime = datetime.datetime.strptime(fullexif[36867], "%Y:%m:%d %H:%M:%S")
                stamps.append(int(aTime.timestamp()))
            except Exception as ex:
                print(ex)
                print("EXIF Problem! Assigning unix timestamp as ", idummy)
                stamps.append(idummy)
                idummy = idummy + 1
        sortedList = [x for _, x in sorted(zip(stamps,tempList), key=lambda pair: pair[0])]
        self.listOfImagePaths = list(sortedList)

    def fullscreen_off(self, event=None):
        self.fullscreenState = False
        self.master.attributes("-fullscreen", False)

    def toggle_fullscreen(self, event=None):
        self.fullscreenState = not self.fullscreenState
        self.master.attributes("-fullscreen", self.fullscreenState)

    def new_search(self, event=None):
        newTags = self.textbox.get()
        if newTags in ['\\quit', '\\exit', '\\abort']:
            self.master.quit()
            return None
        self.input_strings.append(newTags)
        taglist = self.input_strings[-1].split(' ')
        self.listOfImagePaths = getFilesMatchingAllTags(taglist, self.pickleFileName)
        self.sortImageListByShuffle()
        self.currentImageIndex = -1
        self.show_next()
        self.currentInputIndex = 0
        self.textbox.delete(0, tk.END)

    def getHash(self, thefile):
        BLOCKSIZE = 65536
        hasher = hashlib.md5()
        with open(thefile, 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher.update(buf)
                buf = afile.read(BLOCKSIZE)
        return hasher.hexdigest()

    def input_hist_prev(self, event=None):
        self.currentInputIndex -= 1
        if self.currentInputIndex >= -len(self.input_strings):
            self.textbox.delete(0, tk.END)
            self.textbox.insert(0, self.input_strings[self.currentInputIndex])
        else:
            self.currentInputIndex += 1

    def input_hist_next(self, event=None):
        self.currentInputIndex += 1
        if self.currentInputIndex < 0:
            self.textbox.delete(0, tk.END)
            self.textbox.insert(0, self.input_strings[self.currentInputIndex])
        else:
            self.currentInputIndex = 0
            self.textbox.delete(0, tk.END)

    def next_image(self, event=None):
        if self.afterID is not None:
            self.master.after_cancel(self.afterID)
            self.afterID = None
        self.currentImageIndex += 1
        if self.currentImageIndex >= len(self.listOfImagePaths):
            self.currentImageIndex = 0
        try:
            tempFileName = self.listOfImagePaths[self.currentImageIndex]
            testOpen = Image.open(tempFileName)
        except:
            print("Can't open file: "+tempFileName+" (Not an image?) Skipping....")
            if os.path.isfile('./inbox/'+self.filename):
                os.system("mv "+self.fullpath.replace(' ', "\ ")+" "+NUDADBDIR+"../inbox/skipped/"+self.newName)
            else:
                print("Can't find file to skip!? Something has gone wrong...")
            return False    #skip tag input for this skipped file
        self.currentImage = ImageTk.PhotoImage(self.makeThumb(self.listOfImagePaths[self.currentImageIndex]))
        self.showpanel.configure(image=self.currentImage)
        self.showpanel.image = self.currentImage
        return True

    def show_next(self, event=None):
        self.next_image(event)
        self.afterID = self.master.after(DELAY,self.show_next)

    def show_prev(self, event=None):
        self.currentImageIndex = max(0,self.currentImageIndex-2)
        self.next_image(event)
        self.afterID = self.master.after(DELAY,self.show_next)

    def show_stop(self, event):
        self.master.quit()

    def makeThumb(self, imagePath):
        targetW = self.master.winfo_width()
        targetH = self.master.winfo_height()-50
        thumb = Image.open(imagePath)
        self.currentImageOriginal = Image.open(imagePath)
        try:
            orientation = thumb._getexif()[0x0112]
        except:
            print("EXIF problem! Setting orientation=0")
            orientation = 0
        if orientation in self.rotations:
            thumb = thumb.rotate(self.rotations[orientation], expand=1)
        self.master.update_idletasks()
        thumb.thumbnail((targetW, targetH))
        if thumb.size[0] < targetW and thumb.size[1] < targetH:
            scaleFactor = min((targetW/thumb.size[0], targetH/thumb.size[1]))
            thumb = thumb.resize((int(thumb.size[0]*scaleFactor), int(thumb.size[1]*scaleFactor)))
        return thumb


# Prices
flooring = 1.50
insulation = 0.5
dryWall = 2

print("Let's finish your room")

# Dimensions
width = float(input("Room Width: "))
length = float(input("Room Length: "))
height = float(input("Room Height: "))

floorCost = flooring * length * width
insulationCost = insulation * length * width
dryWallCeilingCost = dryWall * length * width
dryWallWallsCost = dryWall * (2 * length * height + 2 * width * height)
totalDryWallCost = dryWallCeilingCost + dryWallWallsCost
totalCost = floorCost + insulationCost + totalDryWallCost

print(f"Room finishing cost: ${totalCost}")


'''In a lot of places, they only spoke about using either dataframes or text as input for Spark NLP functions.
If we use text, it might take too long bc we have SO many records. And also bc we need the Spam/Ham column for each message as well for our model.
So I think converting the input from localhost to a dataframe is our best bet.'''

#from https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html

# Create DataFrame representing the stream of input lines from connection to localhost:9999
lines = spark \
    .readStream \
    .format("socket") \
    .option("host", "localhost") \
    .option("port", 9999) \
    .load()

# Split the lines into words
words = lines.select(
   explode(
       split(lines.value," ")
   ).alias("word")
)

# Generate running word count
wordCounts = words.groupBy("word").count()

'''This lines DataFrame represents an unbounded table containing the streaming text data.
This table contains one column of strings named “value”, and each line in the streaming text data becomes a row in the table.
Note, that this is not currently receiving any data as we are just setting up the transformation, and have not yet started it.
Next, we have used two built-in SQL functions - split and explode, to split each line into multiple rows with a word each.
In addition, we use the function alias to name the new column as “word”.
Finally, we have defined the wordCounts DataFrame by grouping by the unique values in the Dataset and counting them.
Note that this is a streaming DataFrame which represents the running word counts of the stream.'''


# -*- coding: utf-8 -*-
"""Helper functions for EWF image support."""

from dfvfs.lib import errors
from dfvfs.path import factory as path_spec_factory

def EWFGlobPathSpec(file_system, path_spec):
  """Globs for path specifications according to the EWF naming schema.

  Args:
    file_system (FileSystem): file system.
    path_spec (PathSpec): path specification.

  Returns:
    list[PathSpec]: path specifications that match the glob.

  Raises:
    PathSpecError: if the path specification is invalid.
    RuntimeError: if the maximum number of supported segment files is
        reached.
  """
  if not path_spec.HasParent():
    raise errors.PathSpecError(
        'Unsupported path specification without parent.')

  parent_path_spec = path_spec.parent

  parent_location = getattr(parent_path_spec, 'location', None)
  if not parent_location:
    raise errors.PathSpecError(
        'Unsupported parent path specification without location.')

  parent_location, _, segment_extension = parent_location.rpartition('.')
  segment_extension_start = segment_extension[0]
  segment_extension_length = len(segment_extension)

  if (segment_extension_length not in [3, 4] or
      not segment_extension.endswith('01') or (
          segment_extension_length == 3 and
          segment_extension_start not in ['E', 'e', 's']) or (
              segment_extension_length == 4 and
              not segment_extension.startswith('Ex'))):
    raise errors.PathSpecError((
        f'Unsupported parent path specification invalid segment file '
        f'extension: {segment_extension:s}'))

  segment_number = 1
  segment_files = []
  while True:
    segment_location = f'{parent_location:s}.{segment_extension:s}'

    # Note that we don't want to set the keyword arguments when not used
    # because the path specification base class will check for unused
    # keyword arguments and raise.
    kwargs = path_spec_factory.Factory.GetProperties(parent_path_spec)

    kwargs['location'] = segment_location
    if parent_path_spec.parent is not None:
      kwargs['parent'] = parent_path_spec.parent

    segment_path_spec = path_spec_factory.Factory.NewPathSpec(
        parent_path_spec.type_indicator, **kwargs)

    if not file_system.FileEntryExistsByPathSpec(segment_path_spec):
      break

    segment_files.append(segment_path_spec)

    segment_number += 1
    if segment_number <= 99:
      if segment_extension_length == 3:
        segment_extension = f'{segment_extension_start:s}{segment_number:02d}'
      elif segment_extension_length == 4:
        segment_extension = f'{segment_extension_start:s}x{segment_number:02d}'

    else:
      segment_index = segment_number - 100

      if segment_extension_start in ['e', 's']:
        letter_offset = ord('a')
      else:
        letter_offset = ord('A')

      segment_index, remainder = divmod(segment_index, 26)
      third_letter = chr(letter_offset + remainder)

      segment_index, remainder = divmod(segment_index, 26)
      second_letter = chr(letter_offset + remainder)

      first_letter = chr(ord(segment_extension_start) + segment_index)
      if first_letter in ['[', '{']:
        raise RuntimeError('Unsupported number of segment files.')

      if segment_extension_length == 3:
        segment_extension = f'{first_letter:s}{second_letter:s}{third_letter:s}'
      elif segment_extension_length == 4:
        segment_extension = (
            f'{first_letter:s}x{second_letter:s}{third_letter:s}')

  return segment_files


'''@file scorer_factory.py
contains the Scorer factory'''

from . import  sdr_scorer, pesq_scorer

def factory(scorer):
    '''
    gets a scorer class

    Args:
        scorer: the scorer type

    Returns:
        a scorer class
    '''

    if scorer == 'sdr':
        return sdr_scorer.SdrScorer
    if scorer == 'pesq':
        return pesq_scorer.PESQScorer
    else:
        raise Exception('Undefined scorer type: %s' % scorer)


import turtle
from itertools import cycle
colors=cycle(['red','orange','blue','purple','black','orange'])

def draw_circle(size,angle,shift):
    turtle.bgcolor(next(colors))
    turtle.pencolor(next(colors))
    turtle.circle(size)
    turtle.right(angle)
    turtle.forward(shift)
    draw_circle(size+3,angle+4,shift+3)
turtle.bgcolor('blue')
turtle.speed('slow')
turtle.pensize(30)
draw_circle(20,0,5)


import util
from scrapers.base import BaseScraper
from bs4 import BeautifulSoup

class NobaScraper(BaseScraper):
    def scrape(self):
        try:
            self.driver.get(self.website)
            soup = BeautifulSoup(self.driver.page_source, 'html.parser')
            df = []
            headline = soup.find('h1').get_text()
            for elm in soup.select('p'):
                try:
                    if  "text-muted" in elm['class']:
                        continue
                except:
                    df.append(elm.get_text())
            article = util.article(df, headline)
            return article
        except Exception as e:
            print(e)


from tree import training_data, training_labels, testing_data, testing_labels, make_random_forest, make_single_tree, \
    classify
import numpy as np
import random

np.random.seed(1)
random.seed(1)

# tree made without bagging, 1 row per new tree
tree = make_single_tree(training_data, training_labels)
forest = make_random_forest(40, training_data, training_labels)

# initialize variables to count num correct
single_tree_correct = 0
forest_correct = 0

# loops through every point in test set, compares to actual tree value
# and returns percentage of correctly classified points
for i in range(len(testing_data)):
    prediction = classify(testing_data[i], tree)
    if prediction == testing_labels[i]:
        single_tree_correct += 1
    predictions = []
    for forest_tree in forest:
        predictions.append(classify(testing_data[i], forest_tree))
    forest_prediction = max(predictions, key=predictions.count)
    if forest_prediction == testing_labels[i]:
        forest_correct += 1

# prints accuracy for single decision tree
print("Single tree accuracy: " + str(single_tree_correct / len(testing_data)))
print("Forest of trees accuracy: " + str(forest_correct / len(testing_data)))

machine learning/decision trees and forests/forests/evaluating_forest_accuracy.py


import socket
import paramiko
import threading
import sys

host_key = paramiko.RSAKey(filename="C:\\Users\\ASUS\\.ssh\\sshkey")

class Server(paramiko.ServerInterface):
    def __init__(self):
        self.event=threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == "session":
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if username == "root" and password == "toor":
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

server = sys.argv[1]
ssh_port = int(sys.argv[2])

try:
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    sock.bind((server,ssh_port))
    sock.listen(100)
    print("[+] Listening for connection...")
    client,addr = sock.accept()
except Exception as e:
    print("Listen failed: "+str(e))
    sys.exit(1)

print("[+] Got a connection!")
try:
    bhSession = paramiko.Transport(client)
    bhSession.add_server_key(host_key)
    server=Server()
    try:
        bhSession.start_server(server=server)
    except paramiko.SSHException as e:
        print("[-]ssh negotiation failed")
        print(str(e))
    channel = bhSession.accept(20)
    print(channel.recv(1024).decode("utf8"))
    channel.send("Welcome to bh_ssh")
    while True:
        try:
            command = input("Enter command: ").strip("\n")
            if command != "exit":
                channel.send(command)
                print(channel.recv(2048).decode("gbk"))
            else:
                channel.send("exit")
                print("exit...")
                bhSession.close()
                raise Exception("exit")
        except KeyboardInterrupt:
            bhSession.close()
except Exception as e:
    print(str(e))
    try:
        bhSession.close()
    except Exception as _:
        pass
    sys.exit(1)


"""A parser for reading the gravitational deformation file
"""

# Standard library imports
from datetime import datetime

# Third party imports
import numpy as np

# Midgard imports
from midgard.dev import plugins
from midgard.math.constant import constant
from midgard.math.unit import Unit
from midgard.parsers._parser import Parser

@plugins.register
class GravitationalDeformationParser(Parser):
    """A parser for reading the gravitational deformation file"""

    def read_data(self):
        with open(self.file_path, mode="rt") as fid:
            fid.readline()  # skip first line which only contains file version information
            current_station = ""

            for line in fid:
                if line.startswith("#"):
                    continue

                line = line.split()
                if not line:
                    continue

                if len(line) == 3 and not line[0].isnumeric():
                    # block header line
                    if line[0] == "EPOCH":
                        self.data[current_station]["start"] = datetime.strptime(line[1], "%Y%M%d")
                        self.data[current_station]["end"] = datetime.strptime(line[2], "%Y%M%d")
                    else:
                        current_station = line[0].strip().replace(" ", "_")
                        sta_dict = self.data.setdefault(current_station, dict())
                        sta_dict["elevation"] = list()
                        sta_dict["delay"] = list()
                        sta_dict["scale"] = float(line[2])
                        sta_dict["start"] = datetime.min
                        sta_dict["end"] = datetime.max
                else:
                    # data line
                    self.data[current_station]["elevation"].append(float(line[0]))  # Degrees
                    self.data[current_station]["delay"].append(float(line[1]))

    def postprocess_data(self):
        for sta_dict in self.data.values():
            if sta_dict["scale"] != 3.336:
                # Delay values is not given in millimeter
                # Convert delay to meter by using scale factor
                sta_dict["delay"] = np.array(sta_dict["delay"]) * sta_dict["scale"] * Unit.ps2s / constant.c
            else:
                # Use simplified conversion if delay is in millimeter (better precision)
                sta_dict["delay"] = np.array(sta_dict["delay"]) * Unit.mm2m

            del sta_dict["scale"]
            sta_dict["elevation"] = np.deg2rad(sta_dict["elevation"])