import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import scipy.stats as stats
from matplotlib.patches import Ellipse

sizes = [20, 60, 100]
cor = [0, 0.5, 0.9]
r, rs, rq = [], [], []
r_2, rs_2, rq_2 = [], [], []

def setEllipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs):
    cov = np.cov(x, y)
    pearson = cov[0, 1] / np.sqrt(cov[0, 0] * cov[1, 1])
    ell_radius_x = np.sqrt(1 + pearson)
    ell_radius_y = np.sqrt(1 - pearson)
    ellipse = Ellipse((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2, facecolor=facecolor, **kwargs)
    scale_x = np.sqrt(cov[0, 0]) * n_std
    mean_x = np.mean(x)
    scale_y = np.sqrt(cov[1, 1]) * n_std
    mean_y = np.mean(y)
    transf = transforms.Affine2D().rotate_deg(45).scale(scale_x, scale_y).translate(mean_x, mean_y)
    ellipse.set_transform(transf + ax.transData)
    return ax.add_patch(ellipse)

def plotEllipse(size):
    mean = [0, 0]
    fig, ax = plt.subplots(1, 3)
    fig.suptitle("n = " + str(size))
    titles = [r'$ \rho = 0$', r'$\rho = 0.5 $', r'$ \rho = 0.9$']
    num = 0
    for j in cor:
        cov = [[1.0, j], [j, 1.0]]
        rv = stats.multivariate_normal.rvs(mean, cov, size=size)
        x = rv[:, 0]
        y = rv[:, 1]
        ax[num].scatter(x, y, s=3)
        setEllipse(x, y, ax[num], edgecolor='navy')
        ax[num].scatter(np.mean(x), np.mean(y), c='aqua', s=3)
        ax[num].set_title(titles[num])
        num += 1
    plt.show()

def quadrant(x, y):
    size = len(x)
    med_x = np.median(x)
    med_y = np.median(y)
    x_new = np.empty(size, dtype=float)
    x_new.fill(med_x)
    x_new = x - x_new
    y_new = np.empty(size, dtype=float)
    y_new.fill(med_y)
    y_new = y - y_new
    n = [0, 0, 0, 0]
    for i in range(size):
        if x_new[i] >= 0 and y_new[i] >= 0:
            n[0] += 1
        if x_new[i] < 0 and y_new[i] > 0:
            n[1] += 1
        if x_new[i] < 0 and y_new[i] < 0:
            n[2] += 1
        if x_new[i] > 0 and y_new[i] < 0:
            n[3] += 1
    return ((n[0] + n[2]) - (n[1] + n[3])) / size

def Calculation(name, size):
    for rep in range(1000):
        if name == "two":
            rvs = stats.multivariate_normal.rvs([0, 0], [[1.0, j], [j, 1.0]], size=size)
        elif name == "mix":
            rvs = 0.9 * stats.multivariate_normal.rvs([0, 0], [[1.0, 0.9], [0.9, 1.0]], size=size) \
                  + 0.1 * stats.multivariate_normal.rvs([0, 0], [[10, -0.9], [-0.9, 10]], size=size)
        x = rvs[:, 0]
        y = rvs[:, 1]
        r.append(stats.pearsonr(x, y)[0])
        r_2.append(r[rep] ** 2)
        rs.append(stats.spearmanr(x, y)[0])
        rs_2.append(rs[rep] ** 2)
        rq.append(quadrant(x, y))
        rq_2.append(rq[rep] ** 2)

def Print(name, size, cor):
    if name == "two":
        print("n = " + str(size), "cor = " + str(cor))
    elif name == "mix":
        print("n = " + str(size))
    print(np.around(np.mean(r), decimals=3), np.around(np.mean(rs), decimals=3), np.around(np.mean(rq), decimals=3))
    print(np.around(np.mean(r_2), decimals=3), np.around(np.mean(rs_2), decimals=3),
          np.around(np.mean(rq_2), decimals=3))
    print(np.around(np.std(r) ** 2, decimals=3), np.around(np.std(rs) ** 2, decimals=3),
          np.around(np.std(rq) ** 2, decimals=3), "\n")

print("Двумерное нормальное распределение")
for i in sizes:
    for j in cor:
        Calculation("two", i)
        Print("two", i, j)
        r.clear(), rs.clear(), rq.clear(), r_2.clear(), rs_2.clear(), rq_2.clear()
    plotEllipse(i)

print("Смесь нормальных распределений")
for i in sizes:
    Calculation("mix", i)
    Print("two", i, 0)
    r.clear(), rs.clear(), rq.clear(), r_2.clear(), rs_2.clear(), rq_2.clear()


import unittest

import day14
import utils

class TestDay1(unittest.TestCase):
    def test_first(self):
        program = utils.parse_file_lines("day14_test_input1.txt", str)
        self.assertEqual(
            day14.initialize(program),
            165)

    def test_second(self):
        program = utils.parse_file_lines("day14_test_input2.txt", str)
        self.assertEqual(
            day14.initialize_2(program),
            208)


import numpy as np
import random

class EasyBot():
    def __init__(self):
        self.hits_map = np.zeros([10,10]) #local map of enemy board
        self.ship_map = np.zeros([10,10]) #local map of own ships for placement use
        self.ships = {"Carrier": [False,5,list()], "Battleship": [False,4,list()], "Submarine": [False,3,list()], "Cruiser": [False,3,list()],"Destroyer": [False,2,list()]} #local temp copy of ships list
        self.success_log = ["log start:"] #log of past impacts, filled with hit or miss
        self.p_ships = {"Carrier": [True,5], "Battleship": [True,4], "Submarine": [True,3], "Cruiser": [True,3],"Destroyer": [True,2]} #bot keeps track of active ships
        self.ships_sunk_coords = []

    def set_ships(self):
        """takes in no arguments
        returns a dictionary with an array of values in form [bool(ship in play), int(ship length), list(coords in array form)]"""
        for key in self.ships:
            while True:

                start_x_coord = np.random.randint(0,10)
                start_y_coord = np.random.randint(0,10)
                if self.ship_map[start_x_coord][start_y_coord] == 0:
                    break
            while True:

                #get the ship length
                ship_length = self.ships[key][1]
                #Get decision
                choice = random.choice(["up","down","left","right"])

                #placing is available bool
                place = True

                if choice == "left":
                    #check if the last point exists
                    if start_x_coord - ship_length < 0:
                        #last point doesn't exist do nothing
                        print("bot thinking")
                    else:
                        for i in range(ship_length):
                        #else check if everypoint exists and is free
                            #if it isn't place = False
                            if self.ship_map[start_x_coord-i][start_y_coord] == 1:
                                place = False
                        if place == True:
                        #if it passes loop succesfully and place is still true
                            for i in range(ship_length):
                                #loop through everypoint and add to the ship's list and local ship map
                                self.ships[key][2].append([start_x_coord-i, start_y_coord])
                                self.ship_map[start_x_coord-i][start_y_coord] = 1
                            #afterwards set ship in play to true
                            self.ships[key][0] = True
                            #continue and break while loop
                            break

                elif choice == "right":
                    #everything above
                    if start_x_coord + ship_length > 9:
                        print("bot thinking")
                    else:
                        for i in range(ship_length):
                            if self.ship_map[start_x_coord+i][start_y_coord] == 1:
                                place = False
                        if place == True:
                            for i in range(ship_length):
                                self.ships[key][2].append([start_x_coord+i,start_y_coord])
                                self.ship_map[start_x_coord+i][start_y_coord] = 1
                            self.ships[key][0] = True
                            break
                elif choice == "down":
                    #everything above
                    if start_y_coord + ship_length > 9:
                        print("bot thinking")
                    else:
                        for i in range(ship_length):
                            if self.ship_map[start_x_coord][start_y_coord+i] == 1:
                                place = False
                        if place == True:
                            for i in range(ship_length):
                                self.ships[key][2].append([start_x_coord,start_y_coord+i])
                                self.ship_map[start_x_coord][start_y_coord+i] = 1
                            self.ships[key][0] = True
                            break
                elif choice == "up":
                    #everything above
                    if start_y_coord - ship_length < 10:
                        print("bot thinking")
                    else:
                        for i in range(ship_length):
                            if self.ship_map[start_x_coord][start_y_coord-i] == 1:
                                place = False
                        if place == True:
                            for i in range(ship_length):
                                self.ships[key][2].append([start_x_coord,start_y_coord-i])
                                self.ship_map[start_x_coord][start_y_coord-i] = 1
                            self.ships[key][0] = True
                            break
                else:
                    raise Warning("Choice missed: unknown error occuring, not from this script")
        return self.ships

    def strike(self):
        while True:
            x_coord = np.random.randint(0,10)
            y_coord = np.random.randint(0,10)
            if self.hits_map[x_coord][y_coord] == 0:
                self.hits_map[x_coord][y_coord] = 1
                break
        return [x_coord,y_coord]

class MediumBot(EasyBot):
    def __init__(self):
        super().__init__()
        self.target_stack = []
        self.last_shot = list()
    def strike(self):
        #check if last shot was hit or miss (if == [] counts as miss)
        #if hit add surrounding squares to target stack if not already in shot list
        if self.success_log[-1] == "sunk":
            self.target_stack = []
        if self.success_log[-1] == "hit":

            x = self.last_shot[0]
            y = self.last_shot[1]
            if 0<x:
                if self.hits_map[x-1][y] == 0:
                    self.target_stack.append([x-1,y])
            if 9>x:
                if self.hits_map[x+1][y] == 0:
                    self.target_stack.append([x+1,y])
            if 0<y:
                if self.hits_map[x][y-y] == 0:
                    self.target_stack.append([x,y-1])
            if 9>y:
                if self.hits_map[x][y+1] == 0:
                    self.target_stack.append([x,y+1])
        #check if the target stack is empty if it is: hunt
        if self.target_stack == []:

            targ =  self.hunt()

            self.hits_map[targ[0]][targ[1]] = 1

        #if it is not empty pop off a coord from the target stack
        else:

            targ = self.target_stack.pop()
            self.hits_map[targ[0]][targ[1]] = 1
            print(targ)
        #reset the last shot var to the new coord that is going to be shot at
        self.last_shot = targ
        return targ
        #return the coords [x,y]

    def hunt(self):
        #parity
        #hit even number squares
        hitsequence = list((self.p_ships.keys())) #list(reversed(self.p_ships.keys())) <--- smalles ship first

        for key in hitsequence:
           if self.p_ships[key][0] == True:
                while True:
                    row,column = random.choice(range(10)), random.choice(range(10))
                    if (row+column) % self.p_ships[key][1] != 0:
                        continue
                    if self.hits_map[row][column] == 0:
                        self.hits_map[row][column] = 1
                        self.last_shot = [row,column]
                        return [row,column]

        raise Warning("END OF FUNCTION, CODE FAIL")

class HardBot (MediumBot):
    def __init__(self):
        super().__init__()
        self.PROB_MAP = np.zeros([10,10])
        self.hit_ship_coord = []

    def strike(self):
        #get the result of the last shot
        #update the probability map accordingly
        #get the highest value from the probability map
        #update the last shot and the hits map
        #return the location for hit
        if self.success_log[-1] == "hit":
            self.hit_ship_coord.append(self.last_shot)

        self.gen_prob_map()
        max = np.argmax(self.PROB_MAP)

        max_row = int(max/10)
        max_col = int(max%10)
        target = [max_row,max_col]
        self.last_shot = target
        self.hits_map[target[0]][target[1]] = 1

        return target
        raise Warning("WARNING: Bot unable to predict. Reverting to lower class for target")

        return EasyBot().strike()

    def gen_prob_map(self):

       prob_map = np.zeros([10,10])

       for key in self.ships:
            length = self.ships[key][1]-1

            for col in range(10):
                for row in range(10):
                    if self.hits_map[row][col] != 1:
                        # get potential ship endpoints
                        endpoints = []
                        # add 1 to all endpoints to compensate for python indexing
                        if row - length >= 0:
                            endpoints.append(((col - length, row), (col + 1, row + 1)))
                        if row + length <= 9:
                            endpoints.append(((col, row), (col + length + 1, row + 1)))
                        if col - length >= 0:
                            endpoints.append(((col, row - length), (col + 1, row + 1)))
                        if col + length <= 9:
                            endpoints.append(((col, row), (col + 1, row + length + 1)))

                        for (start_col, start_row), (end_col, end_row) in endpoints:
                            if np.all(self.hits_map[start_col:end_col, start_row:end_row] == 0):
                                prob_map[start_col:end_col, start_row:end_row] += 1

                    if self.hits_map[col][row] == 1 and [col, row] not in self.ships_sunk_coords:

                        #looking to the right of coord that we are at right now
                        if col+1 <10 and self.hits_map[col+1][row] == 0:

                            #if the coord to its left exists and if has already been hit and the ship it's attached to hasn't been sunk,
                            # then the coord to the right of current is likely to have a ship

                            if (col-1 > -1) and ([col-1, row] in self.hit_ship_coord) and ([col-1, row] not in self.ships_sunk_coords):

                                prob_map[col+1][row] += 25
                            #otherwise it is not as likely to contain ship coord
                            else:
                                prob_map[col+1][row] += 10

                        if col-1 > -1 and self.hits_map[col-1][row] == 0:
                            if col + 1 < 10 and [col+1, row] in self.hit_ship_coord and [col+1, row] not in self.ships_sunk_coords:
                                prob_map[col-1][row] += 25
                            else:
                                prob_map[col-1][row] += 10

                        if row+1<10 and self.hits_map[col][row+1] == 0:
                            if row-1 >-1 and [col,row-1] in self.hit_ship_coord and [col,row-1] not in self.ships_sunk_coords:
                                prob_map[col][row+1] += 25
                            else:
                                prob_map[col][row+1] += 10

                        if row-1 >-1 and self.hits_map[col][row-1] == 0:
                            if row+1 < 10 and [col,row+1] in self.hit_ship_coord and [col,row+1] not in self.ships_sunk_coords:
                                prob_map[col][row-1] += 25
                            else:
                                prob_map[col][row-1] += 10

                    elif self.hits_map[col][row] == 1 and [col,row] not in self.hit_ship_coord:

                        prob_map[col][row] = 0

                        if col+1 <10 and self.hits_map[col+1][row] == 0:
                            if not((col-1 > -1) and ([col-1, row] in self.hit_ship_coord) and ([col-1, row] not in self.ships_sunk_coords)):

                                prob_map[col+1][row] -= 25
                            else:
                                prob_map[col+1][row] -= 10

                        if col-1 > -1 and self.hits_map[col-1][row] == 0:
                            if not(col + 1 < 10 and [col+1, row] in self.hit_ship_coord and [col+1, row] not in self.ships_sunk_coords):
                                prob_map[col-1][row] -= 25
                            else:
                                prob_map[col-1][row] -= 10

                        if row+1<10 and self.hits_map[col][row+1] == 0:
                            if not(row-1 >-1 and [col,row-1] in self.hit_ship_coord and [col,row-1] not in self.ships_sunk_coords):
                                prob_map[col][row+1] -= 25
                            else:
                                prob_map[col][row+1] -= 10

                        if row-1 >-1 and self.hits_map[col][row-1] == 0:
                            if not(row+1 < 10 and [col,row+1] in self.hit_ship_coord and [col,row+1] not in self.ships_sunk_coords):
                                prob_map[col][row-1] -= 25
                            else:
                                prob_map[col][row-1] -= 10

       self.PROB_MAP = prob_map


import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()

requires = [
    'pyramid>=1.5a2',
]

setup(name='pyramid_skue',
      version='0.1.0',
      description='pyramid_skue',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
          "Programming Language :: Python",
          "Programming Language :: Python :: 2",
          "Framework :: Pyramid",
          "Topic :: Internet :: WWW/HTTP",
      ],
      author='Cyril Panshine',
      author_email='kipanshi@gmail.com',
      url='https://github.com/kipanshi/pyramid_skue',
      keywords='web pyramid pylons rest api',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=requires,
      tests_require=requires,
      test_suite="pyramid_skue",
      )


import logging
import argparse
import sys
import io

from . import parse, __version__

# try:
#     # python3: sys.stdin.buffer contains the 'bytes'
#     input_file = sys.stdin.buffer
# except AttributeError:
#     # python2: sys.stdin contains bytes (aka 'str)
#     input_file = sys.stdin

parser = argparse.ArgumentParser(description='Coreference resolution using e2e')
parser.add_argument("--verbose", "-v", help="Verbose output", action="store_true")
parser.add_argument('-V', '--version', action='version', version="{} ({})".format(__name__, __version__))
parser.add_argument('--model_name', '-m', type=str, default='best')
parser.add_argument('cfg_file', type=str)
parser.add_argument('input_file', nargs='?', type=argparse.FileType('rb'), default=sys.stdin.buffer)

args = parser.parse_args()

logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
                    format='[%(asctime)s %(name)-12s %(levelname)-5s] %(message)s')

# Mute output
stdout = io.StringIO()
sys.stdout = stdout
in_obj = parse(args.input_file, args.cfg_file, args.model_name)
sys.stdout = sys.__stdout__
logging.info(stdout.getvalue())
in_obj.dump()


import numpy as np
import matplotlib.pyplot as plt
import matplotlib

print('started...')

v = 10 # cm/s
delta_out = 1000

files = ['gouge_shear_2D_hertz_Lx5_50MPa_log.txt',
	'gouge_shear_2D_hooke_Lx5_50MPa_log.txt',
	'gouge_shear_3D_hertz_thinLy_Lx5_50MPa_log.txt']
dts = [8e-09,8e-09,2e-08]
labels = ['2D hertz','2D hooke','3D hertz (thin $\ell_y$)']
derivative_steps = 10

'''
files = ['gouge_shear_2D_hertz_Lx5_50MPa_log.txt',
	'gouge_shear_2D_hooke_Lx5_50MPa_log.txt']
dts = [8e-09,8e-09]
labels = ['2D hertz','2D hooke']
'''

times = []
velocities = []
for file, dt in zip(files,dts):
	sim_data = np.loadtxt(file)
	sim_length = len(sim_data)
	# x position array of the center of mass of the sheared (bottom) block
	sheared_block_x = np.array(sim_data[0:sim_length,8])
	# caluculate the instantaneous derivative as a function of time
	############
	time_window = derivative_steps*dt*delta_out
	velocity = []
	for i, j in zip(range(0, sheared_block_x.size-derivative_steps, derivative_steps),
		range(derivative_steps, sheared_block_x.size, derivative_steps)):
		instantaneous_velocity = (sheared_block_x[j]-sheared_block_x[i])/time_window
		velocity.append(instantaneous_velocity)
	print(min(np.abs(velocity)))
	# time array with centered derivative increments
	time = np.arange(
		0, sheared_block_x.size-derivative_steps, derivative_steps) + derivative_steps/2
	# convert time to mega seconds
	print('max velocity: '+str(np.max(velocity)))
	times.append(time/1e6)
	velocities.append(np.array(velocity)*100)

plt.rc('font', family='serif', serif = "cmr10", size=20)
plt.rcParams['mathtext.fontset']='cm'
plt.figure(figsize=(10,6))
matplotlib.rcParams['axes.unicode_minus'] = False

for x, y, label in zip(times, velocities, labels):
	avg_string = '$<V_{plate}>$='+str(round(np.mean(y),4))+' cm/s'
	std_string = '$\sigma$='+str(round(np.std(y),4))+' cm/s'
	plt.errorbar(x=x, y=y, linewidth=1, fmt='', label=label+': '+avg_string+', '+std_string)
#plt.errorbar(x=(sim_data[lines_until_step-1,0]-sim_data[0,0]
#	)*v*dt, y=0.29, yerr=0.05,linewidth=3)

plt.legend(loc='lower right', fontsize=20)
plt.xlabel('time (s)\n')
plt.ylabel('\nshearing plate velocity (cm/s)')
plt.title('$V_{slide}=10$ cm/s, varying contact law\n')
plt.tight_layout(pad=0)
plt.grid(linestyle='--')
plt.ylim(bottom=0)
#plt.xscale('log')
plt.show()


#Create two lists (1-4 and 3-6) and create a variable called answer that combines the two lists only by storing the values shared between the two lists
#Create a list of names that are capitalized and create a variable called answer2 that stores a new list of these names reversed (mitchell becomes llehctim) and lower-case

list_a = [1,2,3,4]
list_b = [3,4,5,6]

names = ["Elie", "Tim", "Matt"]

answer = [num for num in list_a if num in list_b]

answer2 = [name[::-1].lower() for name in names]

print(answer)
print(answer2)


import time

from .common import OS_STAT_MTIME_RESOLUTION, OneUserTest, TwoUsersTest

class TestVersioning(OneUserTest):
    def test_version_restore(self):
        remote = self.remote_document_client_1
        local = self.local_1

        self.engine_1.start()

        # Create a remote doc
        doc = remote.make_file(
            self.workspace, "Document to restore.txt", content=b"Initial content."
        )
        self.wait_sync(wait_for_async=True)
        assert local.exists("/Document to restore.txt")
        assert local.get_content("/Document to restore.txt") == b"Initial content."

        # Create version 1.0, update content, then restore version 1.0
        remote.create_version(doc, "Major")
        remote.update(doc, properties={"note:note": "Updated content."})
        self.wait_sync(wait_for_async=True)
        assert local.get_content("/Document to restore.txt") == b"Updated content."
        version_uid = remote.get_versions(doc)[0][0]
        remote.restore_version(version_uid)
        self.wait_sync(wait_for_async=True)
        assert local.get_content("/Document to restore.txt") == b"Initial content."

class TestVersioning2(TwoUsersTest):
    def test_versioning(self):
        local = self.local_1
        self.engine_1.start()
        remote = self.remote_document_client_2

        # Create a file as user 2
        remote.make_file_with_blob("/", "Test versioning.txt", b"This is version 0")
        self.wait_sync()
        assert remote.exists("/Test versioning.txt")
        doc = self.root_remote.fetch(f"{self.ws.path}/Test versioning.txt")
        self._assert_version(doc, 0, 0)

        # Synchronize it for user 1
        self.wait_sync(wait_for_async=True)
        assert local.exists("/Test versioning.txt")

        # Update it as user 1 => should be versioned
        time.sleep(OS_STAT_MTIME_RESOLUTION)
        local.update_content("/Test versioning.txt", b"Modified content")
        self.wait_sync()
        doc = self.root_remote.fetch(f"{self.ws.path}/Test versioning.txt")
        self._assert_version(doc, 0, 1)

        # Update it as user 1 => should NOT be versioned
        # since the versioning delay is not passed by
        time.sleep(OS_STAT_MTIME_RESOLUTION)
        local.update_content("/Test versioning.txt", b"Content twice modified")
        self.wait_sync()
        doc = self.root_remote.fetch(f"{self.ws.path}/Test versioning.txt")
        self._assert_version(doc, 0, 1)

    def _assert_version(self, doc, major, minor):
        assert doc["properties"]["uid:major_version"] == major
        assert doc["properties"]["uid:minor_version"] == minor


import matplotlib.pyplot as plt
import numpy as np

from general import n, n_vectorized
from spectral_functions import E

class DataReader:
    def __init__(self, fileName=r"/Users/ianhu/Documents/ARPES/ARPES Shared Data/X20141210_far_off_node/OD50_0333_nL.dat", w_dim=201, k_dim=695, plot=True):
        Eugen_data_file = open(fileName, "r")
        Eugen_data_file.readline()  # skip blank starting line
        temp = Eugen_data_file.readline()  # energy?
        temp_split = temp.split()

        w_dim = w_dim  # 401 for near node # 201 for far off node
        k_dim = k_dim  # 690 for near node # 695 for far off node

        Eugen_data = np.zeros((w_dim, k_dim))
        k = np.zeros(k_dim)
        w = np.zeros(w_dim)
        for i in range(w_dim):
            w[i] = float(temp_split[i]) * 1000
        self.full_w = np.flip(w)

        Eugen_data_file.readline()  # empty 0.0164694505526385 / 0.515261371488587
        Eugen_data_file.readline()  # unfilled 0.513745070571566 (FOR FAR OFF NODE ONLY)
        Eugen_data_file.readline()  # unfilled 0.512228769654545 (FOR FAR OFF NODE ONLY)

        for i in range(k_dim):
            temp = Eugen_data_file.readline()
            temp_split = temp.split()
            k[i] = float(temp_split[0])  # flip to positive --> removed negative
            for j in range(w_dim):
                Eugen_data[w_dim - j - 1][k_dim - i - 1] = temp_split[j + 1]  # fill in opposite
        self.full_k = np.flip(k)
        self.full_Z = Eugen_data
        self.zoomed_w = None
        self.zoomed_k = None
        self.zoomed_Z = None
        if plot:
            plt.title("Raw Eugen data")
            im = plt.imshow(Eugen_data, cmap=plt.cm.RdBu, aspect='auto',
                            extent=[min(k), max(k), min(w), max(w)])  # drawing the function
            plt.colorbar(im)
            plt.show()
        Eugen_data_file.close()

    def getZoomedData(self, width=140, height=70, x_center=360, y_center=75, scaleup=17500, plot=True):
        """
        Zoom in onto a part of the spectrum. Sets zoomed_k, zoomed_w, and zoomed_Z
        :param width:
        :param height:
        :param x_center: measured from top left
        :param y_center: measured from top left
        :param scaleup:
        :param plot:
        :return:
        """
        height_offset = int(y_center - 0.5 * height)
        width_offset = int(x_center - 0.5 * width)

        zoomed_k = np.zeros(width)
        zoomed_w = np.zeros(height)

        zoomed_Z = np.zeros((height, width))

        for i in range(height):
            zoomed_w[i] = self.full_w[i + height_offset]
            for j in range(width):
                zoomed_Z[i][j] = self.full_Z[i + height_offset][j + width_offset]
                zoomed_k[j] = self.full_k[j + width_offset]

        zoomed_Z = np.multiply(zoomed_Z, scaleup)
        zoomed_Z = np.around(zoomed_Z)

        self.zoomed_k = zoomed_k
        self.zoomed_w = zoomed_w
        self.zoomed_Z = zoomed_Z

        if plot:
            plt.title("Raw Eugen data (Reduced Window)")
            # zoomed_Z = zoomed_Z - 700
            # zoomed_Z = np.clip(zoomed_Z, a_min=0, a_max=None)
            # zoomed_Z /= n_vectorized(zoomed_w, 100.86)[:, None]
            im = plt.imshow(zoomed_Z, cmap=plt.cm.RdBu, aspect='auto',
                            extent=[min(zoomed_k), max(zoomed_k), min(zoomed_w), max(zoomed_w)])  # drawing the function
            plt.colorbar(im)
            # plt.plot(zoomed_k, -E((zoomed_k - 0.00608974), 3563.07808, -26.1965687, 7.00118984))  # 0290
            # plt.plot(zoomed_k, 3563.07808 * (zoomed_k - 0.00608974) ** 2 - 26.1965687)
            # plt.plot(zoomed_k, -E((zoomed_k - 0.01248904), 2568.30255, -21.0992210, 13.5027728))  # 0333
            # plt.plot(zoomed_k, 2568.30255 * (zoomed_k - 0.01248904) ** 2 - 21.0992210)
            plt.show()


import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

############################ 2D convolution #########################

# img = cv.imread('OpenCV_Logo.png')
# kernel = np.ones((5,5),np.float32)/25

# dst = cv.filter2D(img, -1, kernel)

# plt.subplot(121),plt.imshow(img),plt.title('Original')
# plt.xticks([]), plt.yticks([])
# plt.subplot(122),plt.imshow(dst),plt.title('Averaging')
# plt.xticks([]), plt.yticks([])
# plt.show()

# cv.waitKey(0)
# cv.destroyAllWindows()

############################### Image Blurring ###############################

########### Averaging ###########

img = cv.imread('OpenCV_Logo.png')

# blur = cv.blur(img,(5,5))
# blur = cv.GaussianBlur(img, (5,5), 0)
# blur = cv.medianBlur(img, 5)

blur = cv.bilateralFilter(img, 9, 75, 75)

plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(blur),plt.title('Blurred')
plt.xticks([]), plt.yticks([])
plt.show()


#!/usr/bin/env python3

def add_item(result,element,counter):
        if counter == 1:
            result.append(element)
        else:
            result.append(2*element + str('-' + counter))

def solve(text):
    '''Thc hin bin đi

      input: [a, abbbccccdddd, xxyyyxyyx]
      output: [a, abb3cc4dd4, xx2yy3xyy2x]

    Gii thích: Nhng ch cái không lp li thì output gi nguyên ch cái đó.
    Nhng ch cái liên tip s in ra 2 ln + s ln lp li liên tip.

    Đây là mt bin th ca mt thut toán nén d liu có tên Run-length
    encoding (RLE).
    NOTE: không dùng itertools.groupby
    '''
    result = []

    # Xoá dòng sau và vit code vào đây set các giá tr phù hp
    # raise NotImplementedError("Hc viên cha làm bài này")

    input_text = list(text)
    count = 1
    first_char = input_text[0]
    if len(input_text) > 1:
            for i in range(1,len(input_text)):
                    cur_char = input_text[i]
                    if cur_char == first_char:
                            count += 1
                    else:
                            add_item(result, first_char, count)
                            count = 1
                            first_char = cur_char
            add_item(result, cur_char, count)
    else:
            add_item(result, cur_char, count)
    result = ' '.join(result)
    return result

def add_item(result_list, char, count):
        if count == 1:
                result_list.append(char)
        else:
                result_list.append(2*char + str(count))

# def solve(text):
#    count=1
#    result=""
#    for i in range(1,len(text)):
#        if text[i-1]==text[i]:
#           count+=1
#        else :
#            result+= printchar(text[i-1],count)
#            count=1
#    result+= printchar(text[i],count)
#    return result

# def printchar(chr, count):
#    if count==1:
#        return chr
#    else:
#        return 2*chr+str(count)

#-- So lan character xuat hien trong word, ko can lien tiep
# def solve(text):
#    solved_char = []
#    result=[]
#    for i in text:
#        if i not in solved_char:
#            if text.count(i) == 1:
#                result.append(i)
#            else:
#                result.append(2*i + str(text.count(i)))
#            solved_char.append(i)
#    return ''.join(result)

def main():
    print(solve('abbbccccddddaaj'))

if __name__ == "__main__":
    main()


import os;

from settings.autostart import initialCmdArr;
from settings.keys import mod, terminal, keys;
from settings.groups import groups;
from settings.screens import screens;

from libqtile import bar, layout, widget
from libqtile.config import Click, Drag, Group, Key, Match, Screen
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal

layouts=[
    layout.Columns(
        margin=10,
        border_focus="a54c3f",
        border_normal="1A1A1A",
        border_width=2
    ),
    layout.Max(
        margin=10,
    ),
];
mouse = [
    Drag([mod], "Button1", lazy.window.set_position_floating(), start=lazy.window.get_position()),
    Drag([mod], "Button3", lazy.window.set_size_floating(), start=lazy.window.get_size()),
    Click([mod], "Button2", lazy.window.bring_to_front()),
]

# ///--- rules
dgroups_key_binder = None
dgroups_app_rules = []  # type: list
follow_mouse_focus = True
bring_front_click = False
cursor_warp = False
floating_layout = layout.Floating(
    float_rules=[
        *layout.Floating.default_float_rules,
        Match(wm_class="confirmreset"),  # gitk
        Match(wm_class="makebranch"),  # gitk
        Match(wm_class="maketag"),  # gitk
        Match(wm_class="ssh-askpass"),  # ssh-askpass
        Match(title="branchdialog"),  # gitk
        Match(title="pinentry"),  # GPG key password entry
    ]
)

# ///--- general conf
auto_fullscreen = True
focus_on_window_activation = "smart"
reconfigure_screens = True
auto_minimize = True
wl_input_rules = None
wmname = "LG3D"

for cmd in initialCmdArr:
    os.system(cmd);


''' BackTracking Recursive Algorithm '''

nsets = 0
def backtrack(total, arr, num):
    i = 0
    global nsets
    l = len(arr)
    if(l == 0): return True
    total = total
    sub_arr = arr[i:l]
    add_sub_arr = sum(sub_arr)

    i += 1
    right_total = total
    right_sub_arr = sub_arr[i:l]
    countr = add_sub_arr - sub_arr[i-1]
    #print("Right = ", right_total, countr)
    if(right_total == num and countr == 0): nsets += 1

    left_total = total + sub_arr[i-1]
    left_sub_arr = sub_arr[i:l]
    countl = add_sub_arr - sub_arr[i-1]
    #print("Left = ", left_total, countl)
    if(left_total == num and countl == 0): nsets += 1

    backtrack(left_total, left_sub_arr, num)
    backtrack(right_total, right_sub_arr, num)

    return nsets

arr = [2, 4, 6, 10, 5, 1, 3]
num = 10
nsets = backtrack(0, arr, num)
print("No of subsets with sum equal to", num, " = ", nsets)


mas = [4, 7, 2, 3, 1, 5, 9, 8]

def find_min(mas):
    min = mas[0]
    for z in mas:
        if z < min:
            min = z
    return min

def arf_min(mas):
    s = 0
    for z in mas:
        s = s + z
    s = s / len(mas)
    return s

print("Mинимума в массиве:", (find_min(mas)))
print("Среднее арифметическое с массиве:", (arf_min(mas)))


from utee import misc, compress
import torch
import torch.backends.cudnn as cudnn
import os
cudnn.benchmark =True
from IPython import embed

params = {
    'dataset': 'mnist',
    'model': 'mnist_cryptonets',
    'batch_size': 100,
    'seed': 117,
    'model_dir': './pretrained_models',
    'data_dir': 'dataset/',
    'n_sample': 20,
    'weight_bits': 6,
    'act_bits': 9,
    'overflow_rate': 0.0
}

misc.ensure_dir(params['model_dir'])
params['model_dir'] = misc.expand_user(params['model_dir'])
params['data_dir'] = misc.expand_user(params['data_dir'])

print("================PARAMS==================")
for k, v in params.items():
    print('{}: {}'.format(k, v))
print("========================================")

assert torch.cuda.is_available(), 'no cuda'
torch.manual_seed(params['seed'])
torch.cuda.manual_seed(params['seed'])

# load model and dataset fetcher
model_raw, ds_fetcher = misc.load_model(params['model'], params['dataset'],
        model_root=params['model_dir'], pretrained=True)
model_raw.cuda()
model_raw.eval()

model_new = compress.CompressedModel(model_raw, input_scale=255,
        act_bits=params['act_bits'], weight_bits=params['weight_bits'])
model_new = model_new.cuda()
print(model_new)

val_ds = ds_fetcher(params['batch_size'], data_root=params['data_dir'], train=False)
acc1, acc5 = misc.eval_model(model_new, val_ds, ngpu=1, n_sample=params['n_sample'], is_imagenet=False)
print("FP accuracy Top1: %g Top5: %g" % (acc1, acc5))

model_new.quantize_params()
acc1, acc5 = misc.eval_model(model_new, val_ds, ngpu=1, n_sample=params['n_sample'], is_imagenet=False)
print("Quant accuracy Top1: %g Top5: %g" % (acc1, acc5))
print(acc1, acc5)

print(model_new)
new_file = os.path.join(params['model_dir'],
        '{}-{}bit.pth'.format(params['model'], params['act_bits']))
misc.model_snapshot(model_new, new_file, old_file=None, verbose=True)

#embed()


from math import sqrt

class Data:
    def __init__(self, user_idx, item_idx, rate):
        self.user_idx = user_idx
        self.item_idx = item_idx
        self.rate = rate

    def __str__(self):
        return 'user={}, item={}, rate={}'.format(self.user_idx, self.item_idx, self.rate)

class ToPredict:
    def __init__(self, test_idx, user_idx, item_idx):
        self.test_idx = test_idx
        self.user_idx = user_idx
        self.item_idx = item_idx
        self.rate = 4

train_data, validation_data, test_data = [], [], []

class Classifier:
    def __init__(self):
        self.mu = float(0)
        self.buser = dict()
        self.bitem = dict()
        self.fuser = dict()
        self.fitem = dict()
        self.count_for_user = dict()
        self.count_for_item = dict()
        self.feature_count = 2

    def insert_if_not_exists(self, test):
        if not test.user_idx in self.buser:
            self.buser[test.user_idx] = 0
            self.fuser[test.user_idx] = [0]*self.feature_count
        if not test.item_idx in self.bitem:
            self.bitem[test.item_idx] = 0
            self.fitem[test.item_idx] = [0]*self.feature_count

    def learn(self, train_data):
        old_rmse, rmse = 0, 25
        term_eps = 1e-5
        small_improve = 1e-2
        down_speed = 1e-1
        lam = 0.1

        iter_num = 0
        total = len(train_data)

        rating = dict()

        for t in train_data:
            if not t.user_idx in rating:
                rating[t.user_idx] = dict()
            rating[t.user_idx][t.item_idx] = float(t.rate)
            self.insert_if_not_exists(t)

        while abs(old_rmse - rmse) > term_eps:
            old_rmse = rmse
            rmse = 0

            for user_idx, rates in rating.items():
                for item_idx, rate in rates.items():
                    bu, bi = self.buser[user_idx], self.bitem[item_idx]
                    fu, fi = self.fuser[user_idx], self.fitem[item_idx]
                    err =  rate - (self.mu + bu + bi + sum(p*q for p,q in zip(fu,fi)))
                    rmse += err**2
                    self.mu += down_speed * err
                    self.buser[user_idx] += down_speed * (err - lam * bu)
                    self.bitem[item_idx] += down_speed * (err - lam * bi)
                    for i in range(self.feature_count):
                        self.fuser[user_idx][i] += down_speed * (err*fi[i] - lam*fu[i])
                        self.fitem[item_idx][i] += down_speed * (err*fu[i] - lam*fi[i])

            rmse = sqrt(rmse / total)
            iter_num += 1
            print('Iteration : {}, RMSE : {}'.format(iter_num, rmse))
            if rmse > old_rmse - small_improve:
                down_speed *= 0.66
                small_improve *= 0.5

    def get_rate(self, test):
        self.insert_if_not_exists(test)
        feat_add = sum(p*q for p,q in zip(self.fuser[test.user_idx], self.fitem[test.item_idx]))
        return self.mu + self.buser[test.user_idx] + self.bitem[test.item_idx] + feat_add

classifer = Classifier()

with open('train.csv', 'r') as f:
    f.readline() #title
    train_data = [Data(*line.strip().split(',')) for line in f.readlines()]
    classifer.learn(train_data)

with open('validation.csv', 'r') as f:
    f.readline() #title
    validation_data = [Data(*line.strip().split(',')) for line in f.readlines()]

with open('test-ids.csv', 'r') as f:
    f.readline() #title
    test_data = [ToPredict(*line.strip().split(',')) for line in f.readlines()]

with open('submission0', 'w') as f:
    f.write('id,rating\n')
    for test in test_data:
        test.rate = classifer.get_rate(test)
        f.write('{},{}\n'.format(test.test_idx, test.rate))


"""
Advent of Code 2020 :: Day 12: Rain Risk
"""
import sys
import math
import pyperclip

def round_nearest(fpn):
    """Round the floating point number to the nearest integer."""
    return int(math.floor(fpn + 0.5))

def turn(curr_dirn, turn_cmd, degrees):
    """Turn from current direction."""
    assert (degrees % 90 == 0)
    right_turns = [(1, 0), (0, -1), (-1, 0), (0, 1)]
    left_turns = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    # Find index of current heading.
    index = left_turns.index(curr_dirn) if turn_cmd == 'L' else right_turns.index(curr_dirn)
    new_index = (index + (degrees // 90)) % len(left_turns)
    new_dirn = left_turns[new_index] if turn_cmd == 'L' else right_turns[new_index]
    return new_dirn

def move(curr_posn, curr_dirn, mv_cmd, magnitude):
    """Return new position, direction will not change."""
    offsets = {'N': (0, 1), 'S': (0, -1), 'E': (1, 0), 'W': (-1, 0), 'F': curr_dirn}
    mv_offset = offsets[mv_cmd]
    new_posn = (curr_posn[0] + (magnitude * mv_offset[0]),
                curr_posn[1] + (magnitude * mv_offset[1]))
    return new_posn

def rotate_waypoint(wp_posn, rotate_cmd, degrees):
    """Rotate current position around the origin (the ship)."""
    if rotate_cmd == 'R':
        degrees *= -1
    rads = math.radians(degrees)
    new_posn = (round_nearest(wp_posn[0] * math.cos(rads) - wp_posn[1] * math.sin(rads)),
                round_nearest(wp_posn[0] * math.sin(rads) + wp_posn[1] * math.cos(rads)))
    return new_posn

def main():
    """Main program."""
    commands = [(line[:1], int(line[1:])) for line in sys.stdin]

    # Part 1
    ship_posn = (0, 0)
    ship_dirn = (1, 0)
    for cmd, magnitude in commands:
        if cmd in ['L', 'R']:
            ship_dirn = turn(ship_dirn, cmd, magnitude)
        elif cmd in ['N', 'S', 'E', 'W', 'F']:
            ship_posn = move(ship_posn, ship_dirn, cmd, magnitude)
    soln1 = abs(ship_posn[0]) + abs(ship_posn[1])
    print(f"The solution to part 1 is {soln1}")
    assert soln1 == 319

    # Part 2
    waypoint_rel_posn = (10, 1)
    ship_posn = (0, 0)
    for cmd, magnitude in commands:
        if cmd in ['L', 'R']:
            waypoint_rel_posn = rotate_waypoint(waypoint_rel_posn, cmd, magnitude)
        elif cmd in ['N', 'E', 'S', 'W']:
            waypoint_rel_posn = move(waypoint_rel_posn, None, cmd, magnitude)
        elif cmd == 'F':
            prev = ship_posn
            ship_posn = (ship_posn[0] + (magnitude * waypoint_rel_posn[0]),
                         ship_posn[1] + (magnitude * waypoint_rel_posn[1]))

    soln2 = abs(ship_posn[0]) + abs(ship_posn[1])
    print(f"The solution to part 2 is {soln2}")
    assert soln2 == 50157
    pyperclip.copy(soln2)

if __name__ == '__main__':
    main()


import re

from PyQt6.QtWidgets import (
    QWidget,
    QHBoxLayout,
    QStackedWidget,
    QFileDialog
)
from PyQt6.QtCore import (
    QFileInfo,
    pyqtSignal,
    QUrl
)
from PyQt6.QtGui import (
    QDragEnterEvent,
    QDragMoveEvent,
    QDropEvent,
    QPixmap
)

from .selected_file_widget_ui import Ui_SelectedFileWidget
from .dragdrop_upload_widget_ui import Ui_DragDropUploadWidget

class DragDropUploadWidget(QWidget):
    dropped = pyqtSignal(QUrl)

    def __init__(self, *args, **kwargs):
        super(DragDropUploadWidget, self).__init__(*args, **kwargs)
        self.ui = Ui_DragDropUploadWidget()
        self.ui.setupUi(self)
        self.setAcceptDrops(True)

        self.filter_extensions = "Text files (*.txt)"
        self.extensions = ("txt",)

        self.ui.button_dragdrop.clicked.connect(self.action_clicked_choose_file)

    def action_clicked_choose_file(self):
        filename, _ = QFileDialog.getOpenFileName(
            parent=self,
            caption="Open a key file",
            directory="",
            filter=self.filter_extensions,
        )

        if not filename:
            return

        self.dropped.emit(QUrl.fromLocalFile(filename))

    def dragEnterEvent(self, event: QDragEnterEvent) -> None:
        if event.mimeData().hasUrls():
            file_path = event.mimeData().urls()[0].toLocalFile()
            file_ext = QFileInfo(file_path).completeSuffix()

            if file_ext in self.extensions or self.extensions == "all":
                event.accept()
        else:
            event.ignore()

    def dragMoveEvent(self, event: QDragMoveEvent) -> None:
        if event.mimeData().hasUrls():
            file_path = event.mimeData().urls()[0].toLocalFile()
            file_ext = QFileInfo(file_path).completeSuffix()

            if file_ext in self.extensions or self.extensions == "all":
                event.accept()
        else:
            event.ignore()

    def dropEvent(self, event: QDropEvent) -> None:
        if event.mimeData().hasUrls():
            file = event.mimeData().urls()[0]
            self.dropped.emit(file)
            event.accept()
        else:
            event.ignore()

class SelectedFileWidget(QWidget):
    canceled = pyqtSignal(QUrl)

    def __init__(self, *args, **kwargs):
        super(SelectedFileWidget, self).__init__(*args, **kwargs)
        self.ui = Ui_SelectedFileWidget()
        self.ui.setupUi(self)
        self.ui.label_icon.setPixmap(QPixmap("icons:file.png").scaled(32, 32))
        self.ui.button_close.clicked.connect(lambda: self.canceled.emit(QUrl()))

class DragDropWidget(QWidget):
    dropped = pyqtSignal(QUrl)
    canceled = pyqtSignal(QUrl)

    def __init__(self, *args, **kwargs):
        super(DragDropWidget, self).__init__(*args, **kwargs)
        self.setAcceptDrops(True)
        self.resize(400, 200)

        self.file_path = ""

        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        self.stacked_widget = QStackedWidget(self)
        layout.addWidget(self.stacked_widget)

        self.widget_dragdrop = DragDropUploadWidget()
        self.widget_loadedfile = SelectedFileWidget()

        self.stacked_widget.addWidget(self.widget_dragdrop)
        self.stacked_widget.addWidget(self.widget_loadedfile)

        self.stacked_widget.setCurrentWidget(self.widget_dragdrop)

        self.widget_loadedfile.canceled.connect(self.canceled_file)
        self.widget_dragdrop.dropped.connect(self.dropped_file)

    def set_filter_extensions(self, extensions: str):
        ext_array = re.findall(r"(\*\.[\da-z]+)+", extensions, re.IGNORECASE)
        ext_array = tuple(map(lambda s: s[2::], ext_array))

        if not ext_array:
            ext_array = "all"

        self.widget_dragdrop.extensions = ext_array
        self.widget_dragdrop.filter_extensions = extensions

    def dropped_file(self, file: QUrl):
        self.widget_loadedfile.ui.label_file.setText(file.fileName())
        self.stacked_widget.setCurrentWidget(self.widget_loadedfile)
        self.dropped.emit(file)

    def canceled_file(self, file: QUrl):
        self.stacked_widget.setCurrentWidget(self.widget_dragdrop)
        self.canceled.emit(file)


import requests, re
from bs4 import BeautifulSoup

USER_AGENT_VALUE = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36"

def extract_job(html):
  if(html.find("span", {"class": "closed"})):
    return
  title = html.find("h2", {"itemprop":"title"}).get_text(strip=True)
  company = html.find("h3", {"itemprop": "name"}).get_text(strip=True)
  locationBox = html.find("div", {"class": "location tooltip"})
  location = locationBox.get_text(strip=True) if locationBox else ""
  linkBox = html.find("td", {"class", "source"})
  linkBox = linkBox.find("a")
  link = linkBox["href"] if linkBox else ""

  return {'title':title, 'company':company, 'location':location, 'link': link if("mailto" in link) else f"https://remoteok.io{link}"}

def extract_jobs(url):
  jobs = []
  headers = {'User-Agent': USER_AGENT_VALUE}
  result = requests.get(url, headers=headers)
  soup = BeautifulSoup(result.text, "html.parser")
  table = soup.find("table", {"id": "jobsboard"})
  results = table.find_all("tr", {"class":"job"})

  for result in results:
    job = extract_job(result)
    if(job):
      jobs.append(job)

  return jobs

def get_remoteok_jobs(word):
  words = re.split('[-()\"#/@;:<>{}`+=~|!?]',word)
  jobs = []
  for w in words:
    print(f"Scraping remoteok page by {w}...")
    URL = f"https://remoteok.io/remote-dev+{w}-jobs"
    jobs += extract_jobs(URL)
  return jobs


"""
220. Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

Constraints:
0 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
0 <= k <= 104
0 <= t <= 231 - 1
"""
# Time complexity: O(N)
# Space complexity: O(N)
class Solution:
    def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
        if t < 0: return False
        buckets = {}
        bucket_size = t+1

        for i in range(len(nums)):
            bucket_num = nums[i]//bucket_size

            if bucket_num in buckets:
                return True

            if bucket_num-1 in buckets and abs(nums[i] - buckets[bucket_num-1]) <= t:
                return True
            if bucket_num+1 in buckets and abs(nums[i] - buckets[bucket_num+1]) <= t:
                return True

            buckets[bucket_num] = nums[i]
            if i >= k:
                del buckets[nums[i-k]//bucket_size]
        return False


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2018/8/14 14:18
# @Author   : Peter
# @Site       : Model基类
# @File        : BaseModel.py
# @Software: PyCharm
from sqlalchemy import func, or_, distinct

class BaseModel:

    # 更新model
    @staticmethod
    def mergeModel(model, session, commit=True):
        session.merge(model)
        if commit:
            session.commit()

    # 添加model
    @staticmethod
    def addModel(model, session, commit=True):
        session.add(model)
        if commit:
            session.commit()

    # insert & update
    @staticmethod
    def saveModel(model, session, commit=True):
        session.save(model)
        if commit:
            session.commit()

    # query
    @staticmethod
    def query(sql, session, *args, **kwargs):
        return session.execute(sql)

    # 通过id查询
    @classmethod
    def get(cls, _id, session):
        return session.query(cls).get(_id)

    # 查询所有
    @classmethod
    def getAll(cls, session):
        return session.query(cls).all()

    @classmethod
    def getDistinctK(cls, k, session, **kw):
        if kw.get("columns"):
            cls_colum = []
            for Colum in kw.get("columns", []):
                cls_colum.append(getattr(cls, Colum))
            return session.query(*cls_colum).distinct(getattr(cls, k)).order_by(kw.get("order", k)).all()
        else:
            return session.query(distinct(getattr(cls, k))).order_by(kw.get("order", k)).all()

    # 查询所有
    @classmethod
    def getAllByCondition(cls, cond, session, relation="and", **kw):
        condition = list()
        for k, v in dict(cond).items():
            condition += [getattr(cls, k) == v]
        if relation == "and":
            return session.query(cls).filter(*condition).order_by("id").all()
        elif relation == "or":
            return session.query(cls).filter(or_(*condition)).order_by("id").all()
        else:
            return session.query(cls).all()

    # 查询所有id
    @classmethod
    def getAllIds(cls, session):
        return session.query(cls.id).all()

    # 根据名字查找
    @classmethod
    def getByName(cls, name, session):
        return cls.getByKV("name", name, session)
        # return session.query(cls).filter(cls.name == name).all()

    # 从偏移量查找
    @classmethod
    def getByFromId(cls, from_id, session, **kw):
        if kw.get("where"):
            condition = list()
            for k, v in dict(kw.get("where")).items():
                condition += [getattr(cls, k) == v]
            if condition:
                return session.query(cls).filter(cls.id > from_id).filter(*condition).limit(kw.get("limit", 10)).all()
        return session.query(cls).filter(cls.id > from_id).limit(kw.get("limit", 10)).all()

    # 从偏移量查找，对ID取模
    @classmethod
    def getByFromIdAndMod(cls, from_id, mod, left, session, **kw):
        if kw.get("where"):
            condition = list()
            for k, v in dict(kw.get("where")).items():
                condition += [getattr(cls, k) == v]
            if condition:
                return session.query(cls).filter(cls.id > from_id, cls.id % mod == left).filter(*condition).limit(kw.get("limit", 10)).all()
        return session.query(cls).filter(cls.id > from_id, cls.id % mod == left).limit(kw.get("limit", 10)).all()

    # 从偏移量查找部分字段，对ID取
    @classmethod
    def getColumsByFromIdAndMod(cls, Colums, from_id, mod, left, session, **kw):
        cls_colum = []
        for Colum in Colums:
            cls_colum.append(getattr(cls, Colum))
        return session.query(tuple(cls_colum)).filter(cls.id > from_id, cls.id % mod == left).limit(kw.get("limit", 10)).all()

    # 更新id
    @classmethod
    def updateId(cls, _id, to_id, session):
        res = session.execute("UPDATE " + str(cls.__tablename__) + " set id = " + str(to_id) + " WHERE id = '" + str(_id) + "' LIMIT 1")
        session.commit()
        return res

    # 更新字段
    @classmethod
    def updateKV(cls, _id, k, v, session):
        res = session.execute("UPDATE " + str(cls.__tablename__) + " set " + str(k) + " = '" + str(v) + "' WHERE id = '" + str(_id) + "' LIMIT 1")
        session.commit()
        return res

    # 更新字段
    @classmethod
    def updateKVByCondition(cls, cond_k, cond_v, value_k, value_v, session, limit=1):
        res = session.execute("UPDATE " + str(cls.__tablename__) + " set " + str(value_k) + " = '" + str(value_v) + "' WHERE " + cond_k + " = '" + str(cond_v) + "' LIMIT " + str(limit))
        session.commit()
        return res

    # 根据字段值获取ID
    @classmethod
    def getIdByKV(cls, k, v, session, **kw):
        return session.query(cls.id).filter(getattr(cls, k) == v).order_by("id").limit(kw.get("limit", 1)).all()

    # 根据多个字段值获取ID
    @classmethod
    def getIdByCondition(cls, d, session, **kw):
        condition = list()
        for k, v in dict(d).items():
            condition += [getattr(cls, k) == v]
        return session.query(cls.id).filter(*condition).order_by("id").limit(kw.get("limit", 1)).all()

    # 根据字段值获取信息
    @classmethod
    def getByKV(cls, k, v, session, **kw):
        return session.query(cls).filter(getattr(cls, k) == v).limit(kw.get("limit", 10)).all()

    # 根据字段值获取信息
    @classmethod
    def getByCondition(cls, d, session, relation="and", **kw):
        condition = list()
        for k, v in dict(d).items():
            condition += [getattr(cls, k) == v]
        if relation == "and":
            return session.query(cls).filter(*condition).order_by("id").limit(kw.get("limit", 10)).all()
        elif relation == "or":
            return session.query(cls).filter(or_(*condition)).order_by("id").limit(kw.get("limit", 10)).all()
        else:
            return None

    # 查询总条数
    @classmethod
    def getCount(cls, session):
        return session.query(func.count(cls.id)).scalar()

    # 获取TopN
    @classmethod
    def getTopN(cls, order, session, **kwargs):
        return session.query(cls).order_by(order).limit(kwargs.get("limit", 10)).all()

    # TODO:Test
    @classmethod
    def getKRegion(cls, k, start_v, end_v, session, **kwargs):
        return session.query(cls).filter(getattr(cls, k) >= start_v, getattr(cls, k) < end_v).order_by(kwargs.get("order", "id")).limit(kwargs.get("limit", 10)).all()

    # ++
    @classmethod
    def increaseKVById(cls, id_, k, session, **kwargs):
        res = session.query(cls).filter(cls.id == id_).update({
            getattr(cls, k): getattr(cls, k) + kwargs.get("incr", 1)
        })
        session.commit()
        return res

    # concat
    @classmethod
    def concatKVById(cls, id_, k, v, session, **kwargs):
        res = session.query(cls).filter(cls.id == id_).update({
            getattr(cls, k): func.concat(getattr(cls, k), v)
        })
        session.commit()
        return res

    # concat
    @classmethod
    def concatKK2KById(cls, id_, k1, k2, k_value, session, **kwargs):
        res = session.query(cls).filter(cls.id == id_).update({
            getattr(cls, k_value): func.concat(getattr(cls, k1), func.concat(getattr(cls, k2)))
        })
        session.commit()
        return res

    # concat
    @classmethod
    def concatKV2KById(cls, id_, k, v, k_value, session, **kwargs):
        res = session.query(cls).filter(cls.id == id_).update({
            getattr(cls, k_value): func.concat(getattr(cls, k), v)
        })
        session.commit()
        return res

def createInitFunction(cls):
    import types

    print("""def __init__(self, *arg, **kw):""")
    for k in dir(cls):
        if not (str(k).startswith("__") or isinstance(getattr(cls, k), types.FunctionType)):
            if str(k) in ["metadata", "_sa_class_manager", "_decl_class_registry"]:
                continue
            print("""    self.{attr} = kw.get("{attr}", None)""".format(attr=k))


from PyQt5.QtWidgets import QWidget,QLabel
from PyQt5.Qt import QSize,QPixmap
from PyQt5.QtCore import Qt,QTimer
from PyQt5.QtGui import *
import cv2
import rospy
import os
class CamWin(QWidget):
    def __init__(self,Parent=None):
        super().__init__(Parent)

        self.__InitData()
        self.__InitView()

    def __InitData(self):

        self.__size = QSize(600,450)
        self.pkg_path = rospy.get_param("/pkg_path/screen")
        self.video_path = os.path.join(self.pkg_path,"video")
        self.video_name = rospy.get_param("/video_name")
        self.video = os.path.join(self.video_path,self.video_name)

        self.cap = cv2.VideoCapture(self.video)

        self.create_frame_list()
        self.frame = None
        self.lock = False

        self.curve_paint_timer = QTimer(self)
        self.curve_paint_timer.timeout.connect(self.update_pic)
        self.curve_paint_timer.start(25)

    def __InitView(self):
        #设置界面的尺寸为__size
        self.setFixedSize(self.__size)
        self.show_label =  QLabel(self)
        self.show_label.setFixedSize(self.__size)

        self.show_label.setAlignment(Qt.AlignCenter)

    def create_frame_list(self):
        self.frame_list = []
        self.frame_index = 0
        while(1):
            try:
                _,frame = self.cap.read()
                if len(frame):
                    cv2.cvtColor(frame,cv2.COLOR_BGR2RGB,frame)
                    self.frame_list.append(frame)
                else:
                    return
            except:
                return

    def update_pic(self):
        if self.lock == False:
            self.lock = True
            self.frame = self.frame_list[self.frame_index]
            self.frame_index += 1
            self.frame_index %= len(self.frame_list)
            img_rows,img_cols,channels = self.frame.shape
            bytesPerLine = channels * img_cols
            QImg = QImage(self.frame.data,img_cols,img_rows,bytesPerLine,QImage.Format_RGB888)
            self.show_label.setStyleSheet('background-color: rgb(0, 0, 0)')
            self.show_label.setPixmap(QPixmap.fromImage(QImg).scaled(
                self.show_label.size(),Qt.KeepAspectRatio,Qt.SmoothTransformation
            ))
            self.lock = False


class Vehiculo:
    FACTOR_EMISION_GASOLINA=2.196
    FACTOR_EMISION_DIESEL=2.471
    def __init__(self,placa,color,marca,modelo,combustible,km,tanque,AC):
        self.placa=placa
        self.color=color
        self.marca=marca
        self.modelo=modelo
        self.combustible=combustible
        self.km=km
        self.tanque=tanque
        self.AC=AC
        self.encendido=False
        self.litros_consumidos=0

    # def encender(self):
    #     self.encendido=True

    # def apagar(self):
    #     self.encendido=False

    def tocar_bocina(self):
        print("piii piii")

    def frenar(self):
        print("frenando")

    def obtener_combustible(self):
        return self.tanque

    def mostrar_vehiculo(self):
        print("la placa del vehiculo es" + self.placa)
        print("el color del vehiculo es" + self.color)
        print("la marca del vehiculo es"+  self.marca)
        print("el modelo del vehiculo es" + str(self.modelo))
        print("el tipo de combustible del vehiculo es" + self.combustible)
        print("el kilometraje del vehiculo es" + str(self.km))
        print("el tanque del vehiculo es" + str(self.tanque))
        print("el aire acondicionado del vehiculo es" + str(self.AC))

    def cargar_combustible(self, litros):
        self.tanque+= litros
        print("cargando combustible")

    def recorrer_distancia(self, distancia):
        if self.motor.esta_encendido():
            variante= self.obtener_variante()
            if distancia<(self.tanque*variante):
                self.km+=distancia
                total_litros=round(self.km/variante)
                self.tanque-=total_litros
                self.litros_consumidos+=total_litros
                print("recorriendo {} kilometros".format(distancia))
            else:
                print("no tienes suficiente combustible")
        else:
            print("el vehiculo esta apagado")

    def calcular_CO2(self):
        if self.combustible =="Gasolina":
            return self.FACTOR_EMISION_GASOLINA * self.litros_consumidos
        else:
            return self.FACTOR_EMISION_DIESEL * self.litros_consumidos

    def poner_motor(self,motor):
        self.motor=motor

    def obtener_variante(self):
        cilindrada=self.motor. obtener_cilindrada()
        if cilindrada==1000:
            return(12)
        elif cilindrada==2000:
            return(10)
        else:
            return(8)

    def hay_combustible(self,distancia):
        variante=self.obtener_variante()
        if not distancia<(variante*self.tanque):
            return False
        return True

    def obtener_informe(self):
        informe="\n-----------"
        informe+="\nINFORME FINAL-EMISION CO2"
        informe+="\n----------"
        informe+="\n Ud esta conduciendo un vehiculo marca {},modelo {},color {}".format(self.marca,self.modelo,self.color)
        informe+="\n Ha recorrido un total de {} KM de distancia".format(self.km)
        informe+="\n Ha consumido un total de {} litros de {}".format(self.litros_consumidos,self.combustible)
        informe+="\n En su tanque tiene {} litros de {} ".format(self.tanque,self.combustible)
        informe+="\n Se emitio a la atmosfera un total de {} kg de CO2".format(round(self.calcular_CO2(),2))
        return informe


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

"""
Author: 80243990
Date: 2020/10/22
File: test_key.py
"""
import allure
import pytest

from wallet.v390.flow.key_flow import KeyFlow

@allure.epic("门禁卡")
class TestKey:

    @allure.feature("添加门禁卡")
    @allure.title("添加实体门禁卡")
    @pytest.mark.release
    @pytest.mark.test
    @pytest.mark.nfc
    @pytest.mark.run(order=20)
    def test_key_0001(self, driver, start_stop_app, data, clear_all_message):
        key_flow = KeyFlow(driver)
        key_flow.goto_add_card_page(scene=1)
        key_flow.open_physical_access_card(**data["common"])

    @allure.feature("添加门禁卡")
    @allure.title("生成空白卡")
    @pytest.mark.release
    @pytest.mark.test
    @pytest.mark.nfc
    @pytest.mark.run(order=21)
    def test_key_0002(self, driver, start_stop_app):
        key_flow = KeyFlow(driver)
        key_flow.goto_add_card_page(scene=2)
        key_flow.open_manual_access_card()

    @allure.feature("编辑门禁卡")
    @allure.title("遍历编辑卡片所有功能")
    @pytest.mark.release
    @pytest.mark.test
    @pytest.mark.nfc
    @pytest.mark.run(order=22)
    def test_key_0003(self, driver, start_stop_app, data):
        key_flow = KeyFlow(driver)
        key_flow.edit_access_card(**data["test_key_0003"])

    @allure.feature("迁移门禁卡")
    @allure.title("迁入门禁卡")
    @pytest.mark.release
    @pytest.mark.test
    @pytest.mark.nfc
    @pytest.mark.run(order=23)
    def test_key_0004(self, driver, start_stop_app):
        key_flow = KeyFlow(driver)
        key_flow.goto_add_card_page(scene=3)
        key_flow.access_card_transfer_operation()

    @allure.feature("删除门禁卡")
    @allure.title("删除空白卡")
    @pytest.mark.release
    @pytest.mark.test
    @pytest.mark.nfc
    @pytest.mark.run(order=24)
    def test_key_0005(self, driver, start_stop_app):
        key_flow = KeyFlow(driver)
        key_flow.delete_blank_card()

    @allure.feature("删除门禁卡")
    @allure.title("删除实体门禁卡,并注销钱包账户")
    @pytest.mark.release
    @pytest.mark.test
    @pytest.mark.nfc
    @pytest.mark.run(order=26)
    def test_key_0006(self, driver, start_stop_app,):
        key_flow = KeyFlow(driver)
        key_flow.delete_access_card()


import pygame
from pygame.surface import Surface, SurfaceType
from typing import Union

class Border:
    """
    This class represents the border which appears during the game.
    """
    def __init__(self, position, border_config, orientation, color):
        self.rect_obj = pygame.Rect(position[0], position[1],
                                    border_config['width'],
                                    border_config['height'])
        self.orientation = orientation
        self.color = color

    def draw(self, window: Union[Surface, SurfaceType]):
        """
        The border will be drawn into the window.

        :param window: The main window of the game.
        :return:
        """
        pygame.draw.rect(window, self.color, self.rect_obj)


"""마인크래프트 월드에서 사용자의 위치를 이동하기_함수"""

"""현재 위치를 파악한 뒤에 내 위치에서 입력한 값만큼 움직이는 함수 만들기"""
from mcpi.minecraft import Minecraft

minecraftPy = Minecraft.create() # 파이썬과 마인크래프트 연동
minecraftPy.postToChat("hello, Minecraft!!") # 연동이 잘 되었는지 확인

"""1. 이동시키고 싶은 값을 입력받기"""
moveX = int(input("x 좌표의 값: "))
moveY = int(input("y 좌표의 값: "))
moveZ = int(input("z 좌표의 값: "))

def moveTo(x, y, z):
    """플레이어의 위치를 이동시키는 함수"""
    """2. 현재 위치를 파악하기"""
    beforePlayerPos = minecraftPy.player.getTilePos() # 현재 위치
    print("이동하기 전의 위치: " + str(beforePlayerPos))

    """3. 플레이어의 좌표에 해당 값을 대입"""
    beforePlayerPos.x = beforePlayerPos.x + x
    beforePlayerPos.y = beforePlayerPos.y + y
    beforePlayerPos.z = beforePlayerPos.z + z

    afterPlayerPos = beforePlayerPos # 이후에 이동하고자 하는 좌표를 표시
    print(afterPlayerPos) # 잘 더해졌는지 확인

    """4. 플레이어의 좌표에 대입하기"""
    minecraftPy.player.setTilePos(afterPlayerPos)

moveTo(moveX, moveY, moveZ)


import numpy as np
import matplotlib.pyplot as plt

def get_index(arr, x):
    for i in range(len(arr)):
        if arr[i] == x:
            return i
    return -1

num_points = 4

differences = []
masses = []

lowest_mass = 0.8
highest_mass = 2.2
step = 0.1

for i in np.arange(lowest_mass, highest_mass + step/2, step):
    # May need to change {:0X.Xf} to account for directory names
    s,e = np.loadtxt(
        fname="mass/{:03.1f}/bumpTrack/LOGS/Analysis/Data/critPoints.dat".format(i),
        unpack=True, skiprows=1)
    start = int(s)
    end = int(e)
    profiles, sfs01 = np.loadtxt(
        fname="mass/{:03.1f}/bumpTrack/LOGS/Analysis/Data/SFS01.dat".format(i),
        unpack=True, skiprows=1)

    sum = sfs01[get_index(profiles,start)]
    count = 1
    for j in range(1,num_points+1):
        sum += sfs01[get_index(profiles,start) + i]
        sum += sfs01[get_index(profiles,start) - i]
        count += 2
    sdnu  = sum / count

    sum = sfs01[get_index(profiles,end)]
    count = 0
    for j in range(1,num_points+1):
        sum += sfs01[get_index(profiles,end) + i]
        sum += sfs01[get_index(profiles,end) - i]
        count += 2
    ednu = sum / count

    differences.append(ednu - sdnu)
    masses.append(i)

plt.plot(masses,differences)
plt.xlabel("Mass M/M$_☉$")
plt.ylabel(r"Difference In $\delta\nu_{01}$ Across The Bump")
plt.savefig("dnu01Difference")


import sys
from collections import deque

input = sys.stdin.readline

graph = []
n,m = map(int,input().split())

for i in range(n):
    graph.append(list(map(int,input().split())))

shark = []
inf = int(1e9)
for i in range(n):
    for j in range(m):
        if graph[i][j] == 1:
            shark.append([i,j])

dist = [[inf] * m for _ in range(n)]

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

for s in shark:
    q = deque([[s[0],s[1]]])
    visited = [[0] * m for _ in range(n)]
    visited[s[0]][s[1]] = 1
    dist[s[0]][s[1]] = 0
    while(q):
        x,y = q.popleft()

        for l in range(8):
            nx = x + dx[l]
            ny = y + dy[l]
            if 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 0 and visited[nx][ny] == 0:
                visited[nx][ny] = 1
                q.append([nx,ny])
                dist[nx][ny] = min(dist[x][y] + 1,dist[nx][ny])

answer = max(sum(dist,[]))

print(answer)


from __future__ import annotations

from typing import Dict, List, Iterable, Tuple, Optional, Any, Set

DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]

class Cave:

    def __init__(self, rows: Iterable[Iterable[int]]):
        self.rows = [list(r) for r in rows]

    @property
    def size(self) -> Tuple[int, int]:
        return len(self.rows), len(self.rows[0])

    def get_adjacent_positions(self, pos: Tuple[int, int]) -> Iterable[Tuple[Tuple[int, int], int]]:
        yield from (((r, c), self.rows[r][c]) for r, c in ((pos[0] + dy, pos[1] + dx) for dy, dx in DIRECTIONS)
                    if 0 <= r < self.size[0]
                    and 0 <= c < self.size[1])

    @staticmethod
    def parse(data: Iterable[str]) -> Cave:
        return Cave(([int(char) for char in line] for line in data))

#

def binary_insertion(val: Any, items: List[Any]) -> None:
    left = 0
    right = len(items)
    while left < right:
        m = int((left + right) / 2)
        if items[m] > val:
            right = m
        elif items[m] < val:
            left = m + 1
        else:
            items.insert(m, val)
            return
    items.insert(left, val)

def get_goal_distance(cave: Cave, pos: Tuple[int, int]) -> int:
    return sum(cave.size[i] - pos[i] for i in range(2))

def get_path(cave: Cave) -> List[Tuple[int, int]]:
    back_mapping: Dict[Tuple[int, int], Tuple[int, Optional[Tuple[int, int]]]] = {(0, 0): (0, None)}
    # Not going to bother implementing this as a true heap
    heap: List[Tuple[int, Tuple[int, int]]] = [(get_goal_distance(cave, (0, 0)), (0, 0))]
    visited: Set[Tuple[int, int]] = set()
    goal = tuple(x - 1 for x in cave.size)

    while len(heap) > 0:
        value, pos = heap.pop(0)
        if pos in visited:
            continue

        visited.add(pos)
        if pos == goal:
            break

        path_cost, back = back_mapping[pos]

        for adj, adj_cost in cave.get_adjacent_positions(pos):

            # Check if the path leading up to the current position and then to this adjacent one is shorter
            # than the adjacent position's previous best known route
            if adj in back_mapping:
                adj_back_g, adj_back = back_mapping[adj]
                if adj_back_g > path_cost + adj_cost:
                    back_mapping[adj] = (path_cost + adj_cost, pos)
            else:
                back_mapping[adj] = (path_cost + adj_cost, pos)

            if adj not in visited:
                binary_insertion((back_mapping[adj][0] + get_goal_distance(cave, adj), adj), heap)

    if goal not in back_mapping:
        raise Exception("PATH NOT FOUND.")

    path = []
    pos = goal
    while (0, 0) not in path:
        path.append(pos)
        path_cost, pos = back_mapping[pos]

    return list(reversed(path))


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

import cgi
import cgitb
import os
import sys

root = os.path.dirname(os.path.dirname(__file__))
sys.path.append(root)
from tools import utils

form   = cgi.FieldStorage()
rel_id = int(form.getvalue("id", -1))
name   = str(form.getvalue("name", ""))

show = utils.show
cgitb.enable()

PgConn    = utils.get_dbconn()
PgCursor  = PgConn.cursor()

if rel_id == -1 and name == "":
    utils.print_header("Show polygon")
    show("
%s
" % ("Show polygon"))
    show("<form method='GET' action=''>")
    show("%s" % "Id of relation")
    show("<input type='text' name='id' id='id'>")
    show("
")
    show("%s" % "Name of user polygon")
    show("<input type='text' name='name' id='name'>")
    show("<input type='submit'>")
    show("</form>")
    sys.exit(0)

utils.print_header("Show polygon")

if rel_id != -1:

    sql_list = """SELECT id, params, timestamp, ST_NPoints(geom) AS npoints,
                         ST_MaxDistance(geom, geom) AS length
                  FROM polygons WHERE id = %s
                  ORDER BY params"""
    PgCursor.execute(sql_list, (rel_id, ))

    osm_results = PgCursor.fetchall()

    if osm_results:
        show("
%s
" % ("List of available polygons for id = %d" % rel_id))

        show("
\n")
        show("
\n")
        show("    %s ▾	\n" % ("params"))
        show("    %s	\n" % ("timestamp"))
        show("    %s	\n" % ("NPoints"))
        show("    %s	\n" % ("Length"))
        show("    %s	\n" % ("WKT"))
        show("    %s	\n" % ("GeoJSON"))
        show("    %s	\n" % ("poly"))
        show("    %s	\n" % ("Image"))
        show("
\n")

        for res in osm_results:
            show("
\n")
            show("    " + str(res["params"]) + "	\n")
            show("    " + str(res["timestamp"]) + "	\n")
            show("    " + str(res["npoints"]) + "	\n")
            show("    " + str(res["length"]) + "	\n")
            show("    WKT	\n" % (rel_id, str(res["params"])))
            show("    GeoJSON	\n" % (rel_id, str(res["params"])))
            show("    poly	\n" % (rel_id, str(res["params"])))
            show("    image	\n" % (rel_id, str(res["params"])))
            show("
\n")

        show("
\n")

if name != "":

    sql_list = """SELECT name, timestamp, ST_NPoints(geom) AS npoints,
                         ST_MaxDistance(geom, geom) AS length
                  FROM polygons_user WHERE name LIKE %s
                  ORDER BY name"""
    PgCursor.execute(sql_list, (name, ))

    user_results = PgCursor.fetchall()

    if user_results:
        show("
%s
" % ("List of available user polygons for name = %s" % name))

        show("
\n")
        show("
\n")
        show("    %s	\n" % ("name"))
        show("    %s	\n" % ("timestamp"))
        show("    %s	\n" % ("NPoints"))
        show("    %s	\n" % ("Length"))
        show("    %s	\n" % ("WKT"))
        show("    %s	\n" % ("GeoJSON"))
        show("    %s	\n" % ("poly"))
        show("    %s	\n" % ("Image"))
        show("
\n")

        for res in user_results:
            n = str(res["name"])
            show("
\n")
            show("    " + n + "	\n")
            show("    " + str(res["timestamp"]) + "	\n")
            show("    " + str(res["npoints"]) + "	\n")
            show("    " + str(res["length"]) + "	\n")
            show("    WKT	\n" % (n))
            show("    GeoJSON	\n" % (n))
            show("    poly	\n" % (n))
            show("    image	\n" % (n))
            show("
\n")

        show("
\n")

if rel_id != -1 and name != "" and osm_results and user_results:

    show("
%s
" % ("Union of all osm/user polygons"))

    show("
\n")
    show("
\n")
    show("    params	\n")
    for u_res in user_results:
        show("    %s	\n" % (u_res["name"]))
    show("
\n")
    for o_res in osm_results:
        show("
\n")
        show("    " + str(o_res["params"]) + "	\n")
        for u_res in user_results:
            show("    ")
            show("WKT\n" % (rel_id, o_res["params"], u_res["name"]))
            show("GeoJSON\n" % (rel_id, o_res["params"], u_res["name"]))
            show("poly\n" % (rel_id, o_res["params"], u_res["name"]))
            show("image\n" % (rel_id, o_res["params"], u_res["name"]))
            show("    	")
        show("
\n")
    show("
\n")

if rel_id == -1 or name == "":
    show("

\n")
    show("
%s
" % ("Show polygon"))
    show("<form method='GET' action=''>")
    show("%s" % "Id of relation")
    if rel_id == -1:
        show("<input type='text' name='id' id='id'>")
    else:
        show("<input type='text' name='id' id='id' value='%d'>", rel_id)
    show("
")
    show("%s" % "Name of user polygon")
    show("<input type='text' name='name' id='name' value='%s'>" % name)
    show("<input type='submit'>")
    show("</form>")

###########################################################################
utils.print_tail()

PgConn.commit()
PgConn.close()


from tools.qt import QtCore, QtWidgets, tr

from equipment.liquid_solid import Centrifuge
from UI import UI_corriente
from equipment import parents
from lib.corriente import Corriente, Solid
from lib import unidades
from tools import costIndex
from UI.widgets import Entrada_con_unidades

class UI_equipment(parents.UI_equip):
    """Diálogo de definición de tamices de sólidos"""
    def __init__(self, entrada=None, parent=None):
        """entrada: Parametro opcional de clase corriente que indica la corriente de entrada en kla tubería"""
        super(UI_equipment, self).__init__(Centrifuge, entrada=False, parent=parent)
        self.entrada=entrada

        #Pestaña entrada
        self.Entrada= UI_corriente.Ui_corriente(entrada)
        self.Entrada.Changed.connect(self.cambiar_entrada)
        self.tabWidget.insertTab(0, self.Entrada,tr("equipment", "Entrada", None))

        #Pestaña calculo
        gridLayout_Calculo = QtWidgets.QGridLayout(self.tabCalculo)

        #Pestaña costos
        gridLayout_Costos = QtWidgets.QGridLayout(self.tabCostos)
        gridLayout_Costos.addWidget(QtWidgets.QLabel(tr("equipment", "Tipo:", None)), 1, 1, 1, 1)
        self.tipo=QtWidgets.QComboBox()
        self.tipo.addItem(tr("equipment", "Proceso inorgánico", None))
        self.tipo.addItem(tr("equipment", "Proceso orgánico", None))
        self.tipo.currentIndexChanged.connect(self.mostrarSubclasificacion)
        self.tipo.currentIndexChanged.connect(self.calcularCostos)
        gridLayout_Costos.addWidget(self.tipo, 1, 2, 1, 1)
        gridLayout_Costos.addWidget(QtWidgets.QLabel(tr("equipment", "Material:", None)), 2, 1, 1, 1)
        self.materialInorganico=QtWidgets.QComboBox()
        self.materialInorganico.addItem(tr("equipment", "Acero al carbón", None))
        self.materialInorganico.addItem(tr("equipment", "Acero inoxidable 316", None))
        self.materialInorganico.addItem(tr("equipment", "Monel", None))
        self.materialInorganico.addItem(tr("equipment", "Níquel", None))
        self.materialInorganico.currentIndexChanged.connect(self.calcularCostos)
        gridLayout_Costos.addWidget(self.materialInorganico, 2, 2, 1, 1)
        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(20,20,QtWidgets.QSizePolicy.Policy.Fixed,QtWidgets.QSizePolicy.Policy.Fixed),3,0,1,2)
        self.materialOrganico=QtWidgets.QComboBox()
        self.materialOrganico.addItem(tr("equipment", "Acero al carbón", None))
        self.materialOrganico.addItem(tr("equipment", "Acero inoxidable 316", None))
        self.materialOrganico.addItem(tr("equipment", "Monel", None))
        self.materialOrganico.addItem(tr("equipment", "Níquel", None))
        self.materialOrganico.addItem(tr("equipment", "Hastelloy", None))
        self.materialOrganico.currentIndexChanged.connect(self.calcularCostos)
        gridLayout_Costos.addWidget(self.materialOrganico, 2, 2, 1, 1)
        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(10,10,QtWidgets.QSizePolicy.Policy.Fixed,QtWidgets.QSizePolicy.Policy.Fixed),3,0,1,6)
        gridLayout_Costos.addWidget(QtWidgets.QLabel(tr("equipment", "Caudal calculado:", None)), 4, 1, 1, 1)
        self.caudalcalculado=Entrada_con_unidades(unidades.MassFlow, readOnly=True, retornar=False)
        gridLayout_Costos.addWidget(self.caudalcalculado,4,2,1,1)
        gridLayout_Costos.addWidget(QtWidgets.QLabel(tr("equipment", "Caudal de diseño:", None)), 5, 1, 1, 1)
        self.caudaldiseno=Entrada_con_unidades(unidades.MassFlow)
        gridLayout_Costos.addWidget(self.caudaldiseno,5,2,1,1)
        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(10,10,QtWidgets.QSizePolicy.Policy.Fixed,QtWidgets.QSizePolicy.Policy.Fixed),6,0,1,6)

        self.Costos=costIndex.CostData(1.3, 2)
        self.Costos.valueChanged.connect(self.calcularCostos)
        gridLayout_Costos.addWidget(self.Costos,7,1,2,2)

        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(20,20,QtWidgets.QSizePolicy.Policy.Expanding,QtWidgets.QSizePolicy.Policy.Expanding),9,0,1,6)
        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(20,20,QtWidgets.QSizePolicy.Policy.Expanding,QtWidgets.QSizePolicy.Policy.Expanding),11,0,1,6)
        self.groupBox_Costos = QtWidgets.QGroupBox(tr("equipment", "Costos calculados", None))
        gridLayout_Costos.addWidget(self.groupBox_Costos,10,0,1,6)
        gridLayout_5 = QtWidgets.QGridLayout(self.groupBox_Costos)
        gridLayout_5.addWidget(QtWidgets.QLabel(tr("equipment", "Coste Adquisición:", None)),0,1,1,1)
        self.C_adq=Entrada_con_unidades(unidades.Currency, retornar=False, readOnly=True)
        gridLayout_5.addWidget(self.C_adq,0,2,1,1)
        gridLayout_5.addWidget(QtWidgets.QLabel(tr("equipment", "Coste Instalación:", None)),1,1,1,1)
        self.C_inst=Entrada_con_unidades(unidades.Currency, retornar=False, readOnly=True)
        gridLayout_5.addWidget(self.C_inst,1,2,1,1)

        self.tabWidget.setCurrentIndex(0)
        self.mostrarSubclasificacion(0)

    def mostrarSubclasificacion(self, ind):
        self.materialInorganico.setVisible(not ind)
        self.materialOrganico.setVisible(ind)

    def cambiar_entrada(self, corriente):
        selfentrada=corriente
        self.calculo()

    def calculo(self):
        if self.todos_datos():

            self.rellenoSalida()

    def rellenoSalida(self):
        pass

    def todos_datos(self):
        pass

    def calcularCostos(self):
        if self.todos_datos():
            if self.tipo.currentIndex()==0:
                self.FireHeater.Coste(self.factorInstalacion.value(), 0, self.tipobox.currentIndex(), self.material.currentIndex())
            else:
                self.FireHeater.Coste(self.factorInstalacion.value(), 1, self.tipocilindrico.currentIndex(), self.material.currentIndex())
            self.C_adq.setValue(self.FireHeater.C_adq.config())
            self.C_inst.setValue(self.FireHeater.C_inst.config())

if __name__ == "__main__":
    import sys
    from lib.corriente import Corriente, Mezcla
    app = QtWidgets.QApplication(sys.argv)
    agua=Corriente(300, 1, 3600, Mezcla([62], [1]))
    dialogo = UI_equipment(agua)
    dialogo.show()
    sys.exit(app.exec())


import random
from Group import Group

class Randomizer:
    groups = []
    members = []
    fixed_groups =[]

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

    def handleFixedGroups(self):
        for fixed_group in self.fixed_groups:
            if fixed_group not in self.groups:
                self.groups.append(fixed_group)
                for member in fixed_group:
                    self.members.remove(member)

    def randomize(self):
        if len(self.fixed_groups) > 0:
            self.handleFixedGroups()

        group = Group()

        original_length = len(self.members)

        for member in range(0, original_length):

            length= len(self.members) # leiame sisendi listi pikkuse

            # listi indekid algava 0st, aga listi pikkus algab 1st, kui on 5-elemendiline list, len()=5, indeksid on: 0,1,2,3,4
            random_index = random.randint(0, length - 1) # leiame random indeksi meie sisendist

            random_member = self.members[random_index] # same uue liikme nime kätte
            group.addMember(random_member) # lisame uue liikme gruppi

            # Eemaldame entity listist
            self.members.remove(random_member)

            if group.getGroupSize() >= group.length: # length = 1 -> 1 >= 2; length = 2 -> 2 >= 2
                self.groups.append(str(group))
                group = Group() # teeme ajutise grupi tühjas ning taaskasutame seda
                group.names = []

    def run(self):
        self.randomize()

    def getGroups(self):
        print(self.groups)

    def setFixedGroups(self, fixed_group):
        self.fixed_groups.append(fixed_group)