# =============================================================================
# TEMPORARY IMPORT. REMOVE WHEN FINALISED
# =============================================================================
# Import locally
import os, sys
directory = 'Desktop/py_sgpls'
path = os.path.join(os.path.abspath('.'), directory)
sys.path.append(path)
# =============================================================================
# =============================================================================
import numpy as np

from numpy.testing import (assert_array_equal, assert_array_almost_equal,
                           assert_raises, assert_warns)
from sgpls.utils import sparsity_conversion
from sgpls.utils import _soft_thresholding
from sgpls.utils import _group_thresholding
from sgpls.utils import _lambda_quadratic
from sgpls.utils import _sparse_group_thresholding
from sgpls.utils import _check_1d
from sgpls.utils import _validate_block
from sgpls.utils import pls_array
from sgpls.utils import pls_blocks

def test_sparsity_conversion():
    # Test simple array
    a = np.array([0, 1, 2, 3, 4, 5, 6])
    sc = sparsity_conversion(a, 3)

    assert_array_equal(sc, np.array([3, 2, 1, 0, -1, -2, -3]))

    # Test None case
    b = None
    sc2 = sparsity_conversion(b, 5)

    assert_array_equal(sc2, np.array([0 ,0 ,0, 0, 0]))

def test_soft_thresholding():
    array = np.array([7, 0, -5, -2, 6, -4, -10])
    st = _soft_thresholding(array, 4)

    true_st = np.array([3, 0, -1, 0, 2, 0, -6])

    assert_array_equal(st, true_st)

def test_group_thresholding():
    array = np.array([0, -5, 6, -9, 4, 7, 2])

    # Case 1: lambda_k/penalty <= 1. Array is not penalised
    gt = _group_thresholding(array, 1, 2)    # lambda_k/penalty = 0.5 <= 1

    true_gt = np.array([0, -2.5, 3, -4.5, 2, 3.5, 1])

    assert_array_equal(gt, true_gt)

    # Case 2: lambda_k/penalty > 1. Array is penalised (zeroed out)
    gt2 = _group_thresholding(array, 2, 1)    # lambda_k/penalty = 2 > 1

    assert_array_equal(gt2, np.zeros(len(array)))

def test_lambda_quadratic():
    array = np.array([-0.3, 0.8, 0.9, 1.0, 0.4])
    lambdas = np.linspace(0,5,11)
    lq = np.array([_lambda_quadratic(lam, array, 1/2)
                   for lam in lambdas]).ravel()

    # Compare to lambda.quadra() from sgPLS package internal functions
    true_lq = np.array([2.7, 1.615625, 0.0625, -1.965, -4.5, -7.565625,
                        -11.1625, -15.29625, -20, -25.3125, -31.25])

    assert_array_almost_equal(lq, true_lq)

def test_sparse_group_thresholding():
    array = np.array([7, 0, -5, -2])
    sgt = _sparse_group_thresholding(array, 16, 1e+06, 1/2)

    true_sgt = np.array([-4.589466384, 0, 1.529822128, 0]) # R version
    # true_sgt = np.array([-0.9, 0, 0.3, 0]) # Literature version

    assert_array_almost_equal(sgt, true_sgt)

def test_check_1d():
    # Check that multi-dimensional arrays with n.dim > 2 raise ValueErrors
    multi_d = np.zeros((5, 4, 3))
    assert_raises(ValueError, _check_1d, multi_d)

    # Check that 2D arrays raise ValueErrors
    two_d = np.zeros((5, 4))
    assert_raises(ValueError, _check_1d, two_d)

    # Test 1D arrays
    one_d_a = np.zeros(5)
    assert_array_equal(one_d_a, _check_1d(one_d_a))

    # Check that 2D arrays with shapes (n,1) or (1,n) are converted to 1D
    one_d_b = np.zeros((5, 1))
    one_d_c = np.zeros((1, 5))
    assert_array_equal(one_d_a, _check_1d(one_d_b))
    assert_array_equal(one_d_a, _check_1d(one_d_c))

def test_validate_block():
    a = np.array([0, 3, 5, 8, 9])
    assert_array_equal(a, _validate_block(a))

    # Check that unordered arrays and arrays with repeated entries raise
    # ValueError
    b = np.array([9, 3, 5, 8, 0])   # Swap first and last entry
    c = np.array([0, 3, 3, 5, 8, 9])    # Repeat second entry
    assert_raises(ValueError, _validate_block, b)
    assert_raises(ValueError, _validate_block, c)

def test_pls_array():
    # Case 1: valid array, min_length < max_length
    a = np.array([2, 4, 0, 3, 1, 5])
    assert_array_equal(a,
                                  pls_array(a, max_length=6, min_length=0,
                                            max_entry=5, min_entry=0))

    # Case 2: valid array, min_length = max_length
    assert_array_equal(a,
                                  pls_array(a, max_length=6, min_length=6,
                                            max_entry=5, min_entry=0))

    # Case 3: entries < min_entry. Raises ValueError
    b = np.array([-2, 4, 0, 3, 1, 5])
    assert_raises(ValueError, pls_array, b, 6, 0, 5, 0)

    # Case 4: entries > max_entry. Raises ValueError
    c = np.array([100, 4, 0, 3, 1, 5])
    assert_raises(ValueError, pls_array, c, 6, 0, 5, 0)

    # Case 5: length < min_length. Raises ValueError
    d = np.array([2, 4])
    assert_raises(ValueError, pls_array, d, 6, 3, 5, 0)

    # Case 6: length > max_length. Raises ValueError
    e = np.array([2, 4, 0, 3, 1, 5, 4, 3, 2])
    assert_raises(ValueError, pls_array, e, 6, 3, 5, 0)

def test_pls_blocks():
    a = np.array([0, 3, 5, 8, 9, 15])
    b = np.array([3, 5, 8, 9, 15])
    c = np.array([0, 3, 5, 8, 9])

    true_block = np.array([3, 5, 8, 9])

    # Check results
    block_orig = pls_blocks(true_block, max_entry=15)
    block_a = pls_blocks(a, max_entry=15)
    block_b = pls_blocks(b, max_entry=15)
    block_c = pls_blocks(c, max_entry=15)

    assert_array_equal(block_orig, true_block)    # No change
    assert_array_equal(block_a, true_block)
    assert_array_equal(block_b, true_block)
    assert_array_equal(block_c, true_block)

    # Check that UserWarning is raised
    assert_warns(UserWarning, pls_blocks, a, 15, 0, True)
    assert_warns(UserWarning, pls_blocks, b, 15, 0, True)
    assert_warns(UserWarning, pls_blocks, c, 15, 0, True)


import json
from time import sleep
from math import floor
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

driver = webdriver.Firefox()
driver.set_window_position(0, 0)
driver.get("https://play.cprewritten.net/")
delay = 3

try:
    print("[-] Loading Page...")
    waitingForSite = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'cpr_client')))
    print("[+] Page is ready!\n")
except TimeoutException:
    print("Loading timed out.")

def start(positions):
    pos_obj = json.loads(positions)

    try:
        while True:
            for formula in pos_obj:
                e = driver.find_element_by_xpath('//*[@id="cpr_client"]')

                canvWidth = e.size['width']
                canvHeight = e.size['height']

                xFormula = formula['xFormula']
                yFormula = formula['yFormula']

                xAxis = floor(canvWidth / xFormula)
                yAxis = floor(canvHeight / yFormula)

                print(f"[+] Moving to X: {xAxis}, Y: {yAxis}")
                action = webdriver.common.action_chains.ActionChains(driver)
                action.move_to_element_with_offset(e, xAxis, yAxis)
                action.click()
                action.perform()
                sleep(.5)

                actions = webdriver.common.action_chains.ActionChains(driver)
                actions.send_keys("D")
                actions.perform()
                sleep(12)

    except KeyboardInterrupt:
        print("[!] Keyboard Interrupt")

positions = '[{"xFormula": 1.363076923076923, "yFormula": 1.6},{"xFormula": 1.363076923076923, "yFormula": 1.436182113882212},{"xFormula": 1.4190400390625, "yFormula": 1.513818984902872}]'

while True:
    option = input("[+] Type 'Start' To Start AutoMiner ").lower()
    if option == "start":
        start(positions)
    else:
        pass


import aiohttp, backend, functools, quart, sqlite3, test_products
from collections import Counter

app = quart.Quart(__name__)
db = sqlite3.connect(":memory:")

# create aiohttp session so our web server can perform http requests
@app.before_serving
async def before_serving():
    app.client = aiohttp.ClientSession()

# close http session when done
@app.after_serving
async def after_serving():
    await app.client.close()

# main page just renders the search menu
@app.route("/")
async def ep_home():
    return await quart.render_template("home.html")

# search page requires query parameters that specify the product that the user
# searched for
@app.route("/search")
async def ep_search():
    # query is the name of the product that the user searched
    query = quart.request.args.get("query")

    # get product data from backend
    products = await backend.get_products(app.client, query)

    # get all specs in order of decreasing frequency
    spec_counter = Counter()
    for product in products:
        for spec in product.specs.keys():
            spec_counter[spec] += 1
    specs = [spec for spec, _ in spec_counter.most_common()]

    cur = db.cursor()

    # create the sql table to hold the specs
    create_stmt = "CREATE TABLE main_tbl({});".format(
        ",".join(["Name", "Url"] + specs)
    )

    # insert the data into the table for each product
    cur.execute("DROP TABLE IF EXISTS main_tbl;")
    cur.execute(create_stmt)
    for product in products:
        keys = ["Name", "Url"] + list(product.specs.keys())
        vals = [product.name, product.url] + list(product.specs.values())
        insert_stmt = "INSERT INTO main_tbl({}) VALUES({});".format(
                ",".join(keys),
                ",".join(["?" for _ in vals])
        )
        cur.execute(insert_stmt, vals)

    db.commit()

    product_names = [{"name": product.name, "url": product.url}
                     for product in products]
    return await quart.render_template("search.html",
        query=query,
        specs=specs,
        products=product_names)

# json endpoint to get products that contain any specs from a given set of
# specs
@app.route("/filter")
async def ep_filter():
    arg = quart.request.args

    # get specs from ajax data, and then select Name,Url,[specs]... from the
    # table
    if arg:
        #specs = arg.split(",")
        specs = []
        for item in arg:
            specs.append(item)
        select_stmt = "SELECT Name,Url," + ",".join(specs) + " FROM main_tbl WHERE " + " OR ".join(specs) + ";"

        # TODO: replace with placeholders to avoid injection
        #       the following code does not work
        #select_stmt = "SELECT Name,Url," + ",".join(["?" for _ in specs])
        # + " FROM main_tbl WHERE " + " AND ".join(["? IS NOT NULL" for spec in specs]) + ";"
    else:
        specs = []
        select_stmt = "SELECT Name,Url FROM main_tbl;"

    cur = db.cursor()

    products = []
    for row in cur.execute(select_stmt).fetchall():
        # first column is name, second is url, remaining is specs
        products.append({
            "name": row[0],
            "url": row[1],
            "specs": row[2:]
        })

    return { "specs": specs, "products": products }

app.run(debug=True)


from project import Project
from student import Student
from supervisor import Supervisor
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')

file_handler = logging.FileHandler('../logs/data_reader.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)

logger.addHandler(file_handler)

class DataReader:

    def __init__(self, sup_list_path, stu_list_path, proj_list_path):
        self.__sup_list_path = sup_list_path
        self.__stu_list_path = stu_list_path
        self.__proj_list_path = proj_list_path

        self.__sup_list = self.__generate_supervisor_list()
        self.__proj_list = self.__generate_project_list()
        self.__stu_list = self.__generate_stu_list()

    def getStudentList(self):
        return self.__stu_list

    def getSupervisorList(self):
        return self.__sup_list

    def getProjectList(self):
        return self.__proj_list

    def __generate_stu_list(self):
        logger.info("Reading students\' data from the given path: {0} ".format(self.__stu_list_path))
        # logger.info(str('Reading students\' data from the given path: ' + self.__stu_list_path))
        stu_file = open(self.__stu_list_path, "r")
        stu_list = []
        for stu in stu_file:
            stu_info = stu.split()
            stu_id = int(stu_info[0])
            stu_preferences_list = []
            for item in stu_info[1:]:
                stu_preferences_list.append(int(item))
            student = Student(stu_id, stu_id, stu_preferences_list)
            if self.__student_constraints_check(student, self.__proj_list):
                stu_list.append(student)
        stu_file.close()
        logger.info('Get students\' data successfully')
        return stu_list

    def __generate_supervisor_list(self):
        logger.info("Reading supervisors\' data from the given path: {0} ".format(self.__sup_list_path))
        sup_file = open(self.__sup_list_path, "r")
        sup_list = []
        for sup in sup_file:
            sup_info = sup.split()
            sup_id = int(sup_info[0])
            sup_quota = int(sup_info[1])
            sup_proj_list = []
            for item in sup_info[2:]:
                sup_proj_list.append(int(item))
            supervisor = Supervisor(sup_id, sup_id, sup_proj_list, sup_quota)
            sup_list.append(supervisor)
        sup_file.close()
        logger.info('Get supervisors\' data successfully')
        return sup_list

    def __generate_project_list(self):
        logger.info("Reading projects\' data from the given path: {0} ".format(self.__proj_list_path))
        proj_file = open(self.__proj_list_path, "r")
        proj_list = []
        for proj in proj_file:
            logger.info('project id:')
            logger.info(proj)
            proj_info = proj.split()
            proj_id = int(proj_info[0])
            proj_sup = int(proj_info[1])
            project = Project(proj_id, proj_sup)
            proj_list.append(project)
        proj_file.close()
        logger.info('Get projects\' data successfully')
        return proj_list

    def __student_constraints_check(self, stu: Student, proj_list: list):
        preference_list = stu.getProjectList()
        sup_set = set()
        for proj in preference_list:
            sup_id = proj_list[proj].supervisor_id
            sup_set.add(sup_id)
        if (len(sup_set)) > 1:
            return True
        logger.error("Student id: {0} only choose one supervisor, please choose at least two supervisors"
                     .format(stu.getStudentID()))
        return False


#!/usr/bin/env python
# -*- coding: utf-8 -*-
__Auther__ = 'M4x'

from pwn import *
from time import sleep
import roputils as rp
import os
import sys

elfPath = "./stringer"
libcPath = "./libc.so.6"
remoteAddr = "localhost"
remotePort = 9999

context.log_level = "debug"
context.binary = elfPath
context.terminal = ["deepin-terminal", "-x", "sh", "-c"]

elf = context.binary
if sys.argv[1] == "l":
    io = process(elfPath)
    libc = elf.libc

else:
    if sys.argv[1] == "d":
        io = process(elfPath, env = {"LD_PRELOAD": libcPath})
    else:
        io = remote(remoteAddr, remotePort)
        context.log_level = "info"
    if libcPath:
        libc = ELF(libcPath)

success = lambda name, value: log.success("{} -> {:#x}".format(name, value))

def DEBUG(bps = [], pie = False):
    cmd = "set follow-fork-mode parent\n"
    if pie:
        base = int(os.popen("pmap {}| awk '{{print $1}}'".format(io.pid)).readlines()[1], 16)
        cmd += ''.join(['b *{:#x}\n'.format(b + base) for b in bps])
    else:
        cmd += ''.join(['b *{:#x}\n'.format(b) for b in bps])

    if bps != []:
        cmd += "c"

    gdb.attach(io, cmd)

def add(size, cont):
    io.sendlineafter(": ", "1")
    io.sendlineafter(": ", str(size))
    io.sendafter(": ", cont)

def edit(idx, bidx):
    io.sendlineafter(": ", "1")
    io.sendlineafter(": ", str(idx))
    io.sendlineafter(": ", str(bidx))

def delete(idx):
    io.sendlineafter(": ", "4")
    io.sendlineafter(": ", str(idx))

if __name__ == "__main__":

    io.interactive()
    io.close()


import os.path

import bkl.interpreter
import bkl.dumper
import bkl.io

from bkl.expr import BoolValueExpr, ListExpr, LiteralExpr, ConcatExpr, NullExpr

import projects
projects_dir = os.path.dirname(projects.__file__)

class InterpreterForTestSuite(bkl.interpreter.Interpreter):
    def generate(self):
        pass

def test_model_cloning():
    i = InterpreterForTestSuite()
    i.process_file(os.path.join(projects_dir, 'submodules', 'main.bkl'))
    model = i.model
    model_copy = model.clone()
    model_txt = bkl.dumper.dump_project(model)
    model_copy_txt = bkl.dumper.dump_project(model_copy)
    assert model_txt == model_copy_txt

def test_file_io_unix(tmpdir):
    p = tmpdir.join("textfile")
    f = bkl.io.OutputFile(str(p), bkl.io.EOL_UNIX)
    f.write("one\ntwo\n")
    f.commit()
    text_read = p.read("rb")
    assert text_read == "one\ntwo\n"

def test_file_io_win(tmpdir):
    p = tmpdir.join("textfile")
    f = bkl.io.OutputFile(str(p), bkl.io.EOL_WINDOWS)
    f.write("one\ntwo\n")
    f.commit()
    text_read = p.read("rb")
    assert text_read == "one\r\ntwo\r\n"

def test_expr_as_bool():
    bool_yes = BoolValueExpr(True)
    bool_no = BoolValueExpr(False)
    empty_list = ListExpr([])
    a_list = ListExpr([bool_yes, bool_no])
    literal = LiteralExpr("foo")
    empty_literal = LiteralExpr("")
    concat = ConcatExpr([empty_literal, literal, literal])
    empty_concat = ConcatExpr([empty_literal, empty_literal])

    assert bool(bool_yes)
    assert bool(a_list)
    assert bool(literal)
    assert bool(concat)
    assert not bool(bool_no)
    assert not bool(empty_list)
    assert not bool(empty_literal)
    assert not bool(empty_concat)

def test_list_expr_iterator():
    bool_yes = BoolValueExpr(True)
    bool_no = BoolValueExpr(False)
    empty_list = ListExpr([])
    a_list = ListExpr([bool_yes, bool_no])
    assert len(empty_list) == 0
    assert not empty_list
    assert len(a_list) == 2
    assert a_list
    assert list(a_list) == [bool_yes, bool_no]

    null = NullExpr()
    assert not null
    assert len(null) == 0


from django.db import models
from helpers.models import Model
from payroll.models import PayScale, PayGrade, SalaryGroup, DeductionGroup, BonusGroup
from leave.models import LeaveGroup
from accounts.choices import gender_choices, year_choices, current_year
from payroll.models import DeductionGroup

class EmployeeIdentification(Model):
    employee_code = models.CharField(max_length=255, unique=True, null=True)
    title = models.CharField(max_length=255, choices=[('mr', 'Mr.'), ('mrs', 'Mrs.'), ('miss', 'Miss')],
                             null=True)
    first_name = models.CharField(max_length=255, blank=True, null=True)
    middle_name = models.CharField(max_length=255, blank=True, null=True)
    last_name = models.CharField(max_length=255, blank=True, null=True)
    display_name = models.CharField(max_length=255, blank=True, null=True)
    profile_picture = models.ImageField(upload_to='accounts/profile_pic/', blank=True, null=True)
    employee_id = models.CharField(max_length=255, unique=True, null=True)
    gender = models.CharField(max_length=20, null=True, choices=gender_choices)

    def __str__(self):
        return "%s %s %s" % (self.first_name, self.middle_name, self.last_name)

class JobInformation(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE,
                                 related_query_name='employee_job_informations',
                                 related_name='employee_job_information', null=True)
    company = models.ForeignKey('setting.Company', on_delete=models.SET_NULL, null=True,
                                limit_choices_to={'status': 'active'})
    business_unit = models.ForeignKey('setting.BusinessUnit', on_delete=models.SET_NULL, null=True, blank=True,
                                      limit_choices_to={'status': 'active'})
    division = models.ForeignKey('setting.Division', blank=True, null=True, on_delete=models.SET_NULL,
                                 limit_choices_to={'status': 'active'})
    department = models.ForeignKey('setting.Department', blank=True, null=True, on_delete=models.SET_NULL,
                                   limit_choices_to={'status': 'active'})
    project = models.ForeignKey('setting.Project', on_delete=models.SET_NULL, null=True, blank=True,
                                limit_choices_to={'status': 'active'})

    designation = models.ForeignKey('setting.Designation', blank=True, null=True, on_delete=models.SET_NULL,
                                    related_name='setting_designation', limit_choices_to={'status': 'active'})
    branch = models.ForeignKey('setting.Branch', blank=True, null=True, on_delete=models.SET_NULL,
                                    related_name='setting_branch', limit_choices_to={'status': 'active'})
    report_to = models.ForeignKey(EmployeeIdentification, blank=True, null=True, on_delete=models.SET_NULL,
                                  related_name='report_to')
    additional_report_to = models.ForeignKey(EmployeeIdentification, blank=True, null=True, on_delete=models.SET_NULL,
                                             related_name='additional_report_to')
    pay_group = models.CharField(max_length=10, blank=True, null=True)
    pay_scale = models.ForeignKey(PayScale, blank=True, null=True, on_delete=models.SET_NULL,
                                  limit_choices_to={'status': True})
    pay_grade = models.ForeignKey(PayGrade, blank=True, null=True, on_delete=models.SET_NULL,
                                  limit_choices_to={'status': True})
    job_status = models.ForeignKey('setting.JobStatus', blank=True, null=True, on_delete=models.SET_NULL,
                                   limit_choices_to={'status': True})
    employment_type = models.ForeignKey('setting.EmploymentType', blank=True, null=True, on_delete=models.SET_NULL,
                                        limit_choices_to={'status': True})
    date_of_offer = models.DateField(null=True, blank=True)
    date_of_joining = models.DateField(null=True)
    status = models.BooleanField(default=True, blank=True)

    class Meta:
        get_latest_by = ['updated_at']

class Employment(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, related_query_name='employments',
                                 related_name='employment', null=True)
    confirmation_after = models.IntegerField(blank=True, null=True)
    confirmation_after_unit = models.CharField(max_length=10,
                                               choices=[('days', 'Days'), ('months', 'Months'), ('years', 'Years')],
                                               blank=True, null=True)
    confirmation_date = models.DateField(null=True, blank=True)
    date_of_actual_confirmation = models.DateField(null=True, blank=True)

class EndOfContract(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True, blank=True)
    due_on = models.DateField(null=True, blank=True)
    date_of_settlement = models.DateField(null=True, blank=True)
    effective_date = models.DateField(null=True, blank=True)

class Separation(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    type_of_resign = models.CharField(max_length=50, choices=[('sack', 'Sack'), ('resign', 'Resign'),
                                                              ('accidental_separation', 'Accidental Separation')],
                                      default='sack')
    date_of_sack = models.DateField(blank=True, null=True)
    date_of_resign = models.DateField(blank=True, null=True)
    date_of_settlement = models.DateField(blank=True, null=True)
    effective_date = models.DateField(blank=True, null=True)

class Retirement(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    due_on = models.DateField(blank=True, null=True)
    date_of_settlement = models.DateField(blank=True, null=True)
    effective_date = models.DateField(blank=True, null=True)

class Payment(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True,
                                 related_name='employee_payment')
    payment_mode = models.CharField(max_length=20, choices=[('bank', 'Bank'), ('cash', 'Cash'), ('cheque', 'Cheque')],
                                    default='Bank')
    pay_schedule = models.CharField(max_length=20, choices=[('monthly', 'Monthly'), ('weekly', 'Weekly')],
                                    default='monthly')
    employee_bank_name = models.ForeignKey('setting.Bank', on_delete=models.SET_NULL, blank=True, null=True,
                                           limit_choices_to={'status': 'active'})
    employee_bank_AC_name = models.CharField(max_length=255, blank=True, null=True,
                                             verbose_name='Employee Bank A/C Name')
    bank_branch_code = models.CharField(max_length=255, blank=True, null=True)
    bank_AC_no = models.IntegerField(blank=True, null=True, verbose_name='Bank A/C No')
    routing_number = models.CharField(max_length=255, blank=True, null=True)

class SalaryStructure(Model):
    STATUS_CHOICES = (
        ('active', 'Active'),
        ('inactive', 'Inactive')
    )

    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True,
                                 related_name='employee_salary_structure')
    salary_group = models.ForeignKey(SalaryGroup, null=True, on_delete=models.SET_NULL,
                                     limit_choices_to={'status': 'active'})
    bonus_group = models.ForeignKey(BonusGroup, blank=True, null=True, on_delete=models.SET_NULL,
                                    limit_choices_to={'status': True})
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='active'
    )

    from_date = models.DateField()
    to_date = models.DateField(blank=True, null=True)
    reason_of_salary_modification = models.TextField(blank=True, null=True)

class Personal(Model):
    RELIGION_CHOICES = [
        ('', '-------'),
        ('Islam', 'Islam'),
        ('Hinduism', 'Hinduism'),
        ('Christianity', 'Christianity'),
        ('Buddhism', 'Buddhism'),
        ('Other', 'Other')
    ]
    BLOOD_GROUP_CHOICES = [
        ('', '-------'),
        ('A+', 'A+'),
        ('O+', 'O+'),
        ('B+', 'B+'),
        ('AB+', 'AB+'),
        ('A-', 'A-'),
        ('O-', 'O-'),
        ('B-', 'B-'),
        ('AB-', 'AB-'),
    ]
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True,
                                 related_name='personal_employee')
    date_of_birth = models.DateField(null=True)
    place_of_birth = models.ForeignKey('setting.Countries', on_delete=models.SET_NULL, null=True, blank=True)
    birth_certificate = models.FileField(upload_to='accounts/birth_certificate/', blank=True, null=True)
    nationality = models.CharField(max_length=255, null=True)
    passport_number = models.IntegerField(blank=True, null=True)
    nid_or_ssn_number = models.IntegerField(blank=True, null=True, verbose_name='NID/SSN Number')
    passport_expiry_date = models.DateField(blank=True, null=True)
    nid = models.FileField(upload_to='accounts/nid_pic/', blank=True, null=True, verbose_name='NID')
    passport = models.FileField(upload_to='accounts/passport_pic/', blank=True, null=True)
    tin_number = models.IntegerField(blank=True, null=True, verbose_name='TIN Number')
    TIN = models.FileField(upload_to='accounts/tin_pic/', blank=True, null=True)
    visa_type = models.CharField(max_length=10, blank=True, null=True)
    visa_number = models.IntegerField(blank=True, null=True)
    work_permit_no = models.IntegerField(blank=True, null=True)
    work_permit_expiry_date = models.DateField(blank=True, null=True)
    work_permit_doc = models.FileField(upload_to='accounts/work_permit_pic/', blank=True, null=True)
    driving_licence_no = models.IntegerField(blank=True, null=True)
    driving_licence_expiry_date = models.DateField(blank=True, null=True)
    driving_licence_doc = models.FileField(upload_to='accounts/driving_licence_pic/', blank=True, null=True)

    mothers_name = models.CharField(max_length=255, blank=True, null=True)
    fathers_name = models.CharField(max_length=255, blank=True, null=True)
    marital_status = models.CharField(max_length=20, choices=[('married', 'Married'), ('unmarried', 'Unmarried')],
                                      default='married')
    spouse_name = models.CharField(max_length=255, blank=True, null=True)
    no_of_child = models.IntegerField(default=0, blank=True, null=True)
    height_ft = models.IntegerField(blank=True, null=True, verbose_name='Height')
    height_in = models.IntegerField(blank=True, null=True)
    weight = models.IntegerField(blank=True, null=True)
    weight_unit = models.CharField(max_length=10, choices=[('kg', 'kg'), ('gm', 'gm')], default='kg',
                                   null=True)
    blood_group = models.CharField(max_length=20, blank=True, choices=BLOOD_GROUP_CHOICES, default='')
    identification_mark = models.CharField(max_length=255, blank=True, null=True)
    religion = models.CharField(max_length=20, blank=True, choices=RELIGION_CHOICES, default='')
    caste = models.CharField(max_length=255, blank=True, null=True)
    mother_tongue = models.CharField(max_length=255, blank=True, null=True)
    police_station_address = models.TextField(blank=True, null=True)
    fingerprint = models.FileField(upload_to='accounts/fingerprint/', blank=True, null=True)
    signature = models.FileField(upload_to='accounts/signature/', blank=True, null=True)

    preferred_food = models.TextField(blank=True, null=True)
    hobby = models.TextField(blank=True, null=True)

class AddressAndContact(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    official_cell_number = models.CharField(max_length=100, null=True)
    personal_cell_number = models.CharField(max_length=100, null=True)
    official_email_ID = models.EmailField(blank=True, null=True)
    personal_email_ID = models.EmailField(blank=True, null=True)

    present_address = models.TextField(verbose_name='Address Line', null=True)
    present_country = models.ForeignKey('setting.Countries', on_delete=models.SET_NULL, null=True,
                                        verbose_name='Country', related_name='prensent_country')
    present_state = models.ForeignKey('setting.States', on_delete=models.SET_NULL, null=True, verbose_name='State',
                                      related_name='prensent_state')
    present_city = models.ForeignKey('setting.Cities', on_delete=models.SET_NULL, null=True, verbose_name='City',
                                     related_name='prensent_city')
    present_thana = models.CharField(max_length=255, null=True, blank=True, verbose_name='Thana')
    present_postal_code = models.IntegerField(blank=True, null=True, verbose_name='Postal Code')
    present_contact_person = models.CharField(max_length=255, blank=True, null=True, verbose_name='Contact Person')
    present_phone_number = models.CharField(max_length=100, null=True, verbose_name='Phone Number')
    permanent_address = models.TextField(verbose_name='Address Line', null=True, blank=True)

    permanent_country = models.ForeignKey('setting.Countries', on_delete=models.SET_NULL, null=True,
                                          verbose_name='Country', related_name='permanent_country', blank=True)
    permanent_city = models.ForeignKey('setting.Cities', on_delete=models.SET_NULL, null=True, verbose_name='City',
                                       related_name='permanent_city', blank=True)
    permanent_state = models.ForeignKey('setting.States', on_delete=models.SET_NULL, null=True, verbose_name='State',
                                        related_name='permanent_state', blank=True)
    permanent_thana = models.CharField(max_length=255, blank=True, null=True, verbose_name='Thana')
    permanent_postal_code = models.IntegerField(blank=True, null=True, verbose_name='Postal Code')
    permanent_contact_person = models.TextField(blank=True, null=True, verbose_name='Contact Person')
    permanent_phone_number = models.CharField(max_length=100, verbose_name='Phone Number', blank=True, null=True)

class EmergencyContact(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    name = models.CharField(max_length=255)
    relationship = models.CharField(max_length=255)
    address = models.TextField(blank=True, null=True)
    contact = models.CharField(max_length=100)
    email = models.EmailField(blank=True, null=True)

class Family(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    name_of_family_member = models.CharField(max_length=255)
    relationship_with_employee = models.CharField(max_length=255)
    DOB = models.DateField(blank=True, null=True)
    age = models.IntegerField(blank=True, null=True)
    gender = models.CharField(max_length=20, null=True, choices=gender_choices)
    employed = models.NullBooleanField(default=True)
    dependent = models.NullBooleanField(default=True)

class Education(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    degree = models.CharField(max_length=255, null=True)
    university = models.CharField(max_length=255, verbose_name='University/College/School/Institute', null=True)
    subject = models.CharField(max_length=255, verbose_name='Discipline/Subject', null=True)
    year_of_completion = models.IntegerField(choices=year_choices(), default=current_year, null=True)
    result_type = models.CharField(max_length=10, choices=[('CGPA', 'CGPA'), ('GPA', 'GPA'), ('division', 'Division')],
                                   default='CGPA')
    result_of_gpa = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Result')
    out_of = models.CharField(max_length=10, choices=[('4.0', '4.0'), ('5.0', '5.0')], null=True, blank=True)
    result_of_division = models.CharField(max_length=10, choices=[('1st', '1st'), ('2nd', '2nd'), ('3rd', '3rd')],
                                          blank=True, null=True, verbose_name='Result')
    grade = models.CharField(max_length=5,
                             choices=[('A+', 'A+'), ('A', 'A'), ('A-', 'A-'), ('B+', 'B+'), ('B', 'B'), ('B-', 'B-'),
                                      ('C+', 'C+'), ('C', 'C'), ('D', 'D'), ('F', 'F')], blank=True, null=True)
    marks = models.IntegerField(blank=True, null=True)
    certificate = models.FileField(upload_to='accounts/certificate/', blank=True, null=True)

    class Meta:
        unique_together = ('employee', 'degree')

class Skill(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    skill_name = models.CharField(max_length=255, null=True)
    description = models.TextField(blank=True, null=True)
    skill_level = models.CharField(max_length=255, null=True,
                                   choices=[('beginner', 'Beginner'), ('intermediate', 'Intermediate'),
                                            ('developing', 'Developing'), ('expert', 'Expert')], default='beginner')

    class Meta:
        unique_together = ('employee', 'skill_name')

class Training(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    training_title = models.CharField(max_length=255, null=True)
    country = models.ForeignKey('setting.Countries', on_delete=models.SET_NULL, null=True, blank=True)
    training_year = models.IntegerField(choices=year_choices(), default=current_year, null=True)
    institute = models.CharField(max_length=255, null=True)
    duration = models.IntegerField(null=True)
    duration_unit = models.CharField(max_length=10,
                                     choices=[('hours', 'Hours'), ('day', 'Day'), ('month', 'Month'), ('year', 'Year')],
                                     default='hours')
    certificate = models.FileField(upload_to='accounts/certificate/', blank=True, null=True)

    class Meta:
        unique_together = ('employee', 'training_title')

class ProfessionalCertificate(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    certificate_title = models.CharField(max_length=255, null=True)
    country = models.ForeignKey('setting.Countries', on_delete=models.SET_NULL, null=True, blank=True)
    institute = models.CharField(max_length=255, null=True)
    institute_address = models.TextField(blank=True, null=True)
    duration = models.IntegerField(null=True)
    duration_unit = models.CharField(max_length=10, choices=[('day', 'Day'), ('month', 'Month'), ('year', 'Year')],
                                     default='day')
    certificate = models.FileField(upload_to='accounts/certificate/', blank=True, null=True)

    class Meta:
        unique_together = ('employee', 'certificate_title')

class LanguageProficiency(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    language = models.CharField(max_length=255, null=True)
    description = models.TextField(blank=True, null=True)
    read = models.CharField(max_length=3, choices=[('yes', 'Yes'), ('no', 'No')], default='yes')
    write = models.CharField(max_length=3, choices=[('yes', 'Yes'), ('no', 'No')], default='yes')
    speak = models.CharField(max_length=3, choices=[('yes', 'Yes'), ('no', 'No')], default='yes')

    class Meta:
        unique_together = ('employee', 'language')

class EmploymentHistory(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    organization = models.CharField(max_length=255, null=True)
    designation = models.CharField(max_length=255, null=True)
    department = models.CharField(max_length=255, blank=True, null=True)
    start_from = models.DateField(verbose_name='From', null=True)
    to = models.DateField(null=True)
    salary = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Salary (Gross)', null=True, blank=True)

class Reference(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    ref_person_name = models.CharField(max_length=255, verbose_name='Ref. Person Name', null=True)
    relationship = models.CharField(max_length=255, null=True)
    designation = models.CharField(max_length=255, null=True)
    official_cell_number = models.CharField(max_length=255, verbose_name='Cell Number (Official)', null=True)
    personal_cell_number = models.CharField(max_length=255, verbose_name='Cell Number (Personal)', null=True,
                                            blank=True)
    official_email = models.EmailField(verbose_name='Email Address (Official)', null=True)
    personal_email = models.EmailField(verbose_name='Email Address (Personal)', null=True, blank=True)
    organization_name = models.CharField(max_length=255)
    address_line = models.TextField(null=True)
    country = models.ForeignKey('setting.Countries', on_delete=models.SET_NULL, null=True, blank=True)
    city = models.ForeignKey('setting.Cities', on_delete=models.SET_NULL, null=True, blank=True)
    state = models.ForeignKey('setting.States', on_delete=models.SET_NULL, null=True, blank=True)
    thana = models.CharField(max_length=255, blank=True, null=True)
    postal_code = models.IntegerField(blank=True, null=True)
    contact_person = models.CharField(max_length=255, blank=True, null=True, verbose_name='Contact Person Name')
    phone_number = models.CharField(max_length=100, null=True)

class Asset(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    asset_category = models.CharField(max_length=255, null=True)
    asset_brand_name = models.CharField(max_length=255, null=True)
    description = models.TextField(blank=True, null=True)
    serial_number = models.CharField(max_length=255, null=True)
    date_loaned = models.DateField(null=True)
    date_returned = models.DateField(null=True)

class Documents(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    resume = models.FileField(upload_to='accounts/resume/', blank=True, null=True)
    cover_letter = models.FileField(upload_to='accounts/cover_letter/', blank=True, null=True)
    appointment_letter = models.FileField(upload_to='accounts/appointment_letter/', blank=True, null=True)
    resign_letter = models.FileField(upload_to='accounts/resign_letter/', blank=True, null=True)

class OthersDocuments(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=255, null=True)
    file = models.FileField(upload_to='accounts/others_documents/', blank=True, null=True)

    class Meta:
        unique_together = ('employee', 'title')

class Attendance(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True,
                                 related_name='employee_attendance')
    schedule_type = models.ForeignKey('attendance.ScheduleMaster', on_delete=models.SET_NULL, null=True, blank=True,
                                      limit_choices_to={'status': True})
    punching_id = models.CharField(max_length=100, verbose_name='Punching ID', blank=True, null=True)
    calendar_master = models.ForeignKey('attendance.CalendarMaster', on_delete=models.SET_NULL, null=True, blank=True,
                                        related_name='employee_calendar', verbose_name='Calendar',
                                        limit_choices_to={'status': True})

class LeaveManage(Model):
    employee = models.ForeignKey(EmployeeIdentification, on_delete=models.CASCADE, null=True)
    leave_group = models.ForeignKey(LeaveGroup, on_delete=models.SET_NULL, null=True, blank=True,
                                    limit_choices_to={'status': True})
    overtime = models.BooleanField(default=False)
    overtime_group = models.ForeignKey('attendance.OvertimeRule', on_delete=models.SET_NULL, null=True, blank=True,
                                       related_name='employee_overtime', verbose_name='Select Overtime')
    deduction = models.BooleanField(default=False)
    deduction_group = models.ForeignKey(DeductionGroup, on_delete=models.SET_NULL, null=True, blank=True,
                                        related_name='employee_leave_deduction', limit_choices_to={'status': 'active'})


import logging
import six

from dj.choices import Choices
from django import forms
from django.contrib.auth.models import Group
from django.contrib.contenttypes import generic

from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.fields.related import add_lazy_relation
from django.utils.text import capfirst, slugify
from django.utils.translation import ugettext_lazy as _

from ralph.lib.mixins.models import AdminAbsoluteUrlMixin, TimeStampMixin
from .fields import (
    CustomFieldsWithInheritanceRelation,
    CustomFieldValueQuerySet
)

logger = logging.getLogger(__name__)

CUSTOM_FIELD_VALUE_MAX_LENGTH = 1000

STRING_CHOICE = Choices.Choice('string').extra(
    form_field=forms.CharField,
)
INTEGER_CHOICE = Choices.Choice('integer').extra(
    form_field=forms.IntegerField,
)
DATE_CHOICE = Choices.Choice('date').extra(
    form_field=forms.DateField,
)
URL_CHOICE = Choices.Choice('url').extra(
    form_field=forms.URLField,
)
CHOICE_CHOICE = Choices.Choice('choice list').extra(
    form_field=forms.ChoiceField,
)

class CustomFieldTypes(Choices):
    _ = Choices.Choice

    STRING = STRING_CHOICE
    INTEGER = INTEGER_CHOICE
    DATE = DATE_CHOICE
    URL = URL_CHOICE
    CHOICE = CHOICE_CHOICE

class CustomField(AdminAbsoluteUrlMixin, TimeStampMixin, models.Model):
    name = models.CharField(max_length=255, unique=True)
    attribute_name = models.SlugField(
        max_length=255, editable=False, unique=True,
        help_text=_("field name used in API. It's slugged name of the field"),
        db_index=True,
    )
    type = models.PositiveIntegerField(
        choices=CustomFieldTypes(), default=CustomFieldTypes.STRING.id
    )
    choices = models.TextField(
        null=True,
        blank=True,
        verbose_name=_('choices'),
        help_text=_('available choices for `choices list` separated by |'),
    )
    default_value = models.CharField(
        max_length=CUSTOM_FIELD_VALUE_MAX_LENGTH,
        help_text=_('for boolean use "true" or "false"'),
        null=True,
        blank=True,
        default='',
    )
    managing_group = models.ForeignKey(
        Group, blank=True, null=True,
        help_text=_(
            "When set, only members of the specified group will be "
            "allowed to set, change or unset values of this custom field "
            "for objects."
        )
    )
    use_as_configuration_variable = models.BooleanField(
        default=False,
        help_text=_(
            'When set, this variable will be exposed in API in '
            '"configuration_variables" section. You could use this later in '
            'configuration management tool like Puppet or Ansible.'
        )
    )
    # TODO: when required, custom validator (regex?), is_unique

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.attribute_name = slugify(self.name).replace('-', '_')
        super().save(*args, **kwargs)

    def _get_choices(self):
        if self.type in (
            CustomFieldTypes.CHOICE,
        ):
            return self.choices.split('|')
        return []

    def get_form_field(self):
        params = {
            'initial': self.default_value,
        }
        field_type = CustomFieldTypes.from_id(self.type)
        if issubclass(field_type.form_field, forms.ChoiceField):
            choices = self._get_choices()
            params.update({
                'choices': zip(choices, choices),
            })
        else:
            params.update({
                'required': False
            })
        return field_type.form_field(**params)

class CustomFieldValue(TimeStampMixin, models.Model):
    custom_field = models.ForeignKey(
        CustomField, verbose_name=_('key'), on_delete=models.PROTECT
    )
    # value is stored in charfield on purpose - ralph's custom field mechanism
    # is by-design simple, so it, for example, doesn't allow to filter by range
    # of integers or other Django filters like gte, lte.
    value = models.CharField(max_length=CUSTOM_FIELD_VALUE_MAX_LENGTH)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField(db_index=True)
    object = generic.GenericForeignKey('content_type', 'object_id')

    objects = models.Manager()
    # generic relation has to use specific manager (queryset)
    # which handle inheritance
    inherited_objects = CustomFieldValueQuerySet.as_manager()

    class Meta:
        unique_together = ('custom_field', 'content_type', 'object_id')

    def __str__(self):
        return '{} ({}): {}'.format(
            self.custom_field if self.custom_field_id else None,
            self.object,
            self.value
        )

    def _get_unique_checks(self, exclude=None):
        if exclude:
            for k in ['content_type', 'object_id']:
                try:
                    exclude.remove(k)
                except ValueError:
                    pass
        return super()._get_unique_checks()

    def unique_error_message(self, model_class, unique_check):
        """
        Return better unique validation message than standard Django message.
        """
        opts = model_class._meta

        params = {
            'model': self,
            'model_class': model_class,
            'model_name': six.text_type(capfirst(opts.verbose_name)),
            'unique_check': unique_check,
        }

        if len(unique_check) > 1:
            return ValidationError(
                message=_(
                    "Custom field of the same type already exists for this object."  # noqa
                ),
                code='unique_together',
                params=params,
            )
        return super().unique_error_message(self, model_class, unique_check)

    def clean(self):
        if self.custom_field_id:
            self.custom_field.get_form_field().clean(self.value)
        super().clean()

class CustomFieldMeta(models.base.ModelBase):
    def __new__(cls, name, bases, attrs):
        new_cls = super().__new__(cls, name, bases, attrs)
        new_cls._meta.custom_fields_inheritance_by_model = {}
        new_cls._meta.custom_fields_inheritance_by_path = {}
        # for each field in custom field inheritance, call
        # `add_custom_field_inheritance` - it will be called lazy, only when
        # model will be loaded
        for field_path, model in new_cls.custom_fields_inheritance.items():
            add_lazy_relation(
                new_cls, field_path, model, add_custom_field_inheritance
            )
        return new_cls

def add_custom_field_inheritance(field_path, model, cls):
    model._meta.custom_fields_inheritance_by_model[cls] = field_path
    cls._meta.custom_fields_inheritance_by_path[field_path] = cls

class WithCustomFieldsMixin(models.Model, metaclass=CustomFieldMeta):
    # TODO: handle polymorphic in filters
    custom_fields = CustomFieldsWithInheritanceRelation(CustomFieldValue)
    # mapping from field path (using Django __ convention) to model (provided
    # as string location of app_label and model name)
    custom_fields_inheritance = {}

    class Meta:
        abstract = True

    @property
    def custom_fields_as_dict(self):
        return {
            cfv.custom_field.name: cfv.value
            for cfv in self.custom_fields.select_related('custom_field')
        }

    @property
    def custom_fields_configuration_variables(self):
        return {
            cfv.custom_field.name: cfv.value
            for cfv in self.custom_fields.filter(
                custom_field__use_as_configuration_variable=True
            ).select_related('custom_field')
        }

    def update_custom_field(self, name, value):
        cf = CustomField.objects.get(name=name)
        cfv, _ = self.custom_fields.get_or_create(custom_field=cf)
        cfv.value = value
        cfv.save(update_fields=['value'])

    def clear_children_custom_field_value(self, custom_field):
        """
        For each model inheriting `custom_field` from self (in practice
        for each model inheriting, which have this custom_field set to any
        value), delete their `CustomFieldValue`s.
        """
        for model, field_path in self._meta.custom_fields_inheritance_by_model.items():  # noqa: E501
            custom_fields_values_to_delete = CustomFieldValue.objects.filter(
                custom_field=custom_field,
                content_type=ContentType.objects.get_for_model(model),
                object_id__in=model._default_manager.filter(
                    **{field_path: self}
                ).values_list('pk', flat=True),
            )
            logger.warning(
                'Deleting %s CFVs for descendants of %s (%s by %s)',
                custom_fields_values_to_delete.count(), self,
                model, field_path
            )
            custom_fields_values_to_delete.delete()


import random as rd

def insereValorConjunto(conjunto):
    for i in range(10):
        conjunto.add(rd.randint(0, 10))
    return conjunto

conjunto1 = set()
conjunto1 = insereValorConjunto(conjunto1)

conjunto2 = set()
conjunto2 = insereValorConjunto(conjunto2)

print(conjunto1.difference(conjunto2))
print(conjunto2.difference(conjunto1))

print(conjunto1.intersection(conjunto2))


# mc-control.py
import os
import configparser
from configparser import ConfigParser
from discord.ext import commands
import random
import time

# Define functions
parser = configparser.ConfigParser()

bot = commands.Bot(command_prefix='!')

# Function to receive input from screen log
def fetch():
    time.sleep(12)
    logpath = "%s/logs" % mc_installpath
    print("Getting results from:" + logpath)
    loglist = os.listdir(logpath)
    loglist.sort(reverse=True)
    logpath = "%s/logs/%s" % (mc_installpath, loglist[0])
    with open(logpath, 'r') as f:
        lines = f.read().splitlines()
        output_line = lines[-1]
    scr_output = output_line[22:]
    return scr_output

# Function to create local logs for Minecraft commands
def local_log(log_content):
    base_dir = os.listdir()
    if "logs" not in base_dir:
        os.makedirs("./logs")
    logs_list = os.listdir("./logs")
    cur_log = []
    for i in logs_list:
        if (int(time.time()) - int(i[:10])) < 86400:
            cur_log.append(i)
    if cur_log:
        cur_log.sort(reverse=True)
        cur_log = "./logs/" + cur_log[0]
        with open(cur_log, 'a') as f:
            f.write(log_content + "\n")
            f.close()
    else:
        cur_log = "./logs/" + str(int(time.time())) + "_log.txt"
        with open(cur_log, 'w') as f:
            f.write(log_content + "\n")
            f.close()

# Global vars
install_path = os.getcwd()

# Divide INI file into global vars
parser.read('%s/config.ini' % install_path)

try:
    # Discord
    dc_token = parser.get('discord', 'token')
    dc_guild = parser.get('discord', 'guild')
    dc_channel = parser.get('discord', 'active_channel')

    # Server
    server_name = parser.get('server', 'name')
    mc_installpath = parser.get('server', 'mc_installpath')

    # !give filters
    give_filter = parser.get('command_filters', 'give')
    give_filter.split(",")

    # !summon filters
    summon_filter = parser.get('command_filters', 'summon')
    summon_filter.split(",")

# If INI parsing fails, create the file
except configparser.NoSectionError:
    print("config.ini not found or is not correctly configured.")
    print("would you like to create it?")
    create_file = input("y/n:")
    if create_file.lower() == "y":
        print("Creating file")
        # Creating config def
        config = ConfigParser()
        print("Let's set up your Discord config first.")
        token = input("Discord token: ")
        guild = input("Your Discord guild: ")
        active_channel = input("Your active channel: ")
        print("Now, we'll set up the config for your server.")
        server_install_path = input("Enter the path that your Minecraft installation is running at: ")
        name = input("Your Minecraft server name: ")
        print(
            "Finally, if you wish to have filters for your commands, you may edit the .ini file that will be created."
        )
        config["discord"] = {
            "token": token,
            "guild": guild,
            "active_channel": active_channel,
        }
        config["server"] = {
            "mc_installpath": server_install_path,
            "name": name,
        }
        config["command_filters"] = {
            "give": "",
            "summon": "",
        }
        with open("config.ini", 'w') as output_file:
            config.write(output_file)
        print("config.ini has been created. Please re-run this program to start your server.")
        exit(0)
    else:
        print("File will not be created. Please create the config.ini document and attempt to run the program again.")
        exit(1)

# Connect to Discord bot
@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')

# !rain
@bot.command(name='rain', help='Makes it rain or snow on the server')
async def make_rain(ctx):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        print("Making it rain")
        local_log(f"{time_called} {author} executed: weather rain")
        os.system("""screen -S %s -p 0 -X stuff "weather rain^M" """ % server_name)
        message = [
            "Hello Seattle!",
            "The clouds are peeing",
            "I always like walking in the rain, so no one can see me crying",
            "Rainy days should be spent at home with a cup of tea and a good book",
            "Those who hate rain hate life"
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !clear
@bot.command(name='clear', help='Makes the weather clear')
async def make_clear(ctx):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        print("Making it clear")
        local_log(f"{time_called} {author} executed: weather clear")
        os.system("""screen -S %s -p 0 -X stuff "weather clear^M" """ % server_name)
        message = [
            "A cloudy day is no match for a sunny disposition!",
            "Just direct your feet to the sunny side of the street",
            "We're in the money, the skies are sunny; old man depression, you are through, you done us wrong!",
            "I don't complain when it's sunny",
            "What a bright sunny day, and I don't know what to say..."
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !thunder
@bot.command(name='thunder', help='Makes the weather thunder')
async def make_thunder(ctx):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        print("Making it thunder")
        local_log(f"{time_called} {author} executed: weather thunder")
        os.system("""screen -S %s -p 0 -X stuff "weather thunder^M" """ % server_name)
        message = [
            "If the tranquillity is killing you, seek for the storm to save your life!",
            "A storm will always have a chaotic chorus of accompaniment",
            "A person with storms inside does not feel the storm outside!",
            "Hard storms make great sailors",
            "When the storm seems to overpower you, hold tight, for it is only passing"
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !sunrise
@bot.command(name='sunrise', help='Sets time to sunrise')
async def make_sunrise(ctx):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        print("Making it sunrise")
        local_log(f"{time_called} {author} executed: time set sunrise")
        os.system("""screen -S %s -p 0 -X stuff "time set sunrise^M" """ % server_name)
        message = [
            "The sun does not rise or set. The earth rotates",
            "A sunset is only half of the story",
            "Watching the sunrise every morning is a blessing",
            "The first brush of violet painted the horizon",
            "The fact that it’s a new day won’t matter if I don’t greet it with a new attitude"
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !midnight
@bot.command(name='midnight', help='Sets time to midnight')
async def make_midnight(ctx):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        print("Making it midnight")
        local_log(f"{time_called} {author} executed: time set midnight")
        os.system("""screen -S %s -p 0 -X stuff "time set midnight^M" """ % server_name)
        message = [
            "All great beginnings start in the dark, when the moon greets you to a new day at midnight",
            "It's almost midnight, a great time to get lost and find yourself again",
            "At midnight, in the month of June, I stand beneath the mystic moon",
            "Midnight's the only time where you can be both in the past, present, and future",
            "Welcome to the place on the other side of midnight"
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !noon
@bot.command(name='noon', help='Sets time to noon')
async def make_noon(ctx):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        print("Making it noon")
        local_log(f"{time_called} {author} executed: time set noon")
        os.system("""screen -S %s -p 0 -X stuff "time set noon^M" """ % server_name)
        message = [
            "Never get out of bed before noon",
            "Nothing. And, I don't start before noon",
            "The trouble with morning is that it comes well before noon",
            "When a civilization takes up the study of itself, it is always high noon",
            "I do not believe there is life before noon"
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !night
@bot.command(name='night', help='Sets time to night')
async def make_night(ctx):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        print("Making it night")
        local_log(f"{time_called} {author} executed: time set night")
        os.system("""screen -S %s -p 0 -X stuff "time set night^M" """ % server_name)
        message = [
            "I have loved the stars too fondly to be fearful of the night",
            "How did it get so late so soon?",
            "The trouble with morning is that it comes well before noon",
            "What hath night to do with sleep?",
            "Sleep is such a luxury, which i cant afford"
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !give
@bot.command(name='give', help='Gives a user an object. e.g. (!give XrayOven bucket')
async def give(ctx, *args):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        args[1].replace(" ", "")
        if args[1] in give_filter:
            await ctx.send("You have been blocked form using this command by the server admin team.")
            local_log(f"{time_called} {author} was blocked from executing: give {args[0]} {args[1]}")
            return()
        print(f"Giving {args[0]} {args[1]}")
        local_log(f"{time_called} {author} executed: give {args[0]} {args[1]}")
        os.system("""screen -S %s -p 0 -X stuff "give %s %s^M" """ % (server_name, args[0], args[1]))
        message = [
            "It's not how much we give but how much love we put into giving",
            "We make a living by what we get. We make a life by what we give.",
            "Happiness doesn't result from what we get, but from what we give",
            "For it is in giving that we receive",
            "Giving does not only precede receiving; it is the reason for it. It is in giving that we receive."
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !summon
@bot.command(name='summon', help='Summon an entity to a user. e.g. (!summon wolf XrayOven')
async def give(ctx, *args):
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        args[0].replace(" ", "")
        if args[0] in summon_filter:
            await ctx.send("You have been blocked form using this command by the server admin team.")
            local_log(
                f"{time_called} {author} was blocked from executing:"
                f" execute {args[1]} ~ ~ ~ summon {args[0]} ~ ~ ~"
            )
            return ()
        print("Summoning " + args[0] + "to " + args[1])
        local_log(
            f"{time_called} {author} executed:"
            f" execute {args[1]} ~ ~ ~ summon {args[0]} ~ ~ ~"
        )
        os.system(
            """screen -S %s -p 0 -X stuff "execute %s ~ ~ ~ summon %s ~ ~ ~^M" """ % (server_name, args[1], args[0])
        )
        message = [
            "A friend is someone who knows all about you and still loves you",
            "There is nothing better than a friend, unless it is a friend with chocolate",
            "I would rather walk with a friend in the dark, than alone in the light",
            "Only a true best friend can protect you from your immortal enemies",
            "I got you to look after me, and you got me to look after you, and that's why"
        ]
        await ctx.send(random.choice(message))
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

# !players
@bot.command(name='players', help="List all logged in users.")
async def players(ctx):
    await ctx.send("Let me check that")
    from_channel = str(ctx.channel)
    time_called = int(time.time())
    author = ctx.author
    if from_channel == dc_channel:
        print("Listing players")
        local_log(f"{time_called} {author} executed: list")
        os.system(
            """screen -S %s -p 0 -X stuff "list^M" """ % server_name
        )
        players_ls = fetch()
        if len(players_ls) > 1:
            if players_ls.find(",") > 0:
                if players_ls.find(",") > 1:
                    last_comma = players_ls.rindex(',')
                    players_ls = players_ls[:last_comma] + " and" + players_ls[last_comma + 1:]
                    await ctx.send(players_ls + " are online")
                else:
                    last_comma = players_ls.rindex(',')
                    players_ls = players_ls[:last_comma - 1] + " and" + players_ls[last_comma + 1:]
                    await ctx.send(players_ls + " are online")
            else:
                await ctx.send(players_ls + " is online")
        else:
            await ctx.send("There are no players online. Sad, really...")
    else:
        await ctx.send("""Commands must be sent in the "server-commands" channel""")

bot.run(dc_token)


class BinaryTreeNode:
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None

def preOrder(root):
    #Base Case
    if(root is None):
        return None

    #Induction Hypothesis
    print(root.data,end=" ")
    preOrder(root.left)
    preOrder(root.right)

    return root

def treeInput():
    rootData = int(input())
    if(rootData == -1):
        return None
    root = BinaryTreeNode(rootData)
    leftRoot = treeInput()
    rightRoot = treeInput()

    root.left = leftRoot
    root.right = rightRoot

    return root

root = treeInput()
preOrder(root)


from typing import Optional

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        self.target_sum = targetSum
        return self.solve(root, 0)

    def solve(self, root: Optional[TreeNode], curr_sum: int) -> bool:
        if root:
            new_sum = curr_sum + root.val
            if root.left or root.right:
                left_has_sum = self.solve(root.left, new_sum)
                right_has_sum = self.solve(root.right, new_sum)
                return left_has_sum or right_has_sum
            return new_sum == self.target_sum
        return False

s = Solution()

root = TreeNode(
    5,
    TreeNode(
        4,
        TreeNode(
            11,
            TreeNode(7),
            TreeNode(2),
        ),
    ),
    TreeNode(
        8,
        TreeNode(13),
        TreeNode(
            4,
            None,
            TreeNode(1),
        ),
    ),
)

root = TreeNode(1, TreeNode(2), TreeNode(3))

print(s.hasPathSum(root, 5))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render, redirect

def index(request):
    request.session['purchase'] = []
    return render(request, 'amadon/index.html')

def process(request):
    purchase = {}
    for key, value in request.POST.items():
        if key!="csrfmiddlewaretoken":
            purchase[key] = value

    if purchase['product_id'] == '10':
        purchase['product'] = 'Drone'
        purchase['total'] = int(purchase['quantity'])*59.99
    elif purchase['product_id'] == '20':
        purchase['product'] = 'Props'
        purchase['total'] = int(purchase['quantity'])*5.99
    elif purchase['product_id'] == '30':
        purchase['product'] = 'Motors'
        purchase['total'] = int(purchase['quantity'])*15.99
    else:
        purchase['product'] = 'ECM Board'
        purchase['total'] = int(purchase['quantity'])*19.99

    request.session['purchase'] = []
    request.session['purchase'] = purchase

    return redirect('/checkout')

def checkout(request):
    return render(request, 'amadon/checkout.html')


import threading as th
def mergeSort(arr):
    if len(arr)>1:
        mid = len(arr)/2
        lefthalf = arr[:mid]
        righthalf = arr[mid:]
        t1 = th.Thread(target=mergeSort, args=(lefthalf,))
        t2 = th.Thread(target=mergeSort, args=(righthalf,))
        t1.start()
        t2.start()
        t1.join()
        t2.join()
        i=0
        j=0
        k=0
         # print "lefthalf: ",lefthalf
        # print "righthalf: ",righthalf
        while i<len(lefthalf) and j<len(righthalf):
        #    print lefthalf[i]," ",righthalf[j]
            if lefthalf[i]<righthalf[j]:
                arr[k]=lefthalf[i]
                i=i+1
                k=k+1
            else:
                arr[k]=righthalf[j]
                j=j+1
                k=k+1
        while i < len(lefthalf):
            arr[k]=lefthalf[i]
            i=i+1
            k=k+1
        while j < len(righthalf):
            arr[k]=righthalf[j]
            j=j+1
            k=k+1
         # print "merging", arr
 #
# arr = [13,4,1,7,90,24,113,63]
# mergeSort(arr)


import os
import random
import uuid

import numpy as np

import paddle
from paddle.io import RandomSampler, SequenceSampler
from paddle.io import DataLoader as paddleDataLoader
from paddle.fluid.dataloader.collate import default_collate_fn

from .samplers import YoloBatchSampler

def get_yolox_datadir():
    """
    get dataset dir of YOLOX. If environment variable named `YOLOX_DATADIR` is set,
    this function will return value of the environment variable. Otherwise, use data
    """
    yolox_datadir = os.getenv("YOLOX_DATADIR", None)
    if yolox_datadir is None:
        import yolox

        yolox_path = os.path.dirname(os.path.dirname(yolox.__file__))
        yolox_datadir = os.path.join(yolox_path, "datasets")
    return yolox_datadir

class InfiniteDataLoader(paddleDataLoader):
    """ Dataloader that reuses workers
    Uses same syntax as vanilla DataLoader
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
        self.iterator = super().__iter__()

    def __len__(self):
        return len(self.batch_sampler.sampler)

    def __iter__(self):
        for i in range(len(self)):
            yield next(self.iterator)

class _RepeatSampler:
    """ Sampler that repeats forever
    Args:
        sampler (Sampler)
    """

    def __init__(self, sampler):
        self.sampler = sampler

    def __iter__(self):
        while True:
            yield from iter(self.sampler)

class DataLoader(paddleDataLoader):
    """
    Lightnet dataloader that enables on the fly resizing of the images.
    See :class:`paddle.io.DataLoader` for more information on the arguments.
    Check more on the following website:
    https://gitlab.com/EAVISE/lightnet/-/blob/master/lightnet/data/_dataloading.py
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__initialized = False
        shuffle = False
        batch_sampler = None
        if len(args) > 5:
            shuffle = args[2]
            sampler = args[3]
            batch_sampler = args[4]
        elif len(args) > 4:
            shuffle = args[2]
            sampler = args[3]
            if "batch_sampler" in kwargs:
                batch_sampler = kwargs["batch_sampler"]
        elif len(args) > 3:
            shuffle = args[2]
            if "sampler" in kwargs:
                sampler = kwargs["sampler"]
            if "batch_sampler" in kwargs:
                batch_sampler = kwargs["batch_sampler"]
        else:
            if "shuffle" in kwargs:
                shuffle = kwargs["shuffle"]
            if "sampler" in kwargs:
                sampler = kwargs["sampler"]
            if "batch_sampler" in kwargs:
                batch_sampler = kwargs["batch_sampler"]

        # Use custom BatchSampler
        if batch_sampler is None:
            if sampler is None:
                if shuffle:
                    sampler = RandomSampler(self.dataset)
                else:
                    sampler = SequenceSampler(self.dataset)
            batch_sampler = YoloBatchSampler(
                sampler,
                self.batch_size,
                self.drop_last
            )
            # batch_sampler = IterationBasedBatchSampler(batch_sampler, num_iterations =

        self.batch_sampler = batch_sampler

        self.__initialized = True

    def close_mosaic(self):
        self.batch_sampler.mosaic = False

def list_collate(batch):
    """
    Function that collates lists or tuples together into one list (of lists/tuples).
    Use this as the collate function in a Dataloader, if you want to have a list of
    items as an output, as opposed to tensors (eg. Brambox.boxes).
    """
    items = list(zip(*batch))

    for i in range(len(items)):
        if isinstance(items[i][0], (list, tuple)):
            items[i] = list(items[i])
        else:
            items[i] = default_collate_fn(items[i])

    return items

def worker_init_reset_seed(worker_id):
    seed = uuid.uuid4().int % 2**32
    random.seed(seed)
    paddle.seed(seed)
    paddle.set_cuda_rng_state(paddle.get_cuda_rng_state())
    np.random.seed(seed)


import boto3
from botocore.exceptions import ClientError

ec2 = boto3.client('ec2')
ec2resource = boto3.resource('ec2')

response = ec2.describe_instances()
# print(response)
# print(len(response['Reservations'])) # there are 5 instances here

def list_ec2_instances():
	instances = {}
	res = ec2.describe_instances() # response object is a nested dictionary
	for r in res['Reservations']:
		for ins in r['Instances']:
			if ins['State']['Name'] == 'running':
				instances[ins['InstanceId']] = ins['PublicIpAddress']
	print(instances)

def list_images():
	res = ec2.describe_images(Owners=['self'])
	for img in res['Images']:
		print("Name: ",img['Name'])
		print("Image: ", img['ImageId'])
		print("Description: ", img['Description'])
		print("----")

def update_security_group():
    security_groups = []
    res = ec2.describe_instances()
    for r in res['Reservations']:
        for ins in r['Instances']:
            id = ins['SecurityGroups'][0]['GroupId']
            security_group = ec2resource.SecurityGroup(id)
            security_groups.append(security_group)
    return security_groups

def describe_security_groups(SECURITY_GROUP_ID):
    try:
        response = ec2.describe_security_groups(GroupIds=[SECURITY_GROUP_ID])
        print(response)
    except ClientError as e:
        print(e)

describe_security_groups(update_security_group()[0])


import argparse
import json
import os

import src.utils as utils
import src.dataloaders as data
import src.models as models
import src.trainers as trainers
import src.transforms as transforms
import src.trainers.handlers as handlers

def _parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', type=argparse.FileType('r'),
                        help='path to train config in *.json')
    parser.add_argument('--datapath', type=utils.dir_path, help='path to dataset dir')
    parser.add_argument('--saved-models', type=utils.dir_path, help='path to saved models dir',
                        default='./saved')
    parser.add_argument('--output', type=str, help='path to checkpoint dir')
    return parser.parse_args()

def get_dataloaders(config, datapath: str) -> (data.DataLoader, data.DataLoader):
    train_dataset: data.Dataset = data.TableDataset(os.path.join(datapath, config['data']['root']),
                                                    os.path.join(datapath,
                                                                 config['data']['table']),
                                                    data.DataLoaderMode.TRAINING,
                                                    config['data'].get('is_wav', False))
    train_dataset = data.TransformedDataset(train_dataset, transforms.SpecAugTransformer())
    train_loader: data.DataLoader = data.ClassificationDataLoader(train_dataset,
                                                                  config['data']['batch_size'],
                                                                  config['data'].get('cuda', True))

    val_dataset: data.Dataset = \
        data.TableDataset(os.path.join(datapath, config['data']['root']),
                          os.path.join(datapath,
                                       config['data'].get('val_table', config['data']['table'])),
                          data.DataLoaderMode.VALIDATION,
                          config['data'].get('is_wav', False))
    val_loader: data.DataLoader = \
        data.ClassificationDataLoader(val_dataset,
                                      config['data'].get('val_batch_size',
                                                         config['data']['batch_size']),
                                      config['data'].get('cuda', True))
    return train_loader, val_loader

def build_trainer(config, train_loader: data.DataLoader,
                  val_loader: data.DataLoader, model_io: models.ModelIO,
                  output_dir: str) -> trainers.Trainer:
    validation_validator: handlers.MetricHandler = \
        handlers.MetricHandler(val_loader,
                               batch_count=None,
                               mode=handlers.ValidationMode.VALIDATION,
                               metrics=['xent', 'multiacc'])
    training_validator: handlers.MetricHandler = \
        handlers.MetricHandler(train_loader,
                               batch_count=config['batches_per_validation'],
                               mode=handlers.ValidationMode.TRAINING,
                               metrics=['xent', 'multiacc'])

    printer: handlers.Printer = handlers.Printer(config['epochs'], config['batches_per_epoch'],
                                                 ['xent_train', 'xent_val', 'multiacc_val'])
    printer_handler: handlers.PrinterHandler = handlers.PrinterHandler(printer)
    saver: handlers.ModelSaver = handlers.ModelSaver(model_io, config, output_dir,
                                                     epoch_rate=config['save_after'])
    post_epoch_handlers = [validation_validator, training_validator, saver, printer_handler]
    trainer: trainers.Trainer = trainers.DefaultTrainer([], [printer_handler], post_epoch_handlers)
    return trainer

def main():
    args = _parse_args()
    config = json.loads(args.config.read())
    train_loader, val_loader = get_dataloaders(config, args.datapath)
    print(f'Model output [{config["model"]["head"]["output"]}]')
    print(f'Train labels [{len(train_loader.get_labels())}]')
    assert len(train_loader.get_labels()) == config['model']['head']['output']
    assert len(val_loader.get_labels()) == config['model']['head']['output']
    model_io: models.ModelIO = models.ModelIO(args.saved_models)
    model: models.Model = model_io.build_model(config)
    trainer: trainers.Trainer = build_trainer(config, train_loader, val_loader, model_io,
                                              args.output)
    training_params: trainers.TrainingParams = trainers.TrainingParams(
        batch_count=config['batches_per_epoch'],
        batch_size=config['data']['batch_size'],
        epoch_count=config['epochs'])
    trainer.train([model], train_loader, training_params)
    model_io.save_model(config, model, os.path.join(args.output, 'final'))
    print('DONE')

if __name__ == "__main__":
    main()


"""
781 Rabbits in Forest

In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them.
Those answers are placed in an array.

Return the minimum number of rabbits that could be in the forest.

Examples:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit than answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

Input: answers = [10, 10, 10]
Output: 11

Input: answers = []
Output: 0
Note:

answers will have length at most 1000.
Each answers[i] will be an integer in the range [0, 999].
"""
class Solution:
    # the same-color rabbits can answer x for at most (x+1) times
    def numRabbits(self, answers):
        repeat, res = {}, 0
        for ans in answers:
            if ans not in repeat:   # answer not shown before, this is a new group
                res += ans + 1
                repeat[ans] = 1
            else:
                repeat[ans] += 1    # update repeat times of this color group

            if repeat[ans] > ans + 1:   # the same-color rabbits can answer x for at most (x+1) times, otherwise it's a new color group
                res += ans + 1
                repeat[ans] = 1

        return res
    # my own solution
    # check the number of unique answers
    def numRabbits_Wrong(self, answers):
        """
        :type answers: List[int]
        :rtype: int
        """
        unique = set(answers)
        if 0 in unique: # bug fixed: should consider 0
            unique.remove(0)

        return sum(unique) + len(unique)

#answers = [1,0,1,0,0]   # expected 5
answers = [0, 0, 1, 1, 1]   # expected 6
print(Solution().numRabbits(answers))


"""
This is a django-split-settings main file.
For more information read this:
https://github.com/sobolevn/django-split-settings
https://sobolevn.me/2017/04/managing-djangos-settings
To change settings file:
`DJANGO_ENV=production python manage.py runserver`
"""

from os import environ

import django_stubs_ext
from split_settings.tools import include

# Monkeypatching Django, so stubs will work for all generics,
# see: https://github.com/typeddjango/django-stubs
django_stubs_ext.monkeypatch()

# Managing environment via `DJANGO_ENV` variable:
environ.setdefault("DJANGO_ENV", "development")
_ENV = environ["DJANGO_ENV"]

_base_settings = (
    "components/common.py",
    "components/db_settings.py",
    "components/debug_toolbar_settings.py",
    "components/installed_apps.py",
    "components/middleware_settings.py",
    "components/rest_framework_settings.py",
    "components/swagger_settings.py",
)

# Include settings:
include(*_base_settings)


from django.db import models
from assessmentbaseinfo.models import AssessmentProfile, Metric
from uuid import uuid4
from django.utils.text import slugify
from assessmentbaseinfo.models import AnswerTemplate
from assessmentbaseinfo.models import QualityAttribute
from assessmentcore.models import Space

class Color(models.Model):
    title = models.CharField(max_length=40)
    color_code = models.CharField(max_length=20)

class AssessmentProject(models.Model):

    STATUS_CHOICES = [
        ('WEAK', 'WEAK'),
        ('RISKY', 'RISKY'),
        ('NORMAL', 'NORMAL'),
        ('GOOD', 'GOOD'),
        ('OPTIMIZED', 'OPTIMIZED')
    ]

    id = models.UUIDField(primary_key=True, default=uuid4)
    code = models.SlugField(max_length=100)
    title = models.CharField(max_length=100)
    description = models.TextField()
    creation_time = models.DateTimeField(auto_now_add=True)
    last_modification_date = models.DateTimeField(auto_now=True)
    assessment_profile = models.ForeignKey(AssessmentProfile, on_delete=models.PROTECT, related_name='assessment_projects')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, null=True)
    color = models.ForeignKey(Color, on_delete=models.PROTECT, null=True)
    space = models.ForeignKey(Space, on_delete=models.PROTECT, null=True)

    def __str__(self) -> str:
        return self.title

    def save(self, *args, **kwargs):
        self.code = slugify(self.title)
        default_profile = AssessmentProfile.objects.filter(is_default = True).values()[0]
        self.assessment_profile_id = default_profile['id']
        super(AssessmentProject, self).save(*args, **kwargs)
        if not AssessmentResult.objects.filter(assessment_project_id = self.id).exists():
            AssessmentResult.objects.create(assessment_project_id = self.id)

class AssessmentResult(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid4)
    assessment_project = models.ForeignKey(AssessmentProject, on_delete=models.CASCADE, related_name='assessment_results')

class QualityAttributeValue(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid4)
    assessment_result = models.ForeignKey(AssessmentResult, on_delete=models.CASCADE, related_name='quality_attribute_values')
    quality_attribute = models.ForeignKey(QualityAttribute, on_delete=models.CASCADE, related_name='quality_attribute_values', null=True)
    maturity_level_value = models.PositiveIntegerField(null=True)

class MetricValue(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid4)
    assessment_result = models.ForeignKey(AssessmentResult, on_delete=models.CASCADE, related_name='metric_values')
    metric = models.ForeignKey(Metric, on_delete=models.CASCADE, related_name='metric_values')
    answer = models.ForeignKey(AnswerTemplate, on_delete=models.CASCADE, null=True)