import const
import fight
import game_utils
import handler_game
import instance
import interp
import merc

# Hurl skill by KaVir
def cmd_hurl(ch, argument):
    argument, arg1 = game_utils.read_word(argument)
    argument, arg2 = game_utils.read_word(argument)

    if not ch.is_npc() and ch.learned["hurl"] < 1:
        ch.send("Maybe you should learn the skill first?\n")
        return

    if not arg1:
        ch.send("Who do you wish to hurl?\n")
        return

    victim = ch.get_char_room(arg1)
    if not victim:
        ch.not_here(arg1)
        return

    if ch == victim:
        ch.not_self()
        return

    if fight.is_safe(ch, victim):
        return

    mount = victim.mount
    if mount and victim.mounted == merc.IS_MOUNT:
        ch.send("But they have someone on their back!\n")
        return

    if mount and victim.mounted == merc.IS_RIDING:
        ch.send("But they are riding!\n")
        return

    if not victim.is_npc() and victim.immune.is_set(merc.IMM_HURL):
        ch.send("You are unable to get their feet of the ground.\n")
        return

    if victim.is_npc() and victim.level > 900:
        ch.send("You are unable to get their feet of the ground.\n")
        return

    if victim.hit < victim.max_hit or (victim.position == merc.POS_FIGHTING and victim.fighting != ch):
        handler_game.act("$N is hurt and suspicious, and you are unable to approach $M.", ch, None, victim, merc.TO_CHAR)
        return

    ch.wait_state(const.skill_table["hurl"].beats)

    if not ch.is_npc() and game_utils.number_percent() > ch.learned["hurl"]:
        ch.send("You are unable to get their feet of the ground.\n")
        fight.multi_hit(victim, ch, merc.TYPE_UNDEFINED)
        return

    if not arg2:
        door = game_utils.number_range(0, 3)
    else:
        if game_utils.str_cmp(arg2, ["n", "north"]):
            door = merc.DIR_NORTH
        elif game_utils.str_cmp(arg2, ["e", "east"]):
            door = merc.DIR_EAST
        elif game_utils.str_cmp(arg2, ["s", "south"]):
            door = merc.DIR_SOUTH
        elif game_utils.str_cmp(arg2, ["w", "west"]):
            door = merc.DIR_WEST
        else:
            ch.send("You can only hurl people north, south, east or west.\n")
            return

    if door == merc.DIR_NORTH:
        direction = "north"
        rev_dir = 2
    elif door == merc.DIR_EAST:
        direction = "east"
        rev_dir = 3
    elif door == merc.DIR_SOUTH:
        direction = "south"
        rev_dir = 0
    else:
        direction = "west"
        rev_dir = 1

    pexit = ch.in_room.exit[door]
    to_room = instance.rooms[pexit.to_room] if pexit else None
    if not pexit or not to_room:
        handler_game.act("$n hurls $N into the $t wall.", ch, direction, victim, merc.TO_NOTVICT)
        handler_game.act("You hurl $N into the $t wall.", ch, direction, victim, merc.TO_CHAR)
        handler_game.act("$n hurls you into the $t wall.", ch, direction, victim, merc.TO_VICT)

        dam = game_utils.number_range(ch.level, (ch.level * 4))
        victim.hit -= dam
        fight.update_pos(victim)

        if victim.is_npc() and not ch.is_npc():
            ch.mkill += 1

        if not victim.is_npc() and ch.is_npc():
            victim.mdeath += 1

        if victim.position == merc.POS_DEAD:
            fight.raw_kill(victim)
            return
        return

    pexit = victim.in_room.exit[door]
    if pexit.exit_info.is_set(merc.EX_CLOSED) and not victim.is_affected(merc.AFF_PASS_DOOR) and not victim.is_affected(merc.AFF_ETHEREAL):
        pexit.exit_info.rem_bit(merc.EX_LOCKED)
        pexit.exit_info.rem_bit(merc.EX_CLOSED)
        handler_game.act("$n hoists $N in the air and hurls $M $t.", ch, direction, victim, merc.TO_NOTVICT)
        handler_game.act("You hoist $N in the air and hurl $M $t.", ch, direction, victim, merc.TO_CHAR)
        handler_game.act(f"$n hurls you $t, smashing you through the {pexit.keyword}.", ch, direction, victim, merc.TO_VICT)
        handler_game.act("There is a loud crash as $n smashes through the $d.", victim, None, pexit.keyword, merc.TO_ROOM)

        to_room = pexit.to_room
        pexit_rev = instance.rooms[to_room].exit[rev_dir]
        if to_room and pexit_rev and pexit_rev.to_room == ch.in_room and pexit_rev.keyword:
            pexit_rev.exit_info.rem_bit(merc.EX_LOCKED)
            pexit_rev.exit_info.rem_bit(merc.EX_CLOSED)

            if door == 0:
                direction = "south"
            elif door == 1:
                direction = "west"
            elif door == 2:
                direction = "north"
            else:
                direction = "east"

            victim.in_room.get(victim)
            to_room.put(victim)

            handler_game.act("$n comes smashing in through the $t $d.", victim, direction, pexit.keyword, merc.TO_ROOM)

            dam = game_utils.number_range(ch.level, (ch.level * 6))
            victim.hit -= dam
            fight.update_pos(victim)

            if victim.is_npc() and not ch.is_npc():
                ch.mkill += 1

            if not victim.is_npc() and ch.is_npc():
                victim.mdeath += 1

            if victim.position == merc.POS_DEAD:
                fight.raw_kill(victim)
    else:
        handler_game.act("$n hurls $N $t.", ch, direction, victim, merc.TO_NOTVICT)
        handler_game.act("You hurl $N $t.", ch, direction, victim, merc.TO_CHAR)
        handler_game.act("$n hurls you $t.", ch, direction, victim, merc.TO_VICT)

        if door == 0:
            direction = "south"
        elif door == 1:
            direction = "west"
        elif door == 2:
            direction = "north"
        else:
            direction = "east"

        victim.in_room.get(victim)
        to_room.put(victim)

        handler_game.act("$n comes flying in from the $t.", victim, direction, None, merc.TO_ROOM)

        dam = game_utils.number_range(ch.level, (ch.level * 2))
        victim.hit -= dam
        fight.update_pos(victim)

        if victim.is_npc() and not ch.is_npc():
            ch.mkill += 1

        if not victim.is_npc() and ch.is_npc():
            victim.mdeath += 1

        if victim.position == merc.POS_DEAD:
            fight.raw_kill(victim)

interp.register_command(
    interp.CmdType(
        name="hurl",
        cmd_fun=cmd_hurl,
        position=merc.POS_STANDING, level=0,
        log=merc.LOG_NORMAL, show=True,
        default_arg=""
    )
)


import glob
import os
import random
import re
import subprocess

# 1匹だけ写っているネコの画像が110枚以上あるもののみ使う
# 100匹を学習、10匹をtestに使う
num_train_images = 100
num_test_images = 10

def create_image_list():
    image_dic = {}
    files = glob.glob('output/[0-9][0-9][0-9]-[0-9]-*.png')
    for f in files:
        _, catid, image_id, fileid = re.split('[-/]', f)
        image_dic[fileid] = image_dic.get(fileid, []) + [(catid, image_id)]
    return image_dic

def get_single_and_multiple_cat_images(image_dic):
    # 1匹のみまたは複数ネコを含んだ画像リストを作る
    single_images = {}
    multiple_images = []
    max_num_cat = 0
    max_fileid = 0
    for fileid, li in image_dic.items():
        if len(li) > 1:
            print(fileid + " has more than one cat.")
            multiple_images.append(fileid)
            if len(li) > max_num_cat:
                max_fileid = fileid
                max_num_cat = len(li)
        else:
            for catid, image_id in li:
                single_images[catid] = single_images.get(catid, []) + [fileid]
    print(len(multiple_images))
    print(max_fileid, image_dic[max_fileid])
    return single_images, multiple_images

image_dic = create_image_list()
single_cat_images, multiple_cat_images = get_single_and_multiple_cat_images(image_dic)

#print(single_cat_images)

train_samples = {}
test_samples = {}

for catid, image in single_cat_images.items():
    if len(image) < num_train_images+num_test_images:
        continue
    random_sample = random.sample(image, num_train_images+num_test_images)
    train_samples[catid] = random_sample[:num_train_images]
    test_samples[catid] = random_sample[num_train_images:]

#print(test_samples)
#print(multiple_cat_images)

os.makedirs('output/train', exist_ok=True)
os.makedirs('output/test', exist_ok=True)

with open('train_images.csv', 'w') as f:
    f.write(f'ImageName,ImageLabel\n')
    for catid, fileids in train_samples.items():
        for fileid in fileids:
            f.write(f'{catid}-0-{fileid}, {int(catid)}\n')

with open('test_images.csv', 'w') as f:
    f.write(f'ImageName,ImageLabel\n')
    for catid, fileids in test_samples.items():
        for fileid in fileids:
            f.write(f'{catid}-0-{fileid}, {int(catid)}\n')

def resize_sample(data_type='train'):
    with open(f'{data_type}_images.csv') as f:
        lines = f.readlines()[1:]
        for line in lines:
            filename, _= line.rstrip().split(',')
            print('.', end="", flush=True)
            subprocess.run(f'python resize_image.py output/{filename} output/{data_type}/{filename} 224', shell=True)

resize_sample('train')
resize_sample('test')


#!/usr/bin/env python3

from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from logging import DEBUG, INFO, basicConfig, info
from os.path import isfile
from socketserver import ThreadingTCPServer
from sys import exit

from mysqlite import __version__
from mysqlite.server import Server

def main():
  parser = ArgumentParser(prog="mysqlite", add_help=False, allow_abbrev=False, formatter_class=ArgumentDefaultsHelpFormatter)
  parser.add_argument("--filename", help="Filename of the SQLite database")
  parser.add_argument("--address", default="localhost", help="IP address to bind to")
  parser.add_argument("--port", default=3306, type=int, help="Port number to use for connections")
  parser.add_argument("--debug", action="store_true", help="Print packets payload")
  parser.add_argument("--version", action="store_true", help="Version information")
  parser.add_argument("--help", action="store_true", help="This help")
  args = parser.parse_args()

  if args.version:
    print(f"MySQLite {__version__}")
    exit()
  elif args.help or args.filename is None or len(args.filename) == 0:
    parser.print_help()
    exit()
  elif not isfile(args.filename):
    raise FileNotFoundError(args.filename)

  level = DEBUG if args.debug else INFO
  basicConfig(format="%(threadName)s %(levelname).3s %(message)s", level=level)

  with ThreadingTCPServer((args.address, args.port), Server, False) as server:
    try:
      info(f"MySQLite {__version__}")
      info("STARTING...")
      server.allow_reuse_address = True
      server.server_bind()
      server.server_activate()
      server.filename = args.filename

      server.serve_forever()
    except KeyboardInterrupt:
      info("STOPPING...")
      server.shutdown()

if __name__ == "__main__":
  main()


# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['pycoinglass']

package_data = \
{'': ['*']}

install_requires = \
['pandas>=1.4.2,<2.0.0', 'requests>=2.27.1,<3.0.0']

setup_kwargs = {
    'name': 'pycoinglass',
    'version': '0.1.0',
    'description': '',
    'long_description': None,
    'author': 'ko0hi',
    'author_email': 'ko0hi.4731@gmail.com',
    'maintainer': None,
    'maintainer_email': None,
    'url': None,
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.9.0,<4.0.0',
}

setup(**setup_kwargs)


# -*- coding: utf-8 -*-
import socket

def get_info():
    global PORT
    PORT = int(input("Please choose the port number: "))

    global HOST_NAME
    HOST_NAME = socket.gethostname()

    global HOST_ADDRESS
    HOST_ADDRESS = socket.gethostbyname(HOST_NAME)

    print(HOST_NAME)
    print(HOST_ADDRESS)

def create_server():
    print("Openning socket...")
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) # create server socket
    server.bind((HOST_ADDRESS,PORT))
    server.listen(5)

    while True:
        client_connection, client_addr = server.accept()
        try:
            print("Connected to Client", client_addr)
            while True:
                # Receive data from Client
                data = client_connection.recv(4096)
                if not data:
                    break
                else:
                    print("-" * 20)
                    print("Client:", data.decode("utf8"))
                    if data.decode("utf8") == "quit":
                        break

                # Send msg to Client
                msg = input("Server: ")
                client_connection.send(msg.encode("utf8"))
        finally:
            client_connection.close()
            break
    print("-" * 20)
    print("Shutting dowm....")
    server.close()
    print("Done")

if __name__ == "__main__":
    get_info()
    create_server()


import http.server
import socketserver

class SimpleHTMLHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # Set the response code to 200 (OK)
        self.send_response(200)

        # Set the Content-type header to indicate HTML content
        self.send_header('Content-type', 'text/html')
        self.end_headers()

        # Read the content of the HTML file and send it as the response
        with open('page1.html', 'rb') as file:
            self.wfile.write(file.read())

# Set the port number you want to run the server on
port = 8080

# Create the HTTP server and bind it to the specified port
with socketserver.TCPServer(("127.0.0.1", port), SimpleHTMLHandler) as httpd:
    print(f"Server running on port {port}")

    # Start serving indefinitely until interrupted
    httpd.serve_forever()


import pandas as pd
import numpy as np
import pandas as pd
import joblib
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF
import csv
# Загрузка данных из CSV без разделительных столбцов "|||"
data = pd.read_csv('../metrics/updated_data1.csv', sep=',', usecols=lambda col: '|||' not in col)
# print(data)

# Загрузка данных из CSV без разделительных столбцов "|||"
data = pd.read_csv('../metrics/updated_data1.csv', sep=',', usecols=lambda col: '|||' not in col)
# print(data)

X = data.iloc[:, :-5]
y = data.iloc[:, -2]

# print(X)
# print(y)

X = X.values
y = y.values
# print(y)
X = data.iloc[:, :-5]
y = data.iloc[:, -2]
X = X.values
y = y.values
kernel = RBF()
gpr = GaussianProcessRegressor(kernel=kernel)

gpr.fit(X, y)
# Обучить модель на данных
model_name = 'gpr_trained_model.joblib'
joblib.dump(gpr, model_name)
print("Saved model to disk")
# Обучить модель на данных
model_name = 'gpr_trained_model.joblib'
joblib.dump(gpr, model_name)
print("Saved model to disk")
# Вывести гиперпараметры модели
with open("output.csv", mode="w", encoding="utf-8", newline='') as w_file:
    file_writer = csv.writer(w_file, delimiter=",")
    file_writer.writerow(["Hyperparameters"])
    for hyperparameter in gpr.kernel_.get_params():
        file_writer.writerow([str(hyperparameter)])

    file_writer.writerow([])
    file_writer.writerow(["Covariance Function"])
    covariance_matrix = gpr.kernel_(X)
    for i in range(len(covariance_matrix)):
        file_writer.writerow(covariance_matrix[i])

    file_writer.writerow([])
    file_writer.writerow(["Predictions"])
    predictions, std = gpr.predict(X, return_std=True)
    for i in range(len(X)):
        file_writer.writerow([predictions[i], std[i]])
print("Done")


days = int(input())
room = input()
rating = input()
price = 0
if room == "room for one person":
    price = 18
elif room == "apartment":
    if days - 1 < 10:
        price = 25 * 0.7
    elif 10 <= days - 1 <= 15:
        price = 25 * 0.65
    elif days > 15:
        price = 25 * 0.5
elif room == "president apartment":
    if days - 1 < 10:
        price = 35 * 0.9
    elif 10 <= days - 1 <= 15:
        price = 35 * 0.85
    elif days > 15:
        price = 35 * 0.8
if rating == "positive":
    print(f"{(price * (days - 1)) * 1.25:.2f}")
elif rating == "negative":
    print(f"{(price * (days - 1)) * 0.9:.2f}")

basic/Po-slojni proverki/13. Ski Trip.py


from django.db.models import Q, QuerySet

from rest_framework.generics import get_object_or_404

from app import models
from app import utils

def get_wallet_report_queryset(wallet_id, data) -> QuerySet:
    get_object_or_404(queryset=models.Wallet.objects.all(), id=wallet_id)

    res = models.StatusChange.objects.all().select_related('operation')
    res = res.filter(Q(operation__wallet_from=wallet_id) | Q(operation__wallet_to=wallet_id))

    date_from = utils.parse_user_date(data.get('date_from'))
    if date_from:
        res = res.filter(datetime__gte=date_from)

    date_to = utils.parse_user_date(data.get('date_to'))
    if date_to:
        res = res.filter(datetime__lte=date_to)

    res = res.order_by('-datetime')
    return res

def get_username_report_queryset(username, data) -> QuerySet:
    user = get_object_or_404(queryset=models.MyUser.objects.all(), username=username)
    return get_wallet_report_queryset(user.wallet.id, data)


import os
import sys
import random
from tqdm import tqdm
import torch
import numpy as np
import scipy

this_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(this_path)
transformemnn_path = this_path.strip("data") + "/training/"
# sys.path.append(transformemnn_path + "/db_dataloader")
droidlet_path = this_path.strip("data") + "/fairo/"
sys.path.append(droidlet_path)
sys.path.append(transformemnn_path + "/utils/")
sys.path.append(transformemnn_path)
from droidlet.lowlevel.minecraft.small_scenes_with_shapes import build_shape_scene
from droidlet.shared_data_structs import ErrorWithResponse
from query_builder import QAZoo
from utils.memory_utils import build_memory, get_memory_text
from utils.nsm_utils import make_world_args_from_config
from db_dataloader.db_encoder import DBEncoder
from config_args import get_opts, read_configs
from active_agent_world import EpisodeRunner, WorldBuilder
from utils.log_data import maybe_make_save_dir, update_data_info, save_files
from utils.nsm_utils import NULL_MEMID
from transformers import GPT2Tokenizer

tokenizer = GPT2Tokenizer.from_pretrained("gpt2")

def print_num_choices(opts):
    num_choices = 0
    for i in range(opts.props_per_name):
        num_choices += scipy.special.comb(opts.num_props, i + 1)
    possible_samples = ((num_choices) ** opts.num_names) * (
        opts.num_names + opts.num_props
    )
    print("number of possible samples: {:.0f}\n".format(possible_samples))

def increment_clause_counts(clause_types, clause_type_counts):
    for clause_type in clause_types:
        clause_type_counts[clause_type] = clause_type_counts.get(clause_type, 0) + 1
        clause_type_counts["total_clauses"] += 1

def increment_conjunction_counts(conj_type, conj_type_counts):
    if conj_type:
        conj_type_counts[conj_type] += 1
    else:
        conj_type_counts["NONE"] += 1
    conj_type_counts["total_samples"] += 1

def increment_null_counts(is_null, null_counts):
    if is_null:
        null_counts["null_samples"] += 1
    null_counts["total_samples"] += 1

def check_update_proportions(
    args,
    configs,
    memids,
    query_type,
    clause_types,
    clause_type_counts,
    conj_type,
    conj_type_counts,
    null_counts,
    max_null_percent,
):
    """
    Checks query clause types to see if they are within the target distributions
    Returns reject_sample True/False
    """
    # Clause types
    if query_type == "FiltersQA":
        for clause_type in clause_types:
            target_percentage = configs[query_type]["clause_types"][clause_type]
            actual_percentage = (clause_type_counts.get(clause_type, 0) + 1) / (
                clause_type_counts["total_clauses"] + 1
            )
            if actual_percentage > target_percentage:
                return False

    # AND and NONE conjunctions
    if (args.num_clauses > 1) and (configs[query_type].get("operator_probs", False)):
        target_percentage = configs[query_type]["operator_probs"][conj_type]
        actual_percentage = (conj_type_counts.get(conj_type, 0) + 1) / (
            conj_type_counts["total_samples"] + 1
        )
        if actual_percentage > target_percentage:
            return False

    # NULL answers
    is_null = False
    if (not memids) or (memids[0] == NULL_MEMID):
        is_null = True
        actual_percentage = (null_counts["null_samples"] + 1) / (
            null_counts["total_samples"] + 1
        )
        if actual_percentage > max_null_percent:
            return False

    # TODO: sometimes, nearly all the refobjs are true. we should reject some of these
    # is_all = (len(memids[0]) >= len(db_dump['context']['reference_objects'])-2)
    # if is_all:

    # if it gets here, it passed all of the percentage checks and we will use this query
    increment_clause_counts(clause_types, clause_type_counts)
    increment_conjunction_counts(conj_type, conj_type_counts)
    increment_null_counts(is_null, null_counts)
    return True

def find_valid_query(
    args,
    Z,
    memory,
    snapshots,
    encoder,
    configs,
    clause_type_counts,
    conj_type_counts,
    null_counts,
    max_null_percent,
    verbose,
):
    """
    Given a single context memory, this searches for a query that doesn't doesn't go over the target proportions
    """
    search_counter = 0
    while search_counter < 10:  # search 10 different queries
        search_counter += 1
        try:
            db_dump = Z.get_qa(memory=memory, snapshots=snapshots)
        except (ErrorWithResponse, KeyError) as e:
            # print("ERROR: {}".format(e))
            # keep on truckin
            continue

        if not db_dump:
            if verbose:
                print("REJECTED: inactive clause")
            continue

        keep_sample = check_update_proportions(
            args,
            configs["QA"],
            db_dump["memids_and_vals"][0],
            db_dump["sample_query_type"],
            db_dump["sample_clause_types"],
            clause_type_counts,
            db_dump["sample_conjunction_type"],
            conj_type_counts,
            null_counts,
            max_null_percent,
        )

        if not keep_sample:
            if verbose:
                print("REJECTED: incorrect proportions")
            continue

        db_dump["context"]["text"] = get_memory_text(
            memory, db_dump
        )  # move to get_qa ?
        encoded_sample = encoder.encode_all(db_dump)

        return encoded_sample

    # couldn't find a valid query. Move on and generate a new scene
    return False

def main(opts):
    configs = opts.configs

    random.seed(opts.seed)
    torch.manual_seed(opts.seed)
    np.random.seed(opts.seed)

    save_dir, metadata_file_name = maybe_make_save_dir(opts)

    if not opts.tokenizer_path:
        opts.tokenizer_path = save_dir

    if save_dir:
        print(save_dir)

    if not configs.get("WORLD"):
        print_num_choices(opts)
    else:
        world_opts = make_world_args_from_config(configs)
        opts.SL = world_opts.SL
        opts.H = world_opts.H
        print(
            'WARNING using config["WORLD"], ignoring opts.num_names, opts.num_props, opts.SL, etc.'
        )

    encoder = DBEncoder(
        query_encode=opts.query_encode,
        SL=opts.SL,
        COORD_SHIFT=(-opts.SL // 2, -opts.SL // 2, -opts.SL // 2),
        tokenizer=opts.tokenizer,
        tokenizer_path=opts.tokenizer_path,
        remove_instseg_locations=True,
    )
    examples = []
    info = {}

    num_iterations = opts.num_examples * 20

    pbar = None
    if opts.active_world_steps > 0:
        W = WorldBuilder()
    if not opts.disable_tqdm:
        pbar = tqdm(total=opts.num_examples, ncols=50)

    Z = QAZoo(opts, configs)

    clause_type_counts = {"total_clauses": 0}
    conj_type_counts = {"total_samples": 0, "AND": 0, "OR": 0, "NONE": 0}
    null_counts = {"total_samples": 0, "null_samples": 0}
    for i in range(num_iterations):
        world_spec = None
        if configs.get("WORLD"):
            world_opts = make_world_args_from_config(configs)
            world_spec = build_shape_scene(world_opts)

        if opts.active_world_steps > 0:
            a, w, lf, chat = W.instantiate_world_from_spec(configs, opts)
            runner = EpisodeRunner(a, snapshot_freq=50, keep_on_truckin=True)
            N = opts.active_world_steps
            if lf is not None:
                runner.run_episode(
                    min_steps=N, max_steps=N, logical_form=lf, chatstr=chat
                )
            else:
                runner.run_episode(min_steps=N, max_steps=N, no_agent_step=True)
            snapshots = runner.snapshots
            memory = a.memory
        else:
            snapshots = None
            memory = build_memory(opts, world_spec=world_spec)

        Z = QAZoo(opts, configs)

        encoded_sample = find_valid_query(
            opts,
            Z,
            memory,
            snapshots,
            encoder,
            configs,
            clause_type_counts,
            conj_type_counts,
            null_counts,
            opts.max_percent_null,
            opts.verbose,
        )

        if encoded_sample:
            encoded_sample["world_configs"] = {"SL": opts.SL}
            if pbar:
                pbar.update(1)

            examples.append(encoded_sample)
            info = update_data_info(info, encoded_sample)
            if info["num_samples"] == opts.num_examples:
                break

    assert info["num_samples"] == opts.num_examples, "num_samples != opts.num_examples"

    print("{}\n{}\n{}".format(clause_type_counts, conj_type_counts, null_counts))

    if save_dir:
        save_files(examples, save_dir, encoder, opts, info, metadata_file_name)

if __name__ == "__main__":
    parser = get_opts()

    opts = parser.parse_args()
    opts.configs = read_configs(opts.config_file)

    main(opts)


import os
import subprocess
import time
import logging.handlers
# import multiprocessing

def measure_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        elapsed_time = end_time - start_time

        print(f"Function '{func.__name__}' took:")
        print(f"Seconds: {elapsed_time:.2f}")
        print(f"Minutes: {elapsed_time / 60:.2f}")
        print(f"Hours: {elapsed_time / 3600:.2f}")

        return result

    return wrapper

def run_command(command):
    p = subprocess.Popen(command,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT,
                         shell=True)
    return iter(p.stdout.readline, b'')

def run_bash_command(command):
    p = subprocess.Popen(command,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT, shell=True)

    out, err = p.communicate()
    return out

@measure_time
def build_index(filename, currentTime, baseDir):
    """
    Parse the trectext file given, and create an index.
    """
    pathToFolder = baseDir + 'Collections/IndriIndices/'
    if not os.path.exists(pathToFolder):
        os.makedirs(pathToFolder)

    INDRI_BUILD_INDEX = '/lv_local/home/niv.b/indri/bin/IndriBuildIndex'
    CORPUS_PATH = filename
    CORPUS_CLASS = 'trectext'
    MEMORY = '1G'
    INDEX = pathToFolder + currentTime
    STEMMER = 'krovetz'
    if os.path.exists(INDEX):
        run_bash_command('rm -r ' + INDEX)
    command = INDRI_BUILD_INDEX + ' -corpus.path=' + CORPUS_PATH + ' -corpus.class=' + CORPUS_CLASS + ' -index=' + INDEX + ' -memory=' + MEMORY + ' -stemmer.name=' + STEMMER
    out = run_bash_command(command)
    return INDEX

@measure_time
def merge_indices(asrIndex, baseDir, currentTime):
    """
    Merge indices of ASR and ClueWeb09. If MergedIndx exists, it will be deleted.
    """

    INDRI_DUMP_INDEX = '/lv_local/home/niv.b/indri/bin/dumpindex'
    CLUEWEB = f'/lv_local/home/niv.b/cluewebindex'
    pathToFolder = baseDir + 'Collections/'
    MERGED_INDEX = pathToFolder + f'/mergedindex_{currentTime}'
    run_bash_command('rm -r ' + MERGED_INDEX)
    command = INDRI_DUMP_INDEX + ' ' + MERGED_INDEX + ' merge ' + CLUEWEB + ' ' + asrIndex
    out = run_bash_command(command)
    return MERGED_INDEX

@measure_time
def run_ranking_model(mergedIndex, workingSet, currentTime, baseDir):
    """
    workingSet - a file in trec format that dictates which population to work on
    format is: <qid> Q0 <docid> <rank> <score> <experiment name>\n - rank and score arguments can be filled
    arbitrarily they are simply for the desired format

    """
    pathToFolder = baseDir + 'Results/'
    if not os.path.exists(pathToFolder):
        os.makedirs(pathToFolder)
    INDEX = mergedIndex
    WORKING_SET_FILE = workingSet
    # MODEL_DIR = baseDir+"Code/Models/"
    # MODEL_FILE = MODEL_DIR+"model"
    MODEL_FILE = '/lv_local/home/niv.b/content_modification_code-master/rank_models/model_lambdatamart'
    # QUERIES_FILE = '/lv_local/home/niv.b/content_modification_code-master/data/queries_bot_modified_sorted_1.xml'
    QUERIES_FILE = f'/lv_local/home/niv.b/content_modification_code-master/data/query_files/queries_{current_time}.xml'

    FEATURES_DIR = pathToFolder + '/Features/' + currentTime
    if not os.path.exists(FEATURES_DIR):
        os.makedirs(FEATURES_DIR)
    FEATURES_FILE = 'features'

    if not os.listdir(FEATURES_DIR):

        command = baseDir + 'scripts/LTRFeatures ' + QUERIES_FILE + ' -stream=doc -index=' + INDEX + ' -repository=' + INDEX + ' -useWorkingSet=true -workingSetFile=' + WORKING_SET_FILE + ' -workingSetFormat=trec'
        print(command)
        out = run_bash_command(command)
        print(out)
        out = run_command('mv doc*_* ' + FEATURES_DIR)
        print(out)

        if any(file.startswith("doc") for file in os.listdir('/lv_local/home/niv.b/content_modification_code-master')):
            command = f"find /lv_local/home/niv.b/content_modification_code-master -maxdepth 1 -name 'doc*' -exec mv {{}} /lv_local/home/niv.b/content_modification_code-master/Results/Features/{currentTime}/ \\;"
            output = run_bash_command(command)
            print(output.decode('utf-8'))
        else:
            print("No files starting with 'doc' found in the specified directory.")

    command = 'perl ' + baseDir + 'scripts/generate.pl ' + FEATURES_DIR + ' ' + WORKING_SET_FILE
    print(command)
    out = run_bash_command(command)
    print(out)
    command = '/lv_local/home/niv.b/opt/java/jdk1.8.0/bin/java -jar ' + baseDir + 'scripts/RankLib.jar -load ' + MODEL_FILE + ' -rank ' + FEATURES_FILE + ' -score predictions.tmp'
    print(command)
    out = run_bash_command(command)
    print(out)
    command = 'cut -f3 predictions.tmp > predictions'
    print(command)
    out = run_bash_command(command)
    print(out)
    run_bash_command('rm predictions.tmp')
    RANKED_LIST_DIR = pathToFolder + 'RankedLists/'
    if not os.path.exists(RANKED_LIST_DIR):
        os.makedirs(RANKED_LIST_DIR)
    PREDICTIONS_FILE = 'predictions'
    command = 'perl ' + baseDir + '/scripts/order.pl ' + RANKED_LIST_DIR + '/LambdaMART' + currentTime + ' ' + FEATURES_FILE + ' ' + PREDICTIONS_FILE
    print(command)
    out = run_bash_command(command)
    print(out)
    return RANKED_LIST_DIR + '/LambdaMART' + currentTime

# if __name__ == '__main__':
#     workingSet = '/lv_local/home/niv.b/content_modification_code-master/trecs/working_set.trectext'
#     baseDir = '/lv_local/home/niv.b/content_modification_code-master/'
#     currentTime = "1"
#     documents = '/lv_local/home/niv.b/content_modification_code-master/trecs/bot_followup.trectext'
#
#     asrIndex = build_index(documents, currentTime, baseDir)
#     print("build_index done...")
#     mergedIndex = merge_indices(asrIndex, baseDir)
#     # mergedIndex = '/lv_local/home/niv.b/content_modification_code-master/Collections/mergedindex'
#     print("merge_indices done...")
#     res = run_ranking_model(mergedIndex, workingSet, currentTime, baseDir)
#     print("run_ranking_model done...")
#     print(res)
#
#     # res = run_ranking_model('/lv_local/home/niv.b/cluewebindex', workingSet, currentTime, baseDir)
#     x = 1

def main_task(currentTime):
    logger.info("Starting...")
    baseDir = '/lv_local/home/niv.b/content_modification_code-master/'
    documents = f'/lv_local/home/niv.b/content_modification_code-master/trecs/bot_followup_{currentTime}.trectext'
    workingSet = f'/lv_local/home/niv.b/content_modification_code-master/trecs/working_set_{currentTime}.trectext'

    # asrIndex = build_index(documents, currentTime, baseDir)
    # print("build_index done...")
    # logger.info("build_index done...")
    #
    # mergedIndex = merge_indices(asrIndex, baseDir, currentTime)
    # print("merge_indices done...")
    # logger.info("merge_indices done...")
    # time.sleep(10)

    mergedIndex = baseDir + 'Collections/' + f'/mergedindex_{currentTime}' # in case of running only the ranking model
    res = run_ranking_model(mergedIndex, workingSet, currentTime, baseDir)
    print("run_ranking_model done...")
    logger.info("run_ranking_model done...")

    print(res)
    logger.info(f'{res}')

if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
    logger = logging.getLogger('ranking_logger')
    logger.setLevel(logging.DEBUG)
    # num_cores = multiprocessing.cpu_count()
    # pool = multiprocessing.Pool(processes=num_cores)
    # current_times = ["g1"]
    # print(f"running {current_times[0]} model...")
    # pool.map(main_task, current_times)
    # pool.close()
    # pool.join()
    current_time = "llama13btrain"
    print(f'Starting version {current_time}...')
    logger.info(f'Starting version {current_time}...')
    main_task(current_time)


from tkinter import *

from matplotlib.pyplot import text

root = Tk()
root.title("gosu GUI")
root.geometry("640x480") # 가로 * 세로

listbox = Listbox(root, selectmode='extended', height=2)
listbox.insert(0, '사과')
listbox.insert(1, '딸기')
listbox.insert(2, '바나나')
listbox.pack()

def btncmd():
    #삭제
    #listbox.delete(0)

    #갯수 확인
    #print('리스트에는', listbox.size(), '개가 있어요')

    #항목 확인
    print('1번쨰부터 3번쨰까지의 항목 :', listbox.get(0, 2))

btn = Button(root, text='클릭', command=btncmd)
btn.pack()
root.mainloop()


from .base_page import BasePage
from seleniumpagefactory.Pagefactory import WebElement, By

class MainPage(BasePage):
    locators = {
        'sideBarMenu': ('XPATH', "//div[@data-testid='sidebar-draw']"),
        'advancedBtn': ('ID', "btn-search-advanced"),
        'profileBtn': ('ID',"navbar-btn-user-menu"),
        'profileDetailsBtn': ('ID', "navbar-link-profile"),
        'signOutBtn': ('ID', "navbar-link-signout")

    }

    sideBarMenu: WebElement

    def select_from_sidebar(self, menuitem : str):
        for element in self.sideBarMenu.find_elements(By.TAG_NAME, 'a'):
            if element.text.lower() == menuitem.lower():
                self.click(element)
                break

    def select_from_profile(self, item):
        self.click(self.profileBtn)
        if item == "Sign Out":
            self.click(self.signOutBtn)
        elif item == "Profile Details":
            self.click(self.profileDetailsBtn)

    def click_advanced(self):
        self.click(self.advancedBtn)


import sys
from collections import deque

N = int(sys.stdin.readline())
li = [int(sys.stdin.readline()) for _ in range(N)]
ans = 0

li.sort()
deq = deque(li)

while len(deq) > 1 and deq[0] < 0 and deq[1] < 0:  # 둘 다 음수인 경우
    ans += deq[0] * deq[1] if deq[0] * deq[1] > deq[0] + deq[1] else deq[0] + deq[1]
    deq.popleft()
    deq.popleft()

while len(deq) > 1 and deq[-2] > 0 and deq[-1] > 0:# 둘 다 양수
    ans += deq[-2]*deq[-1] if deq[-2] * deq[-1] > deq[-2] + deq[-1] else deq[-2] + deq[-1]
    deq.pop()
    deq.pop()

#현재 음수 0 ~ 1개 0 0~여러개 양수 0 ~ 1개 남아있는 상황

while len(deq) > 1:
    ans += deq[0] * deq[1] if deq[0] * deq[1] > deq[0] + deq[1] else deq[0] + deq[1]
    deq.popleft()
    deq.popleft()

if deq:
    ans += deq[0]

print(ans)


# @file  Reverse Vowels
# @brief Reverse only vowels in a string

# https://leetcode.com/problems/reverse-vowels-of-a-string/

'''
Write a function that takes a string as input and reverse
only the vowels of a string.
Example 1: Given s = "hello", return "holle".
Example 2: Given s = "leetcode", return "leotcede".
Note: The vowels does not include the letter "y".
'''

#Approach 1: Two pointer approach
def reverseVowels(self, s):
  vowset = {'a','e','i','o','u','A','E','I','O','U'}
  lst  = list(s)
  b, e = 0, len(lst) - 1  #use property: len = e - b + 1
  while b < e:
    if    lst[b] not in vowset: b += 1
    elif  lst[e] not in vowset: e -= 1
    else:
      lst[b], lst[e] = lst[e], lst[b] #tupple assignments
      b, e = b + 1, e - 1
  return ''.join(lst)

# "hello", "holle"
# "aA",    "Aa"
# "",      ""


T = int(input())
# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.
for test_case in range(1, T + 1):
    n = int(input())
    cards = [int(i) for i in list(input().strip())]
    dp = [0 for i in range(10)]
    for card in cards:
        dp[card] += 1

    max_indices = [index for index, value in enumerate(dp) if value == max(dp)]

    print(f"#{test_case} {max_indices[-1]} {max(dp)}")


#!/usr/bin/env python3
import subprocess
import re
import os
import time
import sys

MINIMIZE_BG_PAD = 32

TASK_BAR_HEIGHT = 25
LAYOUTS = [
    #/ x, y, w, h
    [[     0, 0, 1,     1 ], [ 1.0/4, 0, 1.0/2, 1 ], [ 1.0/3, 0, 1.0/3, 1 ]], # m-m (maximized / middle)
    [[     0, 0, 1.0/2, 1 ], [     0, 0, 1.0/3, 1 ], [     0, 0, 1.0/4, 1 ]], # m-h (far left)
    [[ 1.0/2, 0, 1.0/2, 1 ], [ 2.0/3, 0, 1.0/3, 1 ], [ 3.0/4, 0, 1.0/4, 1 ]], # m-l (far right)
    [[     0, 0, 3.0/4, 1 ], [     0, 0, 2.0/3, 1 ], [ 1.0/4, 0, 1.0/4, 1 ]], # m-j (middle left)
    [[ 1.0/4, 0, 3.0/4, 1 ], [ 1.0/3, 0, 2.0/3, 1 ], [ 1.0/2, 0, 1.0/4, 1 ]], # m-k (middle right)

    # Upper half
    [[     0, 0, 1,     0.5 ], [ 1.0/4, 0, 1.0/2, 0.5 ], [ 1.0/3, 0, 1.0/3, 0.5 ]], # m-n (maximized / middle)
    [[     0, 0, 1.0/2, 0.5 ], [     0, 0, 1.0/3, 0.5 ], [     0, 0, 1.0/4, 0.5 ]], # m-y (far left)
    [[ 1.0/2, 0, 1.0/2, 0.5 ], [ 2.0/3, 0, 1.0/3, 0.5 ], [ 3.0/4, 0, 1.0/4, 0.5 ]], # m-o (far right)
    [[     0, 0, 3.0/4, 0.5 ], [     0, 0, 2.0/3, 0.5 ], [ 1.0/4, 0, 1.0/4, 0.5 ]], # m-u (middle left)
    [[ 1.0/4, 0, 3.0/4, 0.5 ], [ 1.0/3, 0, 2.0/3, 0.5 ], [ 1.0/2, 0, 1.0/4, 0.5 ]], # m-i (middle right)

    # Lower half
    [[     0, 0.5, 1,     0.5 ], [ 1.0/4, 0.5, 1.0/2, 0.5 ], [ 1.0/3, 0.5, 1.0/3, 0.5 ]], # m-sh-n (maximized / middle)
    [[     0, 0.5, 1.0/2, 0.5 ], [     0, 0.5, 1.0/3, 0.5 ], [     0, 0.5, 1.0/4, 0.5 ]], # m-sh-y (far left)
    [[ 1.0/2, 0.5, 1.0/2, 0.5 ], [ 2.0/3, 0.5, 1.0/3, 0.5 ], [ 3.0/4, 0.5, 1.0/4, 0.5 ]], # m-sh-o (far right)
    [[     0, 0.5, 3.0/4, 0.5 ], [     0, 0.5, 2.0/3, 0.5 ], [ 1.0/4, 0.5, 1.0/4, 0.5 ]], # m-sh-u (middle left)
    [[ 1.0/4, 0.5, 3.0/4, 0.5 ], [ 1.0/3, 0.5, 2.0/3, 0.5 ], [ 1.0/2, 0.5, 1.0/4, 0.5 ]], # m-sh-i (middle right)
]

g_monitor_whxys = []

def run(cmd):
    lines = subprocess.check_output(cmd, shell=True).decode('utf-8').strip().split('\n')
    return [re.sub(r'\s+', ' ', l.strip()).split(' ') for l in lines]

def get_global_monitor_whxys():
    global g_monitor_whxys
    vals = run(r"xrandr | grep ' connected' | grep -v 'connected (' | sed 's/primary //g'")
    g_monitor_whxys = [[int(x) for x in re.sub(r'[x+]', ' ', val[2]).split(' ')] for val in vals]

def get_active_win_id():
    return int(re.sub(',', '', run('xprop -root _NET_ACTIVE_WINDOW')[0][4]), 16)

def get_vdesktop_id(win_id):
    return int(run("wmctrl -l | grep "+format(win_id,'x'))[0][1])

def get_all_win_ids():
    return [int(x[0], 16) for x in run("wmctrl -l")]

def is_window_minimized(win_id):
    return run('xwininfo -id '+hex(win_id)+' | grep "Map State:"')[0][2] == 'IsUnMapped'

def minimize_window(win_id):
    run('xdotool windowminimize ' + hex(win_id))

def get_monitor_index_for_point(x, y):
    for i in range(len(g_monitor_whxys)):
        mw, mh, mx, my = g_monitor_whxys[i]
        if x >= mx and x <= mx + mw and y >= my and y <= my + mh:
            return i
    return 0

def get_monitor_index_for_win_id(win_id):
    dims = get_win_dimensions(win_id)
    x = dims['cx']
    y = dims['cy']
    for i in range(len(g_monitor_whxys)):
        mw, mh, mx, my = g_monitor_whxys[i]
        if x >= mx and x <= mx + mw and y >= my and y <= my + mh:
            return i
    return 0

def get_win_dimensions(id):
    lines = run('xwininfo -id '+hex(id)+' | grep -E "upper-left|Width:|Height:"')
    win = [int(x[-1]) for x in lines]
    woff = 2 * win[2]
    hoff = win[2] + win[3]
    ox = win[0] - win[2]
    oy = win[1] - win[3]
    ow = win[4] + woff
    oh = win[5] + hoff
    cx = ox + ow / 2
    cy = oy + oh / 2
    return { "woff":woff, "hoff":hoff, "ox":ox, "oy":oy, "ow":ow, "oh":oh, "cx":cx, "cy":cy }

def convert_dims_to_layout(dims, mw, mh, mx, my):
    return [ float(dims['ox']-mx)/mw, float(dims['oy']-my)/mh, float(dims['ow'])/mw, float(dims['oh'])/mh ]

def win_dimensions_intersect(dims0, dims1, padding):
    l0 = dims0['ox'] + padding
    r0 = dims0['ox'] + dims0['ow'] - padding
    t0 = dims0['oy'] + padding
    b0 = dims0['oy'] + dims0['oh'] - padding
    l1 = dims1['ox'] + padding
    r1 = dims1['ox'] + dims1['ow'] - padding
    t1 = dims1['oy'] + padding
    b1 = dims1['oy'] + dims1['oh'] - padding
    if r0 < l1 or r1 < l0: return False
    if b0 < t1 or b1 < t0: return False
    return True

def move_window(id, xywh_args):
    run(r'wmctrl -i -r "'+hex(id)+'" -e "0,'+','.join([str(x) for x in xywh_args])+'"')

def get_visible_other_windows(this_win_id):
    this_vd_id = get_vdesktop_id(this_win_id)
    this_mon_index = get_monitor_index_for_win_id(this_win_id)
    ret = []
    for win_id in get_all_win_ids():
        if win_id == this_win_id or get_vdesktop_id(win_id) != this_vd_id or is_window_minimized(win_id):
            continue
        if this_mon_index != get_monitor_index_for_win_id(win_id):
            continue
        ret.append(win_id)
    return ret

def get_fill_layout(this_layout, other_layout):
    if other_layout[0] < this_layout[0]:
        return [0, 0, this_layout[0], 1]
    else:
        return [this_layout[0] + this_layout[2], 0, 1.0 - this_layout[0] - this_layout[2], 1]

def run_minimize_bg():
    this_win_id = get_active_win_id()
    this_dims = get_win_dimensions(this_win_id)
    for win_id in get_visible_other_windows(this_win_id):
        if win_dimensions_intersect(this_dims, get_win_dimensions(win_id), MINIMIZE_BG_PAD):
            minimize_window(win_id)

def run_fill_rest():
    this_win_id = get_active_win_id()
    this_dims = get_win_dimensions(this_win_id)
    monitor_index = get_monitor_index_for_point(this_dims['cx'], this_dims['cy'])
    mw, mh, mx, my = g_monitor_whxys[monitor_index]
    mh -= TASK_BAR_HEIGHT
    this_layout = convert_dims_to_layout(this_dims, mw, mh, mx, my)

    for win_id in get_visible_other_windows(this_win_id):
        other_dims = get_win_dimensions(win_id)
        other_layout = convert_dims_to_layout(other_dims, mw, mh, mx, my)
        layout = get_fill_layout(this_layout, other_layout)
        run_layout_or_next_monitor(win_id, layout)

def run_layout_or_next_monitor(win_id, maybe_layout):
    dims = get_win_dimensions(win_id)

    monitor_index = get_monitor_index_for_point(dims['cx'], dims['cy'])

    if maybe_layout == None:
        monitor_index = (monitor_index + 1) % len(g_monitor_whxys)

    mw, mh, mx, my = g_monitor_whxys[monitor_index]
    mh -= TASK_BAR_HEIGHT

    if maybe_layout == None:
        layout = convert_dims_to_layout(dims, mw, mh, mx, my)
    else:
        layout = maybe_layout

    nx = int( mx + layout[0] * mw )
    ny = int( my + layout[1] * mh )
    nw = int( layout[2] * mw ) - dims['woff']
    nh = int( layout[3] * mh ) - dims['hoff']
    move_window(win_id, [nx, ny, nw, nh])

def run_next_monitor():
    run_layout_or_next_monitor(get_active_win_id(), None)

def run_snap(new_index):
    new_time = time.time()
    new_subindex = 0
    last_time = 0
    last_index = 0
    last_subindex = 0

    if not os.path.exists('/tmp/divvy.state'):
        with open('/tmp/divvy.state', 'w') as writer:
            writer.write('0,-1,-1')

    with open('/tmp/divvy.state', 'r') as reader:
        parts = reader.read().split(',')
        last_time = float(parts[0])
        last_index = int(parts[1])
        last_subindex = int(parts[2])

    if new_index == last_index and new_time - last_time < 2:
        new_subindex = last_subindex + 1

    with open('/tmp/divvy.state', 'w') as writer:
        writer.write(','.join([ str(new_time), str(new_index), str(new_subindex) ]))

    layout = LAYOUTS[new_index][new_subindex % len(LAYOUTS[new_index])]

    run_layout_or_next_monitor(get_active_win_id(), layout)

def main():
    get_global_monitor_whxys()
    if sys.argv[1] == 'next-monitor':
        run_next_monitor()
    elif sys.argv[1] == 'minimize-bg':
        run_minimize_bg()
    elif sys.argv[1] == 'fill-rest':
        run_fill_rest()
    else:
        run_snap(int(sys.argv[1]))

if __name__ == "__main__":
    main()


from InstagramAPI import InstagramAPI
import pickle

if __name__ == "__main__":
    with open("stored_object.pickle", "rb") as pkl:
        i_api = pickle.load(pkl)

    i_api.searchUsername('serj.cool_esh')
    print(i_api.LastJson)


# %%
import os
from keras.preprocessing.sequence import pad_sequences
import tensorflow as tf
import pickle
# %%
path = os.path.join('NLP_Stuff', 'model.h5')
model = tf.keras.models.load_model(path)

path = os.path.join('NLP_Stuff', 'tokenizer.pkl')
with open(path, 'rb') as f:
    tokenizer = pickle.load(f)
# %%

def predict_sentiment(text):
    # preprocessing the given text
    text_seq = tokenizer.texts_to_sequences(text)
    text_pad = pad_sequences(text_seq, maxlen=200)

    # predicting the class
    predicted_sentiment = model.predict(text_pad).round()

    print(model.predict(text_pad))

    if predicted_sentiment == 1.0:
        return(print('It is a positive sentiment'))
    else:
        return(print('It is a negative sentiment'))

# # %%
# text = ['hahahahahaha funny cute']
# predict_sentiment(text)
# # %%%%
# x = ['no one cares about me. i will die alone']
# predict_sentiment(x)

# %%


# if sencillo
x = "fade"
y = input("enter the word")

if(x == y):
    print(" x and y are equal")
else:
    print(" x is NOT equal y")

#el-if
a = 4
b = 5
c = 6

if(x==y):
    print("x and y are equal")
elif(x>y):
    print("x is greater than y")
else:
    print("x is less than y")


# Imports
import Protests_Functions as pf
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from collections import Counter

def count_genderfreq(text, dictionaryIndicators):
    indicators = []
    for word in text:
        if word in dictionaryIndicators:
            indicators.append(word)
    return len(indicators)

# Variables
farleft_file = 'C:/Users/khahn/PycharmProjects/NLP Protests/article database/Protests Links - Far Left.csv'
left_file = 'C:/Users/khahn/PycharmProjects/NLP Protests/article database/Protests Links - Left.csv'
center_file = 'C:/Users/khahn/PycharmProjects/NLP Protests/article database/Protests Links - Center.csv'
right_file = 'C:/Users/khahn/PycharmProjects/NLP Protests/article database/Protests Links - Right.csv'
farright_file = 'C:/Users/khahn/PycharmProjects/NLP Protests/article database/Protests Links - Far Right.csv'

genderDict = {'male indicators': ['male', 'man', 'men', 'he', 'his', 'him', 'boy', 'boys'], 'female indicators':
    ['female', 'woman', 'women', 'she', 'her', 'hers', 'girl', 'girls']}
dictionaryNames = ['male indicators', 'female indicators']

# Frequency of the words in the categories of article
# Get the text from all the articles per political ideology
farleft_text = pf.open_file(farleft_file)
left_text = pf.open_file(left_file)
center_text = pf.open_file(center_file)
right_text = pf.open_file(right_file)
farright_text = pf.open_file(farright_file)
all_text = farleft_text + left_text + farright_text
print('got all the text')

all_indicatorsm = count_genderfreq(all_text, genderDict['male indicators'])
farleft_indicatorsm = count_genderfreq(farleft_text, genderDict['male indicators'])
left_indicatorsm = count_genderfreq(left_text, genderDict['male indicators'])
center_indicatorsm = count_genderfreq(center_text, genderDict['male indicators'])
right_indicatorsm = count_genderfreq(right_text, genderDict['male indicators'])
farright_indicatorsm = count_genderfreq(farright_text, genderDict['male indicators'])

all_indicatorsf = count_genderfreq(all_text, genderDict['female indicators'])
farleft_indicatorsf = count_genderfreq(farleft_text, genderDict['female indicators'])
left_indicatorsf = count_genderfreq(left_text, genderDict['female indicators'])
center_indicatorsf = count_genderfreq(center_text, genderDict['female indicators'])
right_indicatorsf = count_genderfreq(right_text, genderDict['female indicators'])
farright_indicatorsf = count_genderfreq(farright_text, genderDict['female indicators'])
print('got all the indicators')

maleFreq = [farleft_indicatorsm, left_indicatorsm, center_indicatorsm, right_indicatorsm, farright_indicatorsm]
femaleFreq = [farleft_indicatorsf, left_indicatorsf, center_indicatorsf, right_indicatorsf, farright_indicatorsf]
frequency = [farleft_indicatorsm, left_indicatorsm, center_indicatorsm, right_indicatorsm, farright_indicatorsm, farleft_indicatorsf, left_indicatorsf, center_indicatorsf, right_indicatorsf, farright_indicatorsf]
words = ['Male gender', 'Male gender', 'Male gender', 'Male gender', 'Male gender', 'Female gender', 'Female gender',
         'Female gender', 'Female gender', 'Female gender']
leaning = ['Far left', 'Left', 'Center', 'Right', 'Far Right', 'Far left', 'Left', 'Center', 'Right', 'Far Right']

all_info = [words, frequency, leaning]
df = pd.DataFrame(all_info).transpose()
df.columns = ['Words', 'Frequency', 'Political Leaning']
print('made the dataframe')

plot = sns.catplot(x='Words',y='Frequency',hue='Political Leaning', data=df, kind='bar')
#plot.set_title('Frequency of Gender Words from Newspapers across the Political Spectrum Covering the Black Lives Matter Protests')
plt.show()


"""
Find lost element from a duplicated array
Given two arrays which are duplicates of each other except one element,
that is one element from one of the array is missing,
we need to find that missing element.
"""
def lost_element_duplicate_array(arr1, arr2):
    res = 0
    for i in range(len(arr1)):
        res ^= arr1[i]
    for i in range(len(arr2)):
        res ^= arr2[i]
    return res

def main():
    arr1 = [9, 4, 5]
    arr2 = [4, 5, 7, 9]
    print(lost_element_duplicate_array(arr1, arr2))
main()

Searching_an_array/Bitwise XOR/Lost Element from duplicated array.py


import re
import os
import json
import scrapy
import datetime
from pathlib import Path
from dotenv import load_dotenv

try:
    load_dotenv()
except:
    env_path = Path(".env")
    load_dotenv(dotenv_path=env_path)
class SephoraUKPdpSpider(scrapy.Spider):
    name = 'sephora_uk_pdp_weekly'
    start_urls = ['https://www.sephora.co.uk/']
    CURRENT_DATETIME = datetime.datetime.now()
    CURRENT_DATE = CURRENT_DATETIME.strftime("%Y-%m-%d")
    DATE=CURRENT_DATE.replace("-","_")

    ROTATING_PROXY = os.getenv("ROTATING_PROXY")
    custom_settings={
        # 'FEEDS' : {f"s3://scraping-external-feeds-lapis-data/{CURRENT_DATE}/sephora_uk/%(name)s_{DATE}.json": {"format": "json",}},

    "CONCURRENT_REQUESTS":64,
    'ROTATING_PROXY_LIST' : [ROTATING_PROXY],
    "HTTPCACHE_ENABLED" : True,
    "HTTPCACHE_DIR" : 'httpcache',
    'HTTPCACHE_EXPIRATION_SECS':79200,
    "HTTPCACHE_IGNORE_HTTP_CODES":[502],
    "HTTPCACHE_STORAGE" : "scrapy.extensions.httpcache.FilesystemCacheStorage",
    }
    def parse(self, response):
        spider_name = SephoraUKPdpSpider.name.replace('pdp_weekly','categories')
        current_date = datetime.datetime.now().strftime("%Y-%m-%d")
        category_path = os.getcwd() + f'/exports/{spider_name}/{spider_name}_{current_date}.json'
        with open(category_path,'r',encoding='utf-8-sig') as f:
            json_file = f.read()
        category_names = json.loads(json_file)
        for main_cat in category_names:
            category_name = main_cat.get('name','').title()
            category_url = main_cat.get('url','')
            for main_sub_cat in main_cat['category_crumb']:
                if 'category_crumb' in (main_sub_cat).keys():
                    main_category = main_sub_cat.get('name','').title()
                    main_category_url = main_sub_cat.get('url','')
                    for sub_cat in main_sub_cat['category_crumb']:
                        sub_category = sub_cat.get('name','').title()
                        sub_cat_url = sub_cat.get('url','')
                        yield scrapy.Request(url=(sub_cat_url),callback=self.parse_list,dont_filter=True,cb_kwargs={"category_name":category_name,"category_url":category_url,"main_category":main_category,"main_category_url":main_category_url,"sub_category":sub_category,"sub_cat_url":sub_cat_url})
                else:
                    main_category = main_sub_cat.get('name','').title()
                    main_category_url = main_sub_cat.get('url','')
                    sub_category = ''
                    sub_cat_url = ""
                    yield scrapy.Request(url=(main_category_url),callback=self.parse_list,dont_filter=True,cb_kwargs={"category_name":category_name,"category_url":category_url,"main_category":main_category,"main_category_url":main_category_url,"sub_category":sub_category,"sub_cat_url":sub_cat_url})

    def parse_list(self,response,category_name,category_url,main_category,main_category_url,sub_category,sub_cat_url):
        if response.xpath('//div[@class="eba-component eba-product-listing"]/div[contains(@class,"Product")]/a/@href'):
            for product_list_xpath in response.xpath('//div[@class="eba-component eba-product-listing"]/div[contains(@class,"Product")]/a'):
                product_url =  product_list_xpath.xpath('./@href').get()
                yield scrapy.Request(url=response.urljoin(product_url),callback=self.product_detail,dont_filter=True,cb_kwargs={"category_name":category_name,"category_url":category_url,"main_category":main_category,"main_category_url":main_category_url,"sub_category":sub_category,"sub_cat_url":sub_cat_url})
        nexpage_url = response.xpath('//div[@class="loadMore loadMoreBottom"]/a/@href').get()
        if nexpage_url:
           yield scrapy.Request(url=response.urljoin(nexpage_url),callback=self.parse_list,dont_filter=True,cb_kwargs={"category_name":category_name,"category_url":category_url,"main_category":main_category,"main_category_url":main_category_url,"sub_category":sub_category,"sub_cat_url":sub_cat_url})
    async def product_detail(self,response,category_name,category_url,main_category,main_category_url,sub_category,sub_cat_url):
        item = {}
        item['url'] = response.url
        category_crumb = []
        main_cat = {}
        main_cat['name'] = category_name
        main_cat['url'] = category_url
        category_crumb.append(main_cat)
        sub_main_cat = {}
        sub_main_cat['name'] = main_category
        sub_main_cat['url'] = main_category_url
        category_crumb.append(sub_main_cat)
        if sub_category and sub_cat_url:
            sub_cat = {}
            sub_cat['name'] = sub_category
            sub_cat['url'] = sub_cat_url
            category_crumb.append(sub_cat)
        item['category_crumb'] = category_crumb
        if response.xpath('//h1/span[@class="pdp-product-brand-name"]/text()').get('').strip():
            item['name'] = response.xpath('//h1/span[@class="pdp-product-brand-name"]/text()').get('').strip()
            item['subtitle'] = None
            image_url_list = list(set(response.xpath("//div[contains(@class,'productpage-gallery')]/div/a/@href|//div[contains(@class,'productpage-image')]/img/@src").getall()))
            image_urls = [ url.replace(' ','%20') for url in image_url_list if not 'youtube' in url ]
            image_urls = [ url.replace(' ','%20') for url in image_urls if not 'player.' in url ]
            video_url = [ url for url in image_url_list if 'youtube' in url ]
            video_url_player = [ url for url in image_url_list if 'player.' in url ]
            if video_url_player:
                video_url.extend(video_url_player)
            item['image_url'] = image_urls
            item['has_video'] = False
            item["video"] = []
            if video_url:
                item['has_video'] = True
                video_urls = []
                for video_url_http in video_url:
                    if not 'http' in video_url_http:
                        video_url_http = f'https:{video_url_http}'
                        video_urls.append(video_url_http)
                    else:
                        video_urls.append(video_url_http)
                item["video"] = video_urls
            item['brand'] = None
            if re.search(r'<script\s*type\=\"application\/ld\+json\"[^>]*?>[\w\W]*?\"brand\"\:\s*\"([^>]*?)\"[^>]*?<\/script>',response.text):
                item['brand'] = re.findall(r'<script\s*type\=\"application\/ld\+json\"[^>]*?>[\w\W]*?\"brand\"\:\s*\"([^>]*?)\"[^>]*?<\/script>',response.text)[0]
            item['master_product_id'] = None
            item['gtin'] = None
            if  re.search('\"data\"\:\[\"([^>]*?)\"\]',response.text):
                item['master_product_id'] = re.findall('\"data\"\:\[\"([^>]*?)\"\]',response.text)[0]
            if re.search(r'data\-flix\-ean\=\"([^>]*?)\"',response.text):
                gtin = re.findall(r'data\-flix\-ean\=\"([^>]*?)\"',response.text)[0]
                item['gtin'] = gtin if gtin != "" else None

            in_stock = response.xpath('//span[@class="product-options-stock u-error"]/text()|//div[contains(@class,"stock-level")]/text()|//span[@class="product-options-stock"]/text()|//div[@class="sub-products"]/span[@class="option selected"]/span/span[contains(@class,"priceStock")]/span[2]/text()').get("")
            item['in-stock'] = True if 'in stock' in in_stock.lower().strip() else False

            item['price'] = None
            if response.xpath('//p[@class="price-info"]/span/span/text()'):
                item['price'] = ''.join(response.xpath('//p[@class="price-info"]/span/span/text()').getall()).strip()
            price_before = response.xpath('//p[@class="price-info"]/span/span[@class="Price-details"]/span[@class="rrp"]/text()').get('').strip()
            item['price_before'] = price_before if price_before else None
            promo_label = response.xpath('//div[@class="discountWrapper"]/span/text()').get('').strip()
            item['promo_label'] = promo_label if promo_label else None
            prices = []
            for variant_block in response.xpath('//div[@class="product-detail-information productpage-buy"]//div[@class="sub-products"]/span'):
                variant_dict = {}
                variant_dict['sku_id'] = variant_block.xpath('./@data-sku').get()
                variant_dict['gtin'] = item['gtin']
                in_stock = variant_block.xpath('./span/span[@class="priceStock "]/span[2]/text()').get('')
                variant_dict['in-stock'] = True if 'in stock' in in_stock.lower().strip() else False
                variant_dict['image_url'] = image_urls
                variant_dict['has_video'] = item['has_video']
                variant_dict['video'] = item["video"]
                variant_price = variant_block.xpath('./span/span[contains(@class,"priceStock")]/span[1]/text()').get()
                variant_dict['price'] = variant_price.strip() if variant_price else None
                variant_dict['price_before'] = item['price_before']
                variant_dict['promo_label'] = item['promo_label']
                variant_dict['variant_url'] = response.url
                variant_dict['data_color'] = variant_block.xpath('./span/span[@class="name"]/text()').get()
                variant_dict['data_size'] = None
                prices.append(variant_dict)
            item['prices'] = prices
            description = ' '.join(response.xpath('//section[@id="information"]/div//text()').getall())
            description = re.sub(r'\s+',' ',description)
            item['description'] = description.strip() if description else None

            pass_key_url = 'https://display.ugc.bazaarvoice.com/static/sephora-uk/main_site/en_GB/bvapi.js'
            pass_key_response = await self.requests_process(pass_key_url)
            pass_key,display_code='',''
            if re.search(r'passkey\:\"([^>]*?)\"',pass_key_response.text):
                pass_key = re.findall(r'passkey\:\"([^>]*?)\"',pass_key_response.text)[0]
            if re.search(r'displaycode\:\"([^>]*?)\"',pass_key_response.text):
                display_code = re.findall(r'displaycode\:\"([^>]*?)\"',pass_key_response.text)[0]

            review_url = f'https://api.bazaarvoice.com/data/batch.json?passkey={pass_key}&apiversion=5.5&displaycode={display_code}&resource.q0=products&filter.q0=id%3Aeq%3A{item["master_product_id"]}&stats.q0=reviews&filteredstats.q0=reviews&filter_reviews.q0=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&filter_reviewcomments.q0=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&resource.q1=reviews&filter.q1=isratingsonly%3Aeq%3Afalse&filter.q1=productid%3Aeq%3A{item["master_product_id"]}&filter.q1=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&sort.q1=relevancy%3Aa1&stats.q1=reviews&filteredstats.q1=reviews&include.q1=authors%2Cproducts%2Ccomments&filter_reviews.q1=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&filter_reviewcomments.q1=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&filter_comments.q1=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&limit.q1=100&offset.q1=0&limit_comments.q1=3&callback=BV._internal.dataHandler0'
            review_response = await self.requests_process(review_url)
            review_list = []
            if re.search(r'BV\._internal\.dataHandler0\(([^>]*?)\)$',review_response.text):
                review_block = re.findall(r'BV\._internal\.dataHandler0\(([^>]*?)\)$',review_response.text)[0]
                review_json = json.loads(review_block)
                review_list = self.review(review_json,review_list)
                count = review_json.get('BatchedResults').get('q1').get('TotalResults')
                count = count if count else 0
                for page_count in range(1,round(int(count)/100)+1):
                    review_next_page_url = f'https://api.bazaarvoice.com/data/batch.json?passkey={pass_key}&apiversion=5.5&displaycode={display_code}&resource.q0=products&filter.q0=id%3Aeq%3A{item["master_product_id"]}&stats.q0=reviews&filteredstats.q0=reviews&filter_reviews.q0=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&filter_reviewcomments.q0=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&resource.q1=reviews&filter.q1=isratingsonly%3Aeq%3Afalse&filter.q1=productid%3Aeq%3A{item["master_product_id"]}&filter.q1=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&sort.q1=relevancy%3Aa1&stats.q1=reviews&filteredstats.q1=reviews&include.q1=authors%2Cproducts%2Ccomments&filter_reviews.q1=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&filter_reviewcomments.q1=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&filter_comments.q1=contentlocale%3Aeq%3Aen*%2Cfr*%2Cen_GB&limit.q1=100&offset.q1={100*page_count}&limit_comments.q1=3&callback=BV._internal.dataHandler0'
                    next_page_review_response = await self.requests_process(review_next_page_url)
                    if re.search(r'BV\._internal\.dataHandler0\(([^>]*?)\)$',next_page_review_response.text):
                        next_review_block = re.findall(r'BV\._internal\.dataHandler0\(([^>]*?)\)$',next_page_review_response.text)[0]
                        next_review_json = json.loads(next_review_block)
                        review_list = self.review(next_review_json,review_list)

            item["reviews"] = review_list
            yield item

    def review(self,response,review_list):
        for review_values in response.get('BatchedResults',{}).get('q1',{}).get('Results'):
            review_dict = {}
            review_dict['user'] = review_values.get('UserNickname')
            review_dict['date'] = review_values.get('SubmissionTime','').split('T')[0]
            review_dict['stars'] = review_values.get('Rating')
            review_title = review_values.get('Title')
            review_body = review_values.get('ReviewText')
            review_dict['review'] = f"[{review_title}] {review_body}"
            review_list.append(review_dict)
        return review_list

    async def requests_process(self,url):
        request = scrapy.Request(url)
        response = await self.crawler.engine.download(request, self)
        return response


import json
import math
from collections import defaultdict

from google.protobuf.wrappers_pb2 import BoolValue, UInt64Value, StringValue, DoubleValue

from connectors.integrations.datadog import DatadogConnector
from connectors.integrations.newrelic import NewRelicConnector

from event.clickhouse.models import Events
from event.engine.metric_engine import process_metric_expressions
from event.workflows.workflow_utils import get_metric_key_context, get_event_metric_expr_query, \
    get_transaction_metric_expr_query
from protos.event.entity_pb2 import WorkflowView

class Node:

    def __init__(self, event_type_name, event_type_id):
        self.name = event_type_name
        self.id = event_type_id
        self.has_in_connections = False
        self.has_out_connections = False
        self.metrics = []
        self.status = WorkflowView.NodeStatus.GOOD
        self.workflow_node_config = None

    def mark_in_connection(self):
        self.has_in_connections = True

    def mark_out_connection(self):
        self.has_out_connections = True

    def add_metric(self, metric):
        self.metrics.append(metric)

    def set_status(self, status):
        self.status = status

    def get_proto(self):
        conn_types = []

        if self.has_in_connections:
            conn_types.append(WorkflowView.NodeConnectionType.IN)
        if self.has_out_connections:
            conn_types.append(WorkflowView.NodeConnectionType.OUT)

        return WorkflowView.Node(
            node_id=UInt64Value(value=self.id), label=StringValue(value=self.name),
            status=self.status,
            connection_types=conn_types,
            metrics=self.metrics,
            workflow_node_config=StringValue(value=json.dumps(self.workflow_node_config)),
        )

class Edge:

    def __init__(self, start: Node, end: Node):
        self.start = start
        self.end = end
        start.mark_out_connection()
        end.mark_in_connection()

    def __str__(self):
        return "{} - {} (Count: {})".format(self.start.name, self.end.name, self.counter)

    def print(self):
        print("{} -> {} ({}, {})".format(self.start.name, self.end.name, len(self.owners), self.owners[:1]))

    def get_proto(self):
        return WorkflowView.Edge(
            start_node_id=UInt64Value(value=self.start.id),
            end_node_id=UInt64Value(value=self.end.id),
            metrics=[],
        )

class WorkflowBuilder:

    def __init__(self, dtr, account):
        self.nodes = []
        self.edges = []
        self.dtr = dtr
        self.account = account
        self.dd_connector = None
        self.nr_connector = None

    def get_metric_from_datadog(self, metric_expr, compare_to=None):
        metric_value, delta, delta_type = None, None, None

        self.dd_connector = DatadogConnector(self.dtr.to_tr(), self.account.id)
        metric_value_json = self.dd_connector.fetch_metric(metric_expr)
        metric_value_compare = metric_value_json.get('value')
        if metric_value_compare is not None:
            metric_value = "{} {}".format(metric_value_json.get('value'), metric_value_json.get('unit'))
        else:
            metric_value = None

        if compare_to:
            prev_dtr = self.dtr.get_prev_dtr(compare_to)
            prev_metric_value_json = self.dd_connector.fetch_metric(metric_expr, prev_dtr.to_tr())
            prev_metric_value_compare = prev_metric_value_json.get('value')
            if metric_value_compare and not prev_metric_value_compare:
                delta = 100
                delta_type = WorkflowView.DeltaType.UP
            elif prev_metric_value_compare and not metric_value_compare:
                delta = 100
                delta_type = WorkflowView.DeltaType.DOWN
            elif not prev_metric_value_compare and not metric_value_compare:
                delta = None
                delta_type = None
            else:
                delta = abs(round((metric_value_compare / prev_metric_value_compare) - 1.0, 2)) * 100
                if metric_value_compare >= prev_metric_value_compare:
                    delta_type = WorkflowView.DeltaType.UP
                else:
                    delta_type = WorkflowView.DeltaType.DOWN

        return metric_value, delta, delta_type

    def get_metric_from_drdroid(self, metric_expr, compare_to=None):
        metric_value, delta, delta_type = None, None, None

        aggregation_type = metric_expr.split(':')[0]
        aggregation_field = metric_expr.split(':')[1].split('{')[0]
        filters = list({'lhs': x.split(':')[0], 'rhs': x.split(':')[1]} for x in metric_expr.split('{')[1].split('}')[0].split(','))

        aggregation_object = aggregation_field.split('.')[0]
        metric_expr_query = None
        if aggregation_object == 'event':
            metric_expr_query = get_event_metric_expr_query(aggregation_type, aggregation_field, filters, self.account.id, self.dtr)
        if aggregation_object == 'transaction':
            metric_expr_query = get_transaction_metric_expr_query(aggregation_type, aggregation_field, filters, self.account.id, self.dtr)

        if metric_expr_query:
            qs = Events.objects.raw(metric_expr_query)
            metric_value = list(qs)[0].id
            metric_value = round(metric_value, 2)

            if compare_to:
                prev_dtr = self.dtr.get_prev_dtr(compare_to)
                prev_metric_expr_query = None
                if aggregation_object == 'event':
                    prev_metric_expr_query = get_event_metric_expr_query(aggregation_type, aggregation_field, filters,
                                                                    self.account.id, prev_dtr)
                if aggregation_object == 'transaction':
                    prev_metric_expr_query = get_transaction_metric_expr_query(aggregation_type, aggregation_field, filters,
                                                                          self.account.id, prev_dtr)

                prev_qs = Events.objects.raw(prev_metric_expr_query)
                prev_metric_value = list(prev_qs)[0].id
                if metric_value and not prev_metric_value:
                    delta = 100
                    delta_type = WorkflowView.DeltaType.UP
                elif prev_metric_value and not metric_value:
                    delta = 100
                    delta_type = WorkflowView.DeltaType.DOWN
                elif not prev_metric_value and not metric_value:
                    delta = None
                    delta_type = None
                else:
                    delta = abs(round((metric_value / prev_metric_value) - 1.0, 2)) * 100
                    if metric_value >= prev_metric_value:
                        delta_type = WorkflowView.DeltaType.UP
                    else:
                        delta_type = WorkflowView.DeltaType.DOWN

        return metric_value, delta, delta_type

    def process_workflow_config(self, workflow_config):

        compare_to = workflow_config.get('compare_to')
        nodes = workflow_config.get('nodes')

        for idx, node in enumerate(nodes):
            name = node.get('name')
            metrics = node.get('metrics')
            wb_node = Node(name, idx)

            for metric in metrics:
                metric_name = metric.get('name')
                metric_source = metric.get('source')
                metric_expr = metric.get('expr')

                metric_value, delta, delta_type = None, None, None

                if metric_source == 'Datadog':
                    metric_value, delta, delta_type = self.get_metric_from_datadog(metric_expr, compare_to)
                if metric_source == 'DrDroid':
                    metric_value, delta, delta_type = self.get_metric_from_drdroid(metric_expr, compare_to)
                if metric_source == 'Newrelic':
                    metric_value, delta, delta_type = self.get_metric_from_newrelic(metric_expr, compare_to)

                metric_status = WorkflowView.MetricStatus.GREEN
                if delta_type:
                    metric_context = get_metric_key_context(metric_name)

                    if metric_context == 'up' and delta_type == WorkflowView.DeltaType.DOWN:
                        metric_status = WorkflowView.MetricStatus.RED
                    if metric_context == 'down' and delta_type == WorkflowView.DeltaType.UP:
                        metric_status = WorkflowView.MetricStatus.RED

                if metric_status == WorkflowView.MetricStatus.RED and delta and delta > 15.0:
                    wb_node.set_status(WorkflowView.NodeStatus.BAD)

                wb_node.add_metric(WorkflowView.Node.NodeMetric(name=StringValue(value=metric_name),
                                                                      value=StringValue(value=str(metric_value)),
                                                                      metric_status=metric_status,
                                                                      delta=DoubleValue(value=delta),
                                                                      delta_type=delta_type
                                                                    ))
                wb_node.workflow_node_config = {"config": node, "compare_to": compare_to}

            self.nodes.append(wb_node)
            if idx > 0:
                edge = Edge(self.nodes[idx - 1], wb_node)
                self.edges.append(edge)
                self.nodes[idx - 1].mark_out_connection()
                self.nodes[idx].mark_in_connection()

    def get_workflow_view(self):
        data = []

        for node in self.nodes:
            data.append(
                node.get_proto()
            )

        links = []
        for edge in self.edges:
            links.append(
                edge.get_proto()
            )

        return WorkflowView(
            nodes=data,
            edges=links
        )

    def get_metric_from_newrelic(self, metric_expr, compare_to):
        metric_value, delta, delta_type = None, None, None

        self.nr_connector = NewRelicConnector(self.dtr.to_tr(), self.account.id)
        metric_value_json = self.nr_connector.fetch_metric(metric_expr)
        metric_value_compare = metric_value_json.get('value')
        if metric_value_compare is not None:
            metric_value = "{} {}".format(metric_value_json.get('value'), metric_value_json.get('unit'))
        else:
            metric_value = None

        if compare_to:
            prev_dtr = self.dtr.get_prev_dtr(compare_to)
            prev_metric_value_json = self.nr_connector.fetch_metric(metric_expr, prev_dtr.to_tr())
            prev_metric_value_compare = prev_metric_value_json.get('value')
            if metric_value_compare and not prev_metric_value_compare:
                delta = 100
                delta_type = WorkflowView.DeltaType.UP
            elif prev_metric_value_compare and not metric_value_compare:
                delta = 100
                delta_type = WorkflowView.DeltaType.DOWN
            elif not prev_metric_value_compare and not metric_value_compare:
                delta = None
                delta_type = None
            else:
                delta = abs(round(((metric_value_compare / prev_metric_value_compare) - 1.0), 2)) * 100
                if metric_value_compare >= prev_metric_value_compare:
                    delta_type = WorkflowView.DeltaType.UP
                else:
                    delta_type = WorkflowView.DeltaType.DOWN

        return metric_value, delta, delta_type


"""
可视化训练效果:
    程序运行结束，在cmd 运行tensorboard --logdir=path，然后在浏览器打开http://localhost:6006
"""
import tensorflow as tf
import numpy as np
from datetime import datetime
from sklearn.datasets import fetch_california_housing
from sklearn.preprocessing import StandardScaler

if __name__ == "__main__":
    now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
    root_logdir = r"D://tf_logs"
    logdir = "{}/run-{}/".format(root_logdir, now)

    scaler = StandardScaler()
    housing = fetch_california_housing()
    scaler_housing_data = scaler.fit_transform(housing.data)
    m,n = scaler_housing_data.shape
    scaler_housing_data_bias = np.c_[np.ones((m,1)),scaler_housing_data]

    # 设置梯度下降超参
    learn_rate = 0.01
    n_epochs = 1000
    # 不指定大小，等到真正训练时再生成
    X = tf.placeholder(shape=(None,n+1),dtype=tf.float32,name='X')
    y = tf.placeholder(shape=(None,1), dtype=tf.float32, name='y')

    # 初始化theta 在-1 - 1 之间
    theta = tf.Variable(tf.random.uniform([n+1,1],-1.0,1.0),name='theta')
    # 计算预测值
    y_pred = tf.matmul(X,theta,name='predictions')

    # 限定变量作用域
    # mse 生成相关操作会被放在loss 框图内
    with tf.name_scope("loss") as scope:
        error = y_pred - y
        mse = tf.reduce_mean(tf.square(error), name="mse")

    # error = y_pred - y
    # 计算损失函数
    # mse = tf.reduce_mean(tf.square(error),name='mse')
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learn_rate)
    training_op = optimizer.minimize(mse)
    init = tf.global_variables_initializer()
    # 可视化
    mse_summary = tf.summary.scalar('MSE', mse)
    file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph())

    # 设置批量的样本数
    batch_size = 1000
    n_batches = int(np.ceil(m/batch_size))

    with tf.Session() as sess:
        sess.run(init)
        for i in range(n_epochs):
            for batch_index in range (n_batches):
                # 随机批量，没有按顺序
                indices = np.random.randint(m, size=batch_size)
                X_batch = scaler_housing_data_bias[indices]
                y_batch = housing.target.reshape(-1,1)[indices]
                if batch_index%10 == 0:
                    # 每10次保存效果
                    summary_str = mse_summary.eval(feed_dict={X: X_batch, y: y_batch})
                    step = i * n_batches + batch_index
                    file_writer.add_summary(summary_str, step)
                # 此时才真正确定X，y 大小
                sess.run(training_op,feed_dict={X:X_batch,y:y_batch})
        best_theta = theta.eval()
    #  关闭
    file_writer.close()
    print("theta = ",best_theta)


from server.storage.model.settings import Setting
from server.helper.constant import constant
from server.server import create_app

def db_settings_initializer():
    with create_app().app_context():
        constant.DB.create_all()
        check_db_population = Setting.query.count()
        if check_db_population == 0:
            init_lang_settings = Setting(setting_type="language", value="en")
            init_content_settings = Setting(setting_type="content", value="safe")
            constant.DB.session.add(init_lang_settings)
            constant.DB.session.add(init_content_settings)
            constant.DB.session.commit()


import os
import shutil

src="C:/Users/aaa/Documents/Test_File"
dest="C:/Users/aaa/Documents/File_Organiser"

list_of_files = os.listdir(src)

for file_name in list_of_files:

    name,ext = os.path.splitext(file_name)

    if ext == '':
        continue

    if ext in ['.png', '.jpg', '.pdf', '.gif', '.txt', '.xls']:
        path1 = src+'/'+file_name
        path2 = dest+'/'+ext
        path3 = dest+'/'+ext+'/'+file_name

        if(os.path.exists(path2)):
            shutil.move(path1,path3)

        else:
            os.mkdir(path2)
            shutil.move(path1,path3)


#
# PySNMP MIB module CISCO-ENHANCED-MEMPOOL-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENHANCED-MEMPOOL-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint")
ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability")
AgentCapabilities, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "NotificationGroup", "ModuleCompliance")
NotificationType, Unsigned32, Counter64, Gauge32, TimeTicks, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, MibIdentifier, Bits, IpAddress, ObjectIdentity, ModuleIdentity, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Unsigned32", "Counter64", "Gauge32", "TimeTicks", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "MibIdentifier", "Bits", "IpAddress", "ObjectIdentity", "ModuleIdentity", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
cempCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 462))
cempCapability.setRevisions(('2011-09-21 00:00', '2011-01-31 00:00', '2010-10-28 00:00', '2009-08-21 00:00', '2009-04-23 00:00', '2007-05-09 00:00', '2005-12-29 00:00', '2005-10-26 00:00', '2005-01-27 00:00', '2004-10-01 00:00', '2004-06-15 00:00',))
if mibBuilder.loadTexts: cempCapability.setLastUpdated('201109210000Z')
if mibBuilder.loadTexts: cempCapability.setOrganization('Cisco Systems, Inc.')
cempCapabilityV12R03T = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R03T = cempCapabilityV12R03T.setProductRelease('Cisco IOS 12.3T')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R03T = cempCapabilityV12R03T.setStatus('current')
cempCapabilityV12R03TP5000 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R03TP5000 = cempCapabilityV12R03TP5000.setProductRelease('Cisco IOS 12.3T for AS5350, AS5400 and AS5850\n                        platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R03TP5000 = cempCapabilityV12R03TP5000.setStatus('current')
cempCapabilityV12R04TP37xx = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TP37xx = cempCapabilityV12R04TP37xx.setProductRelease('Cisco IOS 12.4T for c3725 and c3745\n                        platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TP37xx = cempCapabilityV12R04TP37xx.setStatus('current')
cempCapabilityV12R04TP26xx = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TP26xx = cempCapabilityV12R04TP26xx.setProductRelease('Cisco IOS 12.4T for c26xx and c2691\n                        platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TP26xx = cempCapabilityV12R04TP26xx.setStatus('current')
cempCapabilityV12R04TP38xx = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 5))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TP38xx = cempCapabilityV12R04TP38xx.setProductRelease('Cisco IOS 12.4T for c3825 and c3845\n                        platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TP38xx = cempCapabilityV12R04TP38xx.setStatus('current')
cempCapabilityV12R04TP28xx = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 6))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TP28xx = cempCapabilityV12R04TP28xx.setProductRelease('Cisco IOS 12.4T for c28xx platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TP28xx = cempCapabilityV12R04TP28xx.setStatus('current')
cempCapabilityV12R04TPVG224 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 7))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TPVG224 = cempCapabilityV12R04TPVG224.setProductRelease('Cisco IOS 12.4T for VG224 platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TPVG224 = cempCapabilityV12R04TPVG224.setStatus('current')
cempCapabilityV12R04TPIAD243x = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 8))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TPIAD243x = cempCapabilityV12R04TPIAD243x.setProductRelease('Cisco IOS 12.4T for IAD243x platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R04TPIAD243x = cempCapabilityV12R04TPIAD243x.setStatus('current')
cempCapabilityIOSXRV2R0CRS1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 9))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityIOSXRV2R0CRS1 = cempCapabilityIOSXRV2R0CRS1.setProductRelease('Cisco IOS XR 2.0 for CRS-1')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityIOSXRV2R0CRS1 = cempCapabilityIOSXRV2R0CRS1.setStatus('current')
cempCapabilityCatOSV08R0601 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 10))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityCatOSV08R0601 = cempCapabilityCatOSV08R0601.setProductRelease('Cisco CatOS 8.6(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityCatOSV08R0601 = cempCapabilityCatOSV08R0601.setStatus('current')
cempCapabilityV12R05TP184x = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 11))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R05TP184x = cempCapabilityV12R05TP184x.setProductRelease('Cisco IOS 12.5T for 184x platforms')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R05TP184x = cempCapabilityV12R05TP184x.setStatus('current')
cempCapabilityV12R05TP2801 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 12))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R05TP2801 = cempCapabilityV12R05TP2801.setProductRelease('Cisco IOS 12.5T for the 2801 platform')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityV12R05TP2801 = cempCapabilityV12R05TP2801.setStatus('current')
cempCapabilityNXOS501 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 13))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityNXOS501 = cempCapabilityNXOS501.setProductRelease('Cisco MDS & Nexus NX-OS 5.0 and above')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityNXOS501 = cempCapabilityNXOS501.setStatus('current')
cempCapabilityNXOSV05R0201 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 14))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityNXOSV05R0201 = cempCapabilityNXOSV05R0201.setProductRelease('Cisco Nexus NX-OS 5.2(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityNXOSV05R0201 = cempCapabilityNXOSV05R0201.setStatus('current')
cempCapabilityASA = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 15))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityASA = cempCapabilityASA.setProductRelease('8.4.x')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityASA = cempCapabilityASA.setStatus('current')
cempCapabilityNXOSV06R0001 = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 462, 16))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityNXOSV06R0001 = cempCapabilityNXOSV06R0001.setProductRelease('Cisco Nexus NX-OS 6.0(1).')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    cempCapabilityNXOSV06R0001 = cempCapabilityNXOSV06R0001.setStatus('current')
mibBuilder.exportSymbols("CISCO-ENHANCED-MEMPOOL-CAPABILITY", cempCapabilityV12R04TP38xx=cempCapabilityV12R04TP38xx, PYSNMP_MODULE_ID=cempCapability, cempCapabilityASA=cempCapabilityASA, cempCapabilityNXOSV05R0201=cempCapabilityNXOSV05R0201, cempCapabilityV12R05TP2801=cempCapabilityV12R05TP2801, cempCapabilityV12R04TP28xx=cempCapabilityV12R04TP28xx, cempCapabilityIOSXRV2R0CRS1=cempCapabilityIOSXRV2R0CRS1, cempCapabilityV12R04TP26xx=cempCapabilityV12R04TP26xx, cempCapabilityNXOSV06R0001=cempCapabilityNXOSV06R0001, cempCapabilityV12R04TPVG224=cempCapabilityV12R04TPVG224, cempCapabilityV12R03TP5000=cempCapabilityV12R03TP5000, cempCapabilityV12R05TP184x=cempCapabilityV12R05TP184x, cempCapability=cempCapability, cempCapabilityV12R04TP37xx=cempCapabilityV12R04TP37xx, cempCapabilityNXOS501=cempCapabilityNXOS501, cempCapabilityCatOSV08R0601=cempCapabilityCatOSV08R0601, cempCapabilityV12R04TPIAD243x=cempCapabilityV12R04TPIAD243x, cempCapabilityV12R03T=cempCapabilityV12R03T)


import re
import tkinter
import tkinter as tk
from tkinter import ttk

import ArknightsDataParser

class CalcPanel(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)

        self.columnconfigure(1, weight=1)

        self.ear = ""
        self.master = master

        tk.Label(self, justify="left", text="Elite", width=5).grid(column=0, row=0)
        tk.Label(self, justify="left", text="Level", width=5).grid(column=0, row=1)
        tk.Label(self, justify="left", text="Skill 1", width=5).grid(column=0, row=2)
        tk.Label(self, justify="left", text="Skill 2", width=5).grid(column=0, row=3)
        tk.Label(self, justify="left", text="Skill 3", width=5).grid(column=0, row=4)

        self.vcmdElite = (self.register(self.validateElite), "%P", "%W")
        self.vcmdLvl = (self.register(self.validateLvl), "%P", "%W")
        self.vcmdSkill = (self.register(self.validateSkill), "%P", "%W")
        self.ivcmd = (self.register(self.onInvalid), "%W", "%P")

        self.selectElite = ttk.Spinbox(self, from_=0, to=2)
        self.selectElite.insert(0, "0")
        self.selectElite.configure(command=lambda: self.callback("<Command event.>"))
        self.selectElite.configure(validate="all", validatecommand=self.vcmdElite, invalidcommand=self.ivcmd)
        self.selectElite.grid(column=1, row=0, sticky="ew")

        self.selectLvl = ttk.Spinbox(self, from_=1, to=90)
        self.selectLvl.insert(0, "1")
        self.selectLvl.configure(validate="all", validatecommand=self.vcmdLvl, invalidcommand=self.ivcmd)
        self.selectLvl.grid(column=1, row=1, sticky="ew")

        self.selectSkill1 = ttk.Spinbox(self, from_=1, to=10)
        self.selectSkill1.insert(0, "1")
        self.selectSkill1.configure(command=lambda: self.sync_spinbox(self.selectSkill1.get()))
        self.selectSkill1.configure(validate="all", validatecommand=self.vcmdSkill, invalidcommand=self.ivcmd)
        self.selectSkill1.grid(column=1, row=2, sticky="ew")

        self.selectSkill2 = ttk.Spinbox(self, from_=1, to=10)
        self.selectSkill2.insert(0, "1")
        self.selectSkill2.configure(command=lambda: self.sync_spinbox(self.selectSkill2.get()))
        self.selectSkill2.configure(validate="all", validatecommand=self.vcmdSkill, invalidcommand=self.ivcmd)
        self.selectSkill2.grid(column=1, row=3, sticky="ew")

        self.selectSkill3 = ttk.Spinbox(self, from_=1, to=10)
        self.selectSkill3.insert(0, "1")
        self.selectSkill3.configure(command=lambda: self.sync_spinbox(self.selectSkill3.get()))
        self.selectSkill3.configure(validate="all", validatecommand=self.vcmdSkill, invalidcommand=self.ivcmd)
        self.selectSkill3.grid(column=1, row=4, sticky="ew")

        self.selectElite.bind("<Any-KeyRelease>", self.callback)
        self.selectSkill1.bind("<Any-KeyRelease>", self.sync_spinbox)
        self.selectSkill2.bind("<Any-KeyRelease>", self.sync_spinbox)
        self.selectSkill3.bind("<Any-KeyRelease>", self.sync_spinbox)

    def validateElite(self, P, W):
        widget = self.master.nametowidget(W)
        _from = widget["from"]
        _to = widget["to"]
        pattern_elite = r"\d"
        try:
            if P == "":
                return True
            if (_from <= int(P) <= _to) and re.fullmatch(pattern_elite, P):
                return True
        except ValueError:
            return False
        return False

    def validateLvl(self, P, W):
        widget = self.master.nametowidget(W)
        _from = widget["from"]
        _to = widget["to"]
        pattern_level = r"\d{1,2}"
        try:
            if P == "":
                return True
            if (_from <= int(P) <= _to) and re.fullmatch(pattern_level, P):
                return True
        except ValueError:
            return False
        return False

    def validateSkill(self, P, W):
        widget = self.master.nametowidget(W)
        _from = widget["from"]
        _to = widget["to"]
        pattern_skills = r"10|\d"
        try:
            if P == "":
                return True
            if (_from <= int(P) <= _to) and re.fullmatch(pattern_skills, P):
                return True
        except ValueError:
            return False
        return False

    def onInvalid(self, W, P):
        widget = self.master.nametowidget(W)
        _from = widget["from"]
        _to = widget["to"]
        widget.delete(0, 9)
        try:
            if P.isdigit():
                if int(P) >= _to:
                    widget.insert(0, _to)
                if int(P) <= _from:
                    widget.insert(0, _from)
            else:
                widget.insert(0, _from)
        except ValueError:
            widget.insert(0, _from)

    def construct_op(self):
        """
        Создаем объект-ушку с заданными параметрами на прокачку.
        :return: Возвращает ушку как объект с параметрами для прокачки.
        """
        elite = self.selectElite.get()
        level = self.selectLvl.get()
        skill1 = self.selectSkill1.get()
        skill2 = self.selectSkill2.get()
        skill3 = self.selectSkill3.get()
        return ArknightsDataParser.Stats(int(elite), int(level), int(skill1), int(skill2), int(skill3))

    def on_update(self):
        """
        Обновляет фрейм, задавая ограничения полям для ввода на основе выбранной ушки.
        """
        self.ear = ArknightsDataParser.Operator(self.master.selectOperator.get())
        self.selectElite["to"] = len(self.ear.ear["phases"]) - 1
        self.selectLvl["to"] = int(self.ear.phase(self.selectElite.get()))
        if self.selectLvl["to"] <= int(self.selectLvl.get()):
            self.selectLvl.delete(0, 9)
            self.selectLvl.insert(0, self.selectLvl["to"])
        self.selectSkill1["to"] = self.ear.skill_lvl(self.selectElite.get())
        self.selectSkill2["to"] = self.ear.skill_lvl(self.selectElite.get())
        self.selectSkill3["to"] = self.ear.skill_lvl(self.selectElite.get())

    def sync_spinbox(self, event):
        """
        Синхронизирует ввод для полей, отвещающих за уровни навыков ушки.
        :param event:
        """
        print("Sync spinbox triggered: " + str(event))
        if type(event) == tkinter.Event:
            sbvalue = event.widget.get()
        else:
            sbvalue = event
        if int(sbvalue) <= 7:
            self.selectSkill1.delete(0, 9)
            self.selectSkill1.insert(0, sbvalue)
            self.selectSkill2.delete(0, 9)
            self.selectSkill2.insert(0, sbvalue)
            self.selectSkill3.delete(0, 9)
            self.selectSkill3.insert(0, sbvalue)

    # noinspection PyUnusedLocal
    def on_reset(self, event):
        """
        Сбрасывает поля ввода при изменении уровня элитки ушки.
        :param event: Принимает на вход event.
        """
        self.on_update()
        if int(self.selectLvl.get()) > self.selectLvl["to"]:
            self.selectLvl.delete(0, 9)
            self.selectLvl.insert(0, self.selectLvl["to"])
        if int(self.selectSkill1.get()) > self.selectSkill1["to"]:
            self.selectSkill1.delete(0, 9)
            self.selectSkill2.delete(0, 9)
            self.selectSkill3.delete(0, 9)
            self.selectSkill1.insert(0, self.selectSkill1["to"])
            self.selectSkill2.insert(0, self.selectSkill1["to"])
            self.selectSkill3.insert(0, self.selectSkill1["to"])

    def clear_spinboxes(self):
        """
        Очищает все поля, сбрасывая их к изначальным значениям.
        """
        self.selectElite.delete(0, 9)
        self.selectElite.insert(0, "0")
        self.selectLvl.delete(0, 9)
        self.selectLvl.insert(0, "1")
        self.selectSkill1.delete(0, 9)
        self.selectSkill2.delete(0, 9)
        self.selectSkill3.delete(0, 9)
        self.selectSkill1.insert(0, "1")
        self.selectSkill2.insert(0, "1")
        self.selectSkill3.insert(0, "1")

    def callback(self, event):
        # print("Callback triggered: " + str(event))
        self.on_reset("")