import torch

import settingsModule
from settingsModule import Settings, np, random
from population import Population

# Parent of all algorithms
class Algorithm:
	iteration_num: int
	settings: Settings

	def __init__(self, settings: Settings):
		self.settings = settings
		self.iteration_num = 0

	def iterate(self) -> None:
		pass

	def get_algorithm_name(self) -> str:
		pass

	def get_picture_title(self) -> str:
		pass

	def get_progress_status(self) -> str:
		pass

	def get_file_progress(self) -> str:
		pass

	def get_best_picture(self) -> np.array:
		pass

	def get_best_fitness(self) -> float:
		pass

	def termination_condition(self) -> bool:
		pass

# Genetic Algorithm
class GeneticAlgorithm(Algorithm):
	population: Population
	mutation_probability: float

	def __init__(self, settings: Settings):
		super().__init__(settings)
		self.mutation_probability = self.settings.mutation_probability
		self.population = Population(settings)

	def iterate(self):
		if self.settings.cross_over == settingsModule.CROSS_OVERS.ONE_POINT:
			offsprings = self.one_point_crossover()
		elif self.settings.cross_over == settingsModule.CROSS_OVERS.TWO_POINT:
			offsprings = self.two_points_crossover()
		elif self.settings.cross_over == settingsModule.CROSS_OVERS.UNIFORM:
			offsprings = self.uniform_crossover()
		else:
			print("Illegal Cross Over!")
			exit()

		self.population.steady_state_replace(self.random_mutations(offsprings))

	def one_point_crossover(self):
		parent1, parent2 = self.population.roulette_wheel_select_2_parents()

		rand_col = random.randint(0, parent1.shape[1] - 1)

		offspring1 = np.copy(parent1)
		offspring1[:, :, :rand_col] = parent2[:, :, :rand_col]

		offspring2 = np.copy(parent2)
		offspring2[:, :, rand_col:] = parent1[:, :, rand_col:]

		return np.array([offspring1, offspring2])

	def two_points_crossover(self):
		parent1, parent2 = self.population.roulette_wheel_select_2_parents()

		rand_row1 = random.randint(0, parent1.shape[0] - 1)
		rand_col1 = random.randint(0, parent1.shape[1] - 1)

		rand_row2 = random.randint(0, parent1.shape[0] - 1)
		rand_col2 = random.randint(0, parent1.shape[1] - 1)

		offspring1 = np.copy(parent1)
		offspring1[:, rand_row1:rand_row2, rand_col1:rand_col2] = parent2[:, rand_row1:rand_row2, rand_col1:rand_col2]

		offspring2 = np.copy(parent2)
		offspring2[:, rand_row1:rand_row2, rand_col1:rand_col2] = parent1[:, rand_row1:rand_row2, rand_col1:rand_col2]

		return np.array([offspring1, offspring2])

	def uniform_crossover(self):
		parent1, parent2 = self.population.roulette_wheel_select_2_parents()

		random_matching = np.random.random_integers(0, 1, (parent1.shape[1], parent1.shape[2]))

		offspring1 = random_matching * parent1[:] + (1-random_matching) * parent2[:]
		offspring2 = (1-random_matching) * parent1[:] + random_matching * parent2[:]

		return np.array([offspring1, offspring2])

	def random_mutations(self, offsprings: np.array):
		for offspring_idx in range(len(offsprings)):
			if self.settings.mutation == settingsModule.MUTATIONS.UNIFORMAL:
				offsprings[offspring_idx] = self.uniformal_mutation(offsprings[offspring_idx])
			elif self.settings.mutation == settingsModule.MUTATIONS.INDIVIDUAL:
				offsprings[offspring_idx] = self.individual_mutation(offsprings[offspring_idx])
			else:
				print("Illegal Mutation!")
				exit()

		return offsprings

	def uniformal_mutation(self, offspring: np.array):
		# Make a mutation for each gene in a specific probability
		mutations_activations = np.random.rand(offspring.shape[0], offspring.shape[1], offspring.shape[2]) < self.mutation_probability
		return mutations_activations * np.random.rand(offspring.shape[0], offspring.shape[1], offspring.shape[2]) \
			   + (1 - mutations_activations) * offspring

	def individual_mutation(self, offspring: np.array):
		# Make a mutation in a specific probability
		if random.random() < self.mutation_probability:
			# Change the value in all the layers of the picture
			for i in range(self.settings.num_of_layers):
				gen_index = np.random.random_integers(0, offspring.shape[1] - 1, 2)
				mutation = random.randint(0, self.settings.num_of_shades-1) / (self.settings.num_of_shades-1)
				offspring[:, gen_index[0], gen_index[1]] = mutation

		return offspring

	def get_population_best(self):
		return self.population.get_population_best()

	def get_population_wrost(self):
		return self.population.get_population_wrost()

	def get_algorithm_name(self):
		return "Genetic Algorithm"

	def get_picture_title(self):
		title = f"Generation:{self.iteration_num}, Label:{self.settings.label}\n"

		if self.settings.penalty_factor != 0:
			return title + "Certainty:{0:.2f}%".format(round(self.get_population_best()['certainty']*100, 2)) +\
				   ", Penalty:{0:.4f}".format(round(self.get_population_best()['penalty'], 4)) + \
				   ", Fitness:{0:.4f}".format(round(self.get_population_best()['fitness'], 4))
		else:
			return title + "Fitness:{0:.2f}%".format(round(self.get_population_best()['fitness']*100, 2))

	def get_progress_status(self):
		status = f"Algorithm:GA, Model:{self.settings.model.name}, Generation:{self.iteration_num}, Label:{self.settings.label} | BEST("

		if self.settings.penalty_factor != 0:
			status += "Certainty:{0:.4f}".format(round(self.get_population_best()['certainty'], 4)) + \
				   ", Penalty:{0:.4f}".format(round(self.get_population_best()['penalty'], 4)) + \
				   ", Fitness:{0:.4f}".format(round(self.get_population_best()['fitness'], 4))
		else:
			status += "Fitness:{0:.4f}".format(round(self.get_population_best()['fitness'], 4))

		status += ") | Worst(Fitness:{0:.4f})".format(round(self.get_population_wrost()['fitness'], 4))
		return status

	def get_file_progress(self):
		return f"Iteration:{self.iteration_num}" + \
			   ", Certainty:{0:.4f}".format(round(self.get_population_best()['certainty'], 4)) + \
			   ", Penalty:{0:.4f}".format(round(self.get_population_best()['penalty'], 4)) + \
			   ", Fitness:{0:.4f}".format(round(self.get_population_best()['fitness'], 4))

	def get_best_picture(self):
		return self.get_population_best()['pic']

	def get_best_fitness(self):
		return self.get_population_best()['fitness']

	def termination_condition(self):
		return self.population.get_stuck_evolution_counter() >= 10 * self.settings.status_period or self.get_population_best()['fitness'] >= 0.99

# Greedy Algorithm
class GreedyAlgorithm(Algorithm):
	pic: np.array
	max_fitness: float
	last_max_fitness: float
	curr_i = 0
	curr_j = 0

	def __init__(self, settings: Settings):
		super().__init__(settings)
		self.pic = np.random.random_integers(0, self.settings.num_of_shades - 1,
										(self.settings.num_of_layers, self.settings.picture_size, self.settings.picture_size)) \
				   / (self.settings.num_of_shades - 1)
		self.max_fitness = self.certainty(self.pic)
		self.last_max_fitness = 0.0
		self.penalty_factor = settings.penalty_factor

	def iterate(self):
		if self.curr_i >= self.pic.shape[1]:
			self.curr_i = 0

		if self.curr_j >= self.pic.shape[2]:
			self.curr_j = 0

		max_fitness_shade = self.pic[0][self.curr_i][self.curr_j]

		for shade in range(self.settings.num_of_shades):
			#print(shade)
			self.pic[0][self.curr_i][self.curr_j] = shade / (self.settings.num_of_shades - 1)
			fitness = self.fitness(self.pic)
			if fitness > self.max_fitness:
				self.max_fitness = fitness
				max_fitness_shade = shade / (self.settings.num_of_shades - 1)

		self.pic[0][self.curr_i][self.curr_j] = max_fitness_shade

		self.curr_i += 1
		self.curr_j += 1

	def certainty(self, pic: np.array):
		with torch.no_grad():
			network_input = torch.Tensor(pic).unsqueeze(dim=0)  # Expending the array (one example)
			network_output = self.settings.network(network_input)
			certainty = torch.nn.functional.softmax(network_output, dim=1)

			return float(certainty[0][self.settings.label_num])

	def penalty(self, pic: np.array):
		# The penalty is defined by the distances between every two adjacent pixels in the picture
		penalty = 0

		# Avoiding penalty computation when possible
		if self.penalty_factor != 0:
			row_neighbors = np.copy(pic)
			row_neighbors[:, 1:, :] = pic[:, :-1, :]

			col_neighbors = np.copy(pic)
			col_neighbors[:, :, 1:] = pic[:, :, :-1]

			# penalty = np.sum(np.sqrt(np.abs(offspring - row_neighbors)) + np.sqrt(np.abs(offspring - col_neighbors)))
			penalty = np.sum(np.abs(pic - row_neighbors) + np.abs(pic - col_neighbors))
			penalty /= pow(self.settings.picture_size, 2)

		return penalty

	def fitness(self, pic):
		if self.penalty_factor != 0:
			certainty = self.certainty(pic)
			penalty = self.penalty(pic)

			fitness = (1-self.penalty_factor)*certainty + self.penalty_factor*(1-penalty)
		else:
			fitness = self.certainty(pic)

		return fitness

	def get_algorithm_name(self):
		return "Greedy Algorithm"

	def get_picture_title(self):
		title = f"Iteration:{self.iteration_num}, Label:{self.settings.label}\n"
		return title + "Fitness:{0:.2f}%".format(round(self.max_fitness*100, 2))

	def get_progress_status(self):
		status = f"Algorithm:Greedy, Model:{self.settings.model.name}, Iteration:{self.iteration_num}, Label:{self.settings.label}" + \
				 ", Fitness:{0:.4f}".format(round(self.max_fitness, 4))
		return status

	def get_file_progress(self):
		return f"Iteration:{self.iteration_num}" + \
			   ", Certainty:{0:.4f}".format(round(self.max_fitness, 4))

	def get_best_picture(self):
		return self.pic

	def get_best_fitness(self):
		return self.max_fitness

	def termination_condition(self):
		return self.last_max_fitness == self.max_fitness or self.max_fitness >= 0.99


from decimal import Decimal

import click

from PyNFSe.cli import constants
from PyNFSe.utils.entidades import Servico

def servico():
    servico = Servico()
    servico.valor_servico = Decimal(click.prompt('Valor serviço'))
    servico.iss_retido = int(click.prompt('ISS Retido (1 - Sim / 2 - Não)', type=click.Choice(['1', '2']), default=constants.ISS_RETIDO))
    servico.item_lista = click.prompt('Código de item da lista de serviço', default=constants.ITEM_LISTA)
    servico.discriminacao = click.prompt('Discriminação do serviço prestado')
    servico.codigo_municipio = click.prompt('Código do município', default=constants.CODIGO_MUNICIPIO)
    servico.codigo_cnae = click.prompt('Código CNAE', type=int, default=constants.CODIGO_CNAE)
    servico.codigo_tributacao_municipio = click.prompt('Código de Tributação', default=servico.item_lista)
    servico.aliquota = Decimal(click.prompt('Aliquota', default=constants.ALIQUOTA))

    return servico


import urllib.request
import json

class JamendoUtil:

    def __init__(self, client_id, base_url):
        if not client_id:
            raise Exception("You must provide a client_id setting")

        self.client_id = client_id

        self.base_url = base_url

    def _createUrlParameters(self, **kwargs):
        params = dict()
        params["client_id"] = self.client_id
        for key in kwargs:
            params[key] = kwargs[key]

        return urllib.parse.urlencode(params)

    def _parseResponse(self, response):

        jsonResp = json.loads(response.decode("UTF-8"))
        if(jsonResp == None or jsonResp["headers"] == None):
            raise JamendoError(12000, "Error when load JSON response")

        if(jsonResp["headers"]["status"] != "success"):
            raise JamendoError(jsonResp["headers"]["code"], jsonResp["headers"]["error_message"])

        return jsonResp

    def getUserId(self, userName):

        if(userName == None or len(userName) <= 0):
            raise Exception("User name should not be empty")

        requestUrl = self.base_url + "/users/?%s" % self._createUrlParameters(name=userName)

        request = urllib.request.Request(requestUrl)
        response = urllib.request.urlopen(request)

        jsonResponse=response.read()
        obj = self._parseResponse(jsonResponse)

        if(len(obj["results"]) < 1):
            raise JamendoError(12001, "Empty result when trying to get user id")

        return obj["results"][0]["id"]

    def getPublicPlaylists(self, userId, limit = 10, offset = 0):

        if(userId == None or int(userId) <= 0):
            raise Exception("User id must be set")

        requestUrl = self.base_url + "/playlists/?%s" % self._createUrlParameters(user_id=userId, limit=limit, offset = offset)
        request = urllib.request.Request(requestUrl)
        response = urllib.request.urlopen(request)

        jsonResponse=response.read()
        obj = self._parseResponse(jsonResponse)

        return obj["results"]

    def getPlaylistTracks(self, playlistId):
        if(playlistId == None or int(playlistId) <= 0):
            raise Exception("Playlist id must be set")

        requestUrl = self.base_url + "/playlists/tracks/?%s" % self._createUrlParameters(id=playlistId)
        request = urllib.request.Request(requestUrl)
        response = urllib.request.urlopen(request)

        jsonResponse=response.read()
        obj = self._parseResponse(jsonResponse)

        if len(obj["results"]) <= 0 or len(obj["results"][0]) <= 0:
            return []

        return obj["results"][0]["tracks"]

class JamendoError(Exception):

    def __init__(self, code, message):
        self.code = code
        self.message = message


# -*- coding: utf-8 -*-
from django import forms
from django import template
from models import ContactPage
from djangular.forms import NgFormValidationMixin, NgModelFormMixin
from property.models import Property,Borough,Neighborhood

register = template.Library()

#from uni_form.helper import FormHelper

class ContactErrorList(list):
    pass

class ContactForm(NgFormValidationMixin, NgModelFormMixin, forms.Form):
    name = forms.CharField(
        max_length=100,
        help_text=u'',
    )

    email = forms.EmailField()

    subject = forms.ChoiceField(
        choices=(
            ("request", "Request info"),
            ("feedback", "Send a feedback"),
            ("meetup", "Request an appointment"),
        ),
        help_text=u'',
    )

    message = forms.CharField(
        max_length=1000,
        help_text=u'',
        widget=forms.Textarea(
            attrs={
                'Message': '',
            }
        ),
    )

    def clean(self):
        cleaned_data = super(ContactForm, self).clean()
      #  raise forms.ValidationError("This error was added to show the non field errors styling.")
        return cleaned_data

    def form_invalid(self, form):
        if self.request.is_ajax():
            to_json_responce = dict()
            to_json_responce['status'] = 0
            to_json_responce['form_errors'] = form.errors

     #       to_json_responce['new_cptch_key'] = CaptchaStore.generate_key()
      #      to_json_responce['new_cptch_image'] = captcha_image_url(to_json_responce['new_cptch_key'])

            return HttpResponse(json.dumps(to_json_responce), content_type='application/json')

    def form_valid(self, form):
        form.save()
        if self.request.is_ajax():
            to_json_responce = dict()
            to_json_responce['status'] = 1

            to_json_responce['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_responce['new_cptch_image'] = captcha_image_url(to_json_responce['new_cptch_key'])
            return HttpResponse(json.dumps(to_json_responce), content_type='application/json')

class ContactModelForm(forms.ModelForm):
    class Meta:
        model = ContactPage
        field = ('name','email', 'subject', 'message')

class SearchForm(NgFormValidationMixin, NgModelFormMixin, forms.Form):

    borough = forms.ModelMultipleChoiceField(queryset=Borough.objects.all())

    class Meta:
        model = Property
        field = ('borough')

inquiry_form = SearchForm(form_name='inquiry_form', scope_prefix='inquiry_model')
contact_form = ContactForm(form_name='contact_form', scope_prefix='contact_model')


# Zachary Hoover || Guided Practice #22
# 12-05-22
import os
from inspect import getmembers, isfunction

# repeating code
###############

global clear
clear = lambda: os.system('clear' if os.name == 'posix' else 'cls')
funcName = ""

def printHeader():
  clear()
  print("\n    Guided Practice #22   ")
  print(" --------------+--------------")
  print(f" Function: {funcName} \n")
  return

def returnMain():
  print("\n Press Enter to continue")
  input()
  autoMenu()

################################################
# start functions here

def sort():
  printHeader()

  cars = ["bmw", "audi", "toyota", "subaru"]
  print(" Pre-sorted list:", cars)

  cars.sort()
  print(" Sorted list:", cars)

  returnMain()

def reverse():
  printHeader()

  cars = ["bmw", "audi", "toyota", "subaru"]
  print(" Pre-sorted list:", cars)

  cars.sort(reverse=True)
  print(" Sorted list:", cars)

  returnMain()

def temp_sort():
  printHeader()

  cars = ["bmw", "audi", "toyota", "subaru"]
  print(" Original list:", cars)

  print(" Sorted cars:", sorted(cars))
  print(" Original list again:", cars)

  returnMain()

def sorted_func():
  printHeader()

  game_points = [3, 14, 0, 8, 21, 1, 3, 8]
  # set sorted list to a var
  sorted_points = sorted(game_points)

  print(" Game points:", game_points)
  print(" Sorted points:", sorted_points)

  returnMain()

def sorted_func_2():
  printHeader()

  x = [2, 8, 1, 4, 6, 3, 7]

  print(" Sorted list returned:", sorted(x))
  print(" Reverse ssort:", sorted(x, reverse=True))
  print("\n Original list:", x)

  returnMain()

def sorted_string():
  printHeader()

  x = "python"
  print(" Sorted string:", x)

  returnMain()

def reverse_list():
  printHeader()

  cars = ["bmw", "audi", "toyota", "subaru"]
  print(" Cars:", cars)

  cars.reverse()
  print(" Cars reverse:", cars)

  returnMain()

def length_of_list():
  printHeader()

  cars = ["bmw", "audi", "toyota", "subaru"]
  print(" Length of cars:", cars)

  returnMain()

def extend_list():
  printHeader()

  example1 = [1, 2, 3]
  print(" Original list:", example1)
  example1.extend([4, 5, 6])
  print(" Extended list:", example1)

  returnMain()

def extend_by_lst():
  printHeader()

  example1 = [1, 2, 3]
  example2 = [4, 5, 6]

  print(" Example 1:", example1)
  print(" Example 2:", example2)

  # extend exampe1
  example1.extend(example2)

  print("\n Extended list:", example1)

  returnMain()

################################################

menuMode = 0
currentBench = -1
usable = []

def autoMenu():
  global menuMode
  global currentBench
  global usable
  global funcName

  funcName = "autoMenu"

  if menuMode == 1:
    if currentBench > len(usable)-1:
      menuMode = 0
      currentBench = -1
      autoMenu()
    else:
      currentBench += 1
      funcName = usable[currentBench][0]
      usable[currentBench][1]()

  if menuMode == 2:
    if currentBench > len(usable)-1:
      menuMode = 0
      currentBench = -1
      autoMenu()
    else:
      currentBench += 1
      funcName = usable[currentBench][0]
      usable[currentBench][1]()

  else:
    printHeader()

    # change were it says 'baseTemplate' to module name.
    import GuidedPractice22 as foo
    list = []
    list = getmembers(foo, isfunction)

    i = 0
    x = 0
    exceptions = [
      "autoMenu",
      "printHeader",
      "getmembers",
      "clear",
      "time",
      "isfunction",
      "returnMain",
      "cls",
    ]

    usable = []
    print("NOTE: Benchmark mode is still broken on first run,\nrun it again and things should work fine. (i'll fix it eventually)")
    print(">> ----+ Functions +---- <<")
    while i < len(list):
      if list[i][0] not in exceptions:
        x += 1
        print(f"  {x}. {list[i][0]}")
        usable.append(list[i])
      i += 1

    print("\n>> ----+ Utilities +---- <<")
    print(f"  {x+1}. Exit program")
    print(f"  {x+2}. Benchmark (run all)")
    print(f"  {x+3}. Debug (to be added later)")

    try:
      usrin = int(input("\n Enter number of the item: "))
      if usrin == len(usable) + 1:
        SystemExit()
      elif usrin == len(usable) + 2:
        menuMode = 1
        print("Bench")
        autoMenu()
      elif usrin == len(usable) + 3:
        menuMode = 2
        print("Debug")
        autoMenu()
      else:
        funcName = usable[usrin - 1][0]
        usable[usrin - 1][1]()

    except:
      autoMenu()

# auto menu ends
if __name__ == "__main__":
  # program start
  autoMenu()


import random

input("What is your guessed number?")
user_choice = int(input())
available_choice = range(0, 10000)
while not user_choice in available_choice:
    print("Choose another number between 0 and 10000.")
    user_choice = int(input())
computer_choice = random.choice(available_choice)
print(f"You chose {user_choice} and the computer chose {computer_choice}.")


# Movie day
TIME_TRAIN = 0.15

# Време за снимки – цяло число в диапазона [0… 1440]
# Брой сцени  – цяло число в диапазона [5… 25]
# Времетраене на сцена – цяло число в диапазона [20… 90]

time_available = int(input())
scenes_count = int(input())
scene_length = int(input())

time_for_shootings = scenes_count * scene_length
time_needed = time_for_shootings + (time_available * TIME_TRAIN)

if time_available >= time_needed:
    print(f"You managed to finish the movie on time! "
          f"You have {round(time_available - time_needed)} minutes left!")
else:
    print(f"Time is up! To complete the movie you need {round(time_needed - time_available)} minutes.")


# https://atcoder.jp/contests/agc032/tasks/agc032_b
# 完全グラフからどの辺を減らそうかって考えるとわかる

N = int(input())
ans = set()
for i in range(1, N + 1):
    for j in range(i + 1, N + 1):
        ans.add((i, j))

if N & 1:  # 奇数
    N -= 1

for k in range(N // 2):
    i = k + 1
    j = N - k
    ans.remove((i, j))
print(len(ans))
for i, j in ans:
    print(i, j)


from PIL import Image

ALPHA = {(255, 255, 0, 255), (255, 255, 0)}

PALETTE_MAP = {
    (1, 1, 1, 255): 1,
    (62, 184, 73, 255): 2,
    (116, 208, 125, 255): 3,
    (89, 85, 224, 255): 4,
    (128, 118, 241, 255): 5,
    (185, 94, 81, 255): 6,
    (101, 219, 239, 255): 7,
    (219, 101, 89, 255): 8,
    (255, 137, 125, 255): 9,
    (204, 195, 94, 255): 10,
    (222, 208, 135, 255): 11,
    (58, 162, 65, 255): 12,
    (183, 102, 181, 255): 13,
    (204, 204, 204, 255): 14,
    (255, 255, 255, 255): 15
}

PALETTE_MAP.update(dict((tuple(k[:3]), v) for k, v in PALETTE_MAP.items()))

def split_char(char_entry):
    """
    Splits the char_entry as in defined_chars returned by create_charset()
    to pattern and colour tables.
    :param char_entry:
    :return:
    """
    pattern = []
    colours = []
    for b in range(0, 8 * 8, 8):
        row = char_entry[b:(b + 8)]
        row = [PALETTE_MAP[px] for px in row]
        cs = set(row)
        if len(cs) == 1:
            cols = [0, cs.pop()]
        else:
            cols = list(cs)
            cols.sort()
        bits = []
        for px in row:
            if px == cols[1]:
                bits.append("0")
            else:
                bits.append("1")
        pattern.append(int("".join(bits), 2))
        colours.append(16 * cols[0] + cols[1])
    return tuple(pattern), tuple(colours)

def create_charset(imgname, defined_chars=None, orientation="horizontal", redundancy=False):
    """
    Read a PNG file and convert it.
    """
    img = Image.open(imgname)
    w, h = img.size
    print("Read image size:", w, h)
    if defined_chars is None:
        defined_chars = {}

    n_key = len(defined_chars)
    actual_output = {}

    if orientation == "horizontal":
        for y0 in range(0, h, 8):
            for x0 in range(0, w, 8):
                ch = []
                for y in range(y0, y0 + 8):
                    for x in range(x0, x0 + 8):
                        px = img.getpixel((x, y))
                        if px in ALPHA:
                            break
                        ch.append(px)
                    if px in ALPHA:
                        break
                if px in ALPHA:
                    continue
                ch = tuple(ch)
                if ch not in defined_chars or redundancy:
                    key = n_key
                    n_key += 1
                    defined_chars[ch] = key
                actual_output[(x0 / 8, y0 / 8)] = defined_chars[ch]
    else:
        for x0 in range(0, w, 8):
            for y0 in range(0, h, 8):
                ch = []
                for y in range(y0, y0 + 8):
                    for x in range(x0, x0 + 8):
                        px = img.getpixel((x, y))
                        if px in ALPHA:
                            break
                        ch.append(px)
                    if px in ALPHA:
                        break
                if px in ALPHA:
                    continue
                ch = tuple(ch)
                if ch not in defined_chars or redundancy:
                    key = n_key
                    n_key += 1
                    defined_chars[ch] = key
                actual_output[(x0 / 8, y0 / 8)] = defined_chars[ch]
    print("Actual output size:", len(actual_output))
    return defined_chars, actual_output

def rle_encode_sequence(seq):
    colourcoding = []
    current_batch = None
    final_output = []
    for r in seq:
        final_output.append(r)
        if current_batch is None or current_batch[1] != r:
            if current_batch is not None:
                colourcoding.extend(current_batch)
            current_batch = [0, r]
        current_batch[0] += 1
        if current_batch[0] == 255:
            colourcoding.extend(current_batch)
            current_batch = None
    if current_batch is not None:
        colourcoding.extend(current_batch)

    colourcoding.append(0)
    return colourcoding

def convert_to_palette(defined_char, colours):
    """
    Take in a defined character and the colour encoding for each
    pixel row; return the character converted to binary using the
    colour mapping defined by colours.
    """

    pxs = []
    for i in range(0, 64, 8):
        pxs.append(defined_char[i:(i+8)])

    patterns = []
    for row, clr in zip(pxs, colours):
        as_bits = []
        for i in range(8):
            c = row[i]
            if PALETTE_MAP[c] == clr & 15:
                as_bits.append("0")
            else:
                as_bits.append("1")
        patterns.append(int("".join(as_bits), 2))
    return patterns

def batch_convert(defined_chars, clr):
    patterns = []
    invmap = dict((v, k) for k, v in defined_chars.items())

    c1 = clr >> 4

    for k, vall in sorted(invmap.items()):
        as_bits = []
        for i in range(0, 64, 8):
            v = vall[i:(i + 8)]
            for c in v:
                c = PALETTE_MAP[c]
                if c == c1:
                    as_bits.append("1")
                else:
                    as_bits.append("0")
                if len(as_bits) == 8:
                    patterns.append(int("".join(as_bits), 2))
                    as_bits = []
    return patterns

def rle_encode_graphics(defined_chars, first_color=(0, 0)):
    patterns = []
    colors = []
    invmap = dict((v, k) for k, v in defined_chars.items())

    prev_col = first_color
    for k, vall in sorted(invmap.items()):
        as_bits = []
        for i in range(0, 64, 8):
            v = vall[i:(i + 8)]
            c0 = PALETTE_MAP[min(v)]
            c1 = PALETTE_MAP[max(v)]
            c0, c1 = min(c0, c1), max(c0, c1)
            if c0 == c1 and c0 in prev_col:
                c0, c1 = prev_col
            for c in v:
                c = PALETTE_MAP[c]
                if c == c0:
                    as_bits.append("0")
                else:
                    as_bits.append("1")
                if len(as_bits) == 8:
                    patterns.append(int("".join(as_bits), 2))
                    as_bits = []
            colors.append(c0 + c1 * 16)
            prev_col = (c0, c1)
        colourcoding = rle_encode_sequence(colors)
    return colourcoding, patterns


# start

# smiley

# setup
import turtle
import time
star = 4
t = turtle.Turtle()
a = 0
t.color("red")
t.speed(1)

# star 1
t.pu()
t.goto(-100, 100)
t.pd()
while a <= star:
    t.fd(50)
    t.rt(144)
    a = a + 1
t.fd(50)
a = 0

# star 2
t.pu()
t.goto(100, 100)
t.pd()
while a <= star:
    t.fd(50)
    t.rt(144)
    a = a + 1
t.fd(50)
a = 0

# half circle
t.pu()
t.goto(-25, 0)
t.pd()
t.rt(90)
t.circle(50, 180)

# final
time.sleep(1)

# done

# end


from PyQt5 import QtWidgets, uic, QtGui, QtCore
from PyQt5.QtCore import QSettings
from settingsWindow import Ui_SettingsWindow
from userProfile import SETTINGS_DEFAULT, SETTINGS_CUSTOM, SHORTCUTS_DEFAULT, SHORTCUTS_CUSTOM

def themeLoader(self): #function that settings current theme
    if self.theme == '':
        try:
            if self.settings.value('theme') != None:
                self.theme = self.settings.value('theme')
            else: self.theme = 'darkTheme'
        except:
            self.theme = 'darkTheme'
    else:
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../icons/%s/headphones.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.destPronounceButton.setIcon(icon)
        self.ui.srcPronounceButton.setIcon(icon)

    #change icons according to the chosen theme
    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap("../icons/%s/left-arrow.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.ui.previousButton.setIcon(icon)
    icon.addPixmap(QtGui.QPixmap("../icons/%s/right-arrow.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.ui.nextButton.setIcon(icon)
    icon.addPixmap(QtGui.QPixmap("../icons/%s/gear.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.ui.toolButton.setIcon(icon)
    icon.addPixmap(QtGui.QPixmap("../icons/%s/copy.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.ui.copyButton.setIcon(icon)
    # icon.addPixmap(QtGui.QPixmap("../icons/%s/adjust.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    # self.ui.preferencesButton.setIcon(icon)
    icon.addPixmap(QtGui.QPixmap("../icons/%s/swap.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.ui.swapButton.setIcon(icon)
    icon.addPixmap(QtGui.QPixmap("../icons/%s/click.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.ui.translateButton.setIcon(icon)
    icon.addPixmap(QtGui.QPixmap("../icons/%s/google.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.ui.googleButton.setIcon(icon)
    icon.addPixmap(QtGui.QPixmap("../icons/%s/logoDark.png"%self.theme), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    self.settingsWindow.ui.labelIcon.setPixmap(QtGui.QPixmap("../icons/%s/logoDark.png"%self.theme).scaled(60,60, transformMode=QtCore.Qt.SmoothTransformation))
    self.settingsWindow.ui.buttonBox.button(QtWidgets.QDialogButtonBox.Save).setIcon(QtGui.QIcon())
    self.setWindowIcon(QtGui.QIcon('../icons/%s/logoDark.png'%self.theme))

    if self.theme == 'darkTheme': #change text style etc. according to the chosen theme
        QtWidgets.QPushButton.setStyleSheet(self, open('darkStyle.css').read()) #theme css profile

        for item in range(self.ui.horizontalLayout_3.count()):
            self.ui.horizontalLayout_3.itemAt(item).widget().setStyleSheet('background-color: #202020; color: #ffffff;')
        for item in [0,1,3]:
            self.ui.horizontalLayout_4.itemAt(item).widget().setStyleSheet('background-color: #202020; color: #ffffff;')
        for item in range(self.ui.horizontalLayout_2.count()):
            self.ui.horizontalLayout_2.itemAt(item).widget().setStyleSheet('background-color: #202020; color: #ffffff;')
        self.settingsWindow.ui.horizontalLayout.itemAt(0).widget().setStyleSheet('color: #ffffff;')
        self.settingsWindow.ui.horizontalLayout.itemAt(1).widget().setStyleSheet('background-color: #202020; color: #ffffff;')
        self.settingsWindow.ui.buttonBox.setStyleSheet('background-color: #202020; color: #ffffff;')
        self.settingsWindow.setStyleSheet(open('darkStyle.css').read())
        self.color = '#b6b6b6'
        self.colorAdd = '#b6b6b6'
        self.colorSolid = '#ffffff'
        self.settingsWindow.ui.themeBox.setCurrentIndex(0)

    if self.theme == 'lightTheme':
        QtWidgets.QPushButton.setStyleSheet(self, open('lightStyle.css').read()) #theme css profile

        for item in range(self.ui.horizontalLayout_3.count()):
            self.ui.horizontalLayout_3.itemAt(item).widget().setStyleSheet('background-color: #f5f5f5; color: #000000;')
        for item in [0,1,3]:
            self.ui.horizontalLayout_4.itemAt(item).widget().setStyleSheet('background-color: #f5f5f5; color: #000000;')
        for item in range(self.ui.horizontalLayout_2.count()):
            self.ui.horizontalLayout_2.itemAt(item).widget().setStyleSheet('background-color: #f5f5f5; color: #000000;')
        self.settingsWindow.ui.horizontalLayout.itemAt(0).widget().setStyleSheet('color: #000000;')
        self.settingsWindow.ui.horizontalLayout.itemAt(1).widget().setStyleSheet('background-color: #f5f5f5; color: #000000;')
        self.settingsWindow.ui.buttonBox.setStyleSheet('background-color: #f5f5f5; color: #000000;')
        self.settingsWindow.setStyleSheet(open('lightStyle.css').read())
        self.color = '#505050'
        self.colorAdd = '#707070'
        self.colorSolid = '#000000'
        self.settingsWindow.ui.themeBox.setCurrentIndex(1)

    # if self.theme == 'systemTheme': (...)

    if self.ui.toTranslateBox.currentIndex() == 0: #handle status bar bug
        self.destLanguage = 'en' #default destination language is English
        self.ui.toTranslateBox.setCurrentText("English")

    #status bar color etc.
    self.ui.status.setText(' %s | %s>%s'
                        %(self.color, self.ui.googleButton.text(), self.ui.fromTranslateBox.currentText(),
                            self.ui.toTranslateBox.currentText()))

def loadData(self): #function that loads settings saved to .conf fil
    #closeEvent almost the same so it can be optimized

    self.settings = QSettings('darktranslate', 'darktranslate') # .conf file. Saves settings after closing

    mainCheckbox = ['autoTranslationCheckbox', 'reTranslationCheckbox', 'translationServicesCheckbox']

    try: #load main settings
        self.resize(self.settings.value('windowSize'))
        self.move(self.settings.value('windowPosition'))
        self.destLanguage = self.settings.value('destLanguage')

        self.destInd = self.settings.value('destInd')

        self.ui.toTranslateBox.setCurrentIndex(int(self.destInd))

        for name in mainCheckbox:
            if self.settings.value(name) == 'True':
                SETTINGS_CUSTOM[name] = True
            else:
                SETTINGS_CUSTOM[name] = False

        if self.settings.value('highlightTranslationCheckbox') == 'False':
            SETTINGS_CUSTOM['highlightTranslationCheckbox'] = False
        else: SETTINGS_CUSTOM['highlightTranslationCheckbox'] = True
    except: #default config
        self.resize(400, 300)
        self.move(500,400)
        self.destLanguage = "en"
        self.destInd = 21
        self.ui.toTranslateBox.setCurrentIndex(0)
        for name in mainCheckbox:
            SETTINGS_CUSTOM[name] = True
        SETTINGS_CUSTOM['highlightTranslationCheckbox'] = False

    try: #load cache
        self.cache = self.settings.value('cache')
        if self.cache == None:
            self.cache = []
    except:
        self.cache = []

    for name in SHORTCUTS_DEFAULT:  #load SHORTCUTS_CUSTOM
        self.settings.beginReadArray('Shortcuts')
        if self.settings.value(name) != None:
            # print(name)
            SHORTCUTS_CUSTOM[name] = self.settings.value(name) #SHORTCUTS_CUSTOM is equal to saved .conf values
        else:
            SHORTCUTS_CUSTOM[name] = SHORTCUTS_DEFAULT[name] #if .conf does not contain saved shortcut, then custom=default
        self.settings.endArray()

    #set shortcuts widgets text to saved values + installEventFilter
    for [shortcut, index] in zip(SHORTCUTS_CUSTOM.values(), [i for i in range(len(self.settingsWindow.ui.verticalLayout_shortcuts))]):
        self.settingsWindow.ui.verticalLayout_shortcuts.itemAt(index).itemAt(1).widget().setText(shortcut)
        self.settingsWindow.ui.verticalLayout_shortcuts.itemAt(index).itemAt(1).widget().installEventFilter(self)

    #load check marks
    self.settingsWindow.ui.autoTranslationCheckbox.setChecked(SETTINGS_CUSTOM.get('autoTranslationCheckbox', SETTINGS_DEFAULT.get('autoTranslationCheckbox', True))) #set autoTranslateCheckbox as custom\as default
    self.settingsWindow.ui.reTranslationCheckbox.setChecked(SETTINGS_CUSTOM.get('reTranslationCheckbox', SETTINGS_DEFAULT.get('reTranslationCheckbox', True))) #set reTranslationCheckbox as custom\as default
    self.settingsWindow.ui.translationServicesCheckbox.setChecked(SETTINGS_CUSTOM.get('translationServicesCheckbox', SETTINGS_DEFAULT.get('translationServicesCheckbox', True))) #set autoTranslateCheckbox as custom\as default
    self.settingsWindow.ui.highlightTranslationCheckbox.setChecked(SETTINGS_CUSTOM.get('highlightTranslationCheckbox', SETTINGS_DEFAULT.get('highlightTranslationCheckbox', False))) #set highlightTranslationCheckbox as custom\as default


# insert insert this code into Default (Windows).sublime-keymap:
# [
#     { "keys": ["f5"], "command": "build_current_code" },
# ]

import time
import sublime
import sublime_plugin
import os
from inspect import getmembers
from pprint import pprint
import re
import shutil
import uuid
from datetime import datetime

# { "keys": ["f5"], "command": "my_build_current_code" },
class MyBuildCurrentCodeCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        file_name = sublime.active_window().active_view().file_name()
        if (MyBuildCurrentCodeCommand.is_maskfile_valid(file_name, '.app.php')):
            MyBuildCurrentCodeCommand.run_php(file_name)
        elif (MyBuildCurrentCodeCommand.is_maskfile_valid(file_name, '.class.php')):
            MyBuildCurrentCodeCommand.run_php(file_name)
        elif (MyBuildCurrentCodeCommand.is_maskfile_valid(file_name, '.app.js')):
            MyBuildCurrentCodeCommand.run_node(file_name)
        elif (MyBuildCurrentCodeCommand.is_maskfile_valid(file_name, '.csv')):
            MyBuildCurrentCodeCommand.run_anki(file_name)
        elif (MyBuildCurrentCodeCommand.is_maskfile_valid(file_name, '.app.py')):
            MyBuildCurrentCodeCommand.run_python(file_name)
        elif (MyBuildCurrentCodeCommand.is_maskfile_valid(file_name, '.app.java')):
            MyBuildCurrentCodeCommand.run_java(file_name)
        elif (MyBuildCurrentCodeCommand.is_maskfile_valid(file_name, '.sql')):
            count_cursors = len(self.view.sel())
            selected_text = self.view.substr(self.view.sel()[0])
            MyBuildCurrentCodeCommand.exec_mysql(file_name, count_cursors, selected_text)
        elif (os.path.basename(file_name) == 'sql_client.json'
            or
            MyBuildCurrentCodeCommand.is_maskfile_valid(file_name, '.sql_server.json')
            ):
            count_cursors = len(self.view.sel())
            selected_text = self.view.substr(self.view.sel()[0])
            MyBuildCurrentCodeCommand.exec_mysql(file_name, count_cursors, selected_text)
    def is_maskfile_valid(file, mask):
        a = file.lower().split(mask.lower())
        l = len(a)
        if (l > 0 and a[l-1] == ''):
            return True
        else:
            return False
    def get_file_buffer(file, selected_text):
        file_buffer = file + '.buffer'
        f = open(file_buffer, 'w')
        f.write(selected_text)
        f.close()
        return file_buffer
    def run_php(file):
        sublime.active_window().active_view().window().run_command("save")
        cmd_php = os.path.join(os.path.dirname(__file__), 'cmd_php.php')
        cmd_string = 'php ' + cmd_php + ' "(file)=' + file + '"'
        sublime.active_window().active_view().window().run_command("exec", {
            'shell': True,
            'cmd': cmd_string
        })
        return
    def run_anki(file):
        sublime.active_window().active_view().window().run_command("save")
        cmd_php = os.path.join(os.path.dirname(__file__), 'cmd_anki.php')
        cmd_string = 'php ' + cmd_php + ' "(file)=' + file + '"'
        sublime.active_window().active_view().window().run_command("exec", {
            'shell': True,
            'cmd': cmd_string
        })
        return
    def run_python(file):
        sublime.active_window().active_view().window().run_command("save")
        cmd_php = os.path.join(os.path.dirname(__file__), 'cmd_anki.php')
        cmd_string = 'python ' + file
        sublime.active_window().active_view().window().run_command("exec", {
            'shell': True,
            'cmd': cmd_string
        })
        return
    def run_java(file):
        sublime.active_window().active_view().window().run_command("save")
        cmd_php = os.path.join(os.path.dirname(__file__), 'cmd_anki.php')
        # Поехали, алгоритм компиляции Java-кода
        oldFileName = file
        # Создаём папку, или чистим её, если она создана ранее
        pathJava = os.path.join(os.path.dirname(__file__), 'java')
        if (os.path.exists(pathJava) and  os.path.isdir(pathJava)):
            listDir = os.listdir(pathJava)
            for f in listDir:
                shutil.rmtree(os.path.join(pathJava, f) )
        else:
            os.mkdir(pathJava)

        timestamp1 = datetime.strftime(datetime.now(), "%Y-%m-%d-%H%M%S") + '-' + uuid.uuid4().hex[0:8]
        pathJavaTemp = os.path.join(pathJava, timestamp1)
        os.mkdir(pathJavaTemp)

        newFileNameJava = os.path.join(pathJavaTemp, os.path.basename(oldFileName).split('.')[0] + '.java')
        newFileNameClass = os.path.join(pathJavaTemp, os.path.basename(oldFileName).split('.')[0] + '.class')
        className = os.path.basename(oldFileName).split('.')[0]

        shutil.copy(oldFileName, newFileNameJava)

        cmd_string = 'javac ' + newFileNameJava
        sublime.active_window().active_view().window().run_command("exec", {
            'shell': True,
            'cmd': cmd_string
        })

        # TODO: В обычных языках программирования нужно ожидать окончания процесса
        # но я не знаю, как это делать, поэтому поставил задержку
        time.sleep(1)
        print(newFileNameClass)
        if os.path.isfile(newFileNameClass):
            cmd_string = 'java -classpath ' + pathJavaTemp + ' ' + className
            sublime.active_window().active_view().window().run_command("exec", {
                'shell': True,
                'cmd': cmd_string
            })
        else:
            print ('file not found: ' + newFileNameClass)
        return
    def run_node(file):
        sublime.active_window().active_view().window().run_command("save")
        cmd_string = 'node "' + file + '"'
        sublime.active_window().active_view().window().run_command("exec", {
            'shell': True,
            'cmd': cmd_string
        })
        return
    def exec_mysql(file, count_cursors, selected_text):
        sublime.active_window().active_view().window().run_command("save")
        # cmd_mysql = os.path.join(os.path.dirname(__file__), 'exec_mysql.php')
        settings = sublime.load_settings("Preferences.sublime-settings")
        sql_http_script = settings.get("my_builder_sql_http_script")
        if sql_http_script is None:
            sql_http_script = os.path.join(os.path.dirname(__file__), 'cmd_mysql.php')
        cmd_string = 'php ' + sql_http_script + ' "(file)=' + file + '" "(text)=' + selected_text + '"'
        if (count_cursors > 1):
            # Выводим ошибку - множественный курсор
            cmd_string = 'php "' + sql_http_script + '" "(file)=' + file + '" "(mode)=error" "(error)=Multiple selection is not supported !!!"'
            sublime.active_window().active_view().window().run_command("exec", {
                'shell': True,
                'cmd': cmd_string
            })
        elif (count_cursors == 1 and re.match(r'^[a-zA-Z-][a-zA-Z0-9_-]{1,80}$', selected_text)):
            # Выделенный текст записываем в отдельный файл и выполняем
            # file_buffer = MyBuildCurrentCodeCommand.get_file_buffer(file, selected_text)
            cmd_string = 'php "' + sql_http_script + '" "(file)=' + file + '" "(mode)=db_help" "(db_help)=' + selected_text + '"'
            sublime.active_window().active_view().window().run_command("exec", {
                'shell': True,
                'cmd': cmd_string
            })
        elif (count_cursors == 1 and len(selected_text)>0):
            if re.match(r'^[a-zA-Z][a-zA-Z0-9_]{4,80}$', selected_text):
                print('yes')
            # Выделенный текст записываем в отдельный файл и выполняем
            file_buffer = MyBuildCurrentCodeCommand.get_file_buffer(file, selected_text)
            cmd_string = 'php "' + sql_http_script + '" "(file)=' + file_buffer + '" "(mode)=buffer"'
            sublime.active_window().active_view().window().run_command("exec", {
                'shell': True,
                'cmd': cmd_string
            })
        else:
            # Выполнение скрипта в обычном режиме
            cmd_string = 'php "' + sql_http_script + '" "(file)=' + file + '" "(mode)=file"'
            sublime.active_window().active_view().window().run_command("exec", {
                'shell': True,
                'cmd': cmd_string
            })
        return

# { "keys": ["ctrl+shift+f5"], "command": "my_build_php_cs_fixer" },
class MyBuildPhpCsFixerCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        file_name = sublime.active_window().active_view().file_name()
        if (MyBuildPhpCsFixerCommand.is_maskfile_valid(file_name, '.php')):
            MyBuildPhpCsFixerCommand.run_php_cs_fixer(file_name)
    def is_maskfile_valid(file, mask):
        a = file.lower().split(mask.lower())
        l = len(a)
        if (l > 0 and a[l-1] == ''):
            return True
        else:
            return False
    def run_php_cs_fixer(file):
        sublime.active_window().active_view().window().run_command("save")
        settings = sublime.load_settings("Preferences.sublime-settings")
        php_cs_fixer = settings.get("my_builder_php_cs_fixer")
        if php_cs_fixer is None:
            cmd_string = 'php ' + os.path.join(os.path.dirname(__file__), 'cmd_php_cs_fixer.php') + ' "(message)=Параметры не настроены!"'
        elif os.path.isfile(php_cs_fixer):
            cmd_string = 'php ' + php_cs_fixer + ' fix ' + file + ' --level=psr2'
        else:
            cmd_string = 'php ' + os.path.join(os.path.dirname(__file__), 'cmd_php_cs_fixer.php') + ' "(message)='+php_cs_fixer+'"'
        sublime.active_window().active_view().window().run_command("exec", {
            'shell': True,
            'cmd': cmd_string
        })


x = int(input('cislo vacsie ako nula a mensie ako sto: '))
# styri + dsat/desiat + dva
# dva   + nast        + ''
# a     + b           + c
# jeden, jedenast, dvadastjeden, tridsatjeden, styridsatjeden,

#pole
if x == 1:
    pole = str('sedela')
    vrany = str('vrana')
elif 2 <= x <= 4:
    pole = str('sedeli')
    vrany = str('vrany')
else:
    pole = str('sedelo')
    vrany = str('vran')

#vacsie ako 10
if x <= 19:
    if x <= 10:
        if x == 1:
            cislo = str('jedna')
        elif x == 2:
            cislo = str('dve')
        elif x == 3:
            cislo = str('tri')
        elif x == 4:
            cislo = str('styri')
        elif x == 5:
            cislo = str('pat')
        elif x == 6:
            cislo = str('sest')
        elif x == 7:
            cislo = str('sedem')
        elif x == 8:
            cislo = str('osem')
        elif x == 9:
            cislo = str('devat')

    elif 11 <= x <= 19:
        if x == 11:
            cislo = str('jedenast')
        elif x == 12:
            cislo = str('dvanast')
        elif x == 13:
            cislo = str('trinast')
        elif x == 14:
            cislo = str('strnast')
        elif x == 15:
            cislo = str('patnast')
        elif x == 16:
            cislo = str('sestnast')
        elif x == 17:
            cislo = str('sedemnast')
        elif x == 18:
            cislo = str('osemnast')
        elif x == 19:
            cislo = str('devatnast')
    print('Na poli '+ pole + ' ' + cislo +' '+ vrany)

else:
    #a
    m = x // 10
    if m == 2:
        a = str('dva')
    elif m == 3:
        a = str('tri')
    elif m == 4:
        a = str('styri')
    elif m == 5:
        a = str('pat')
    elif m == 6:
        a = str('sest')
    elif m == 7:
        a = str('sedem')
    elif m == 8:
        a = str('osem')
    elif m == 9:
        a = str('devat')

    #b
    if 10 < x < 50:
        b = str('dsat')
    elif 50 <= x:
        b = str('desiat')

    #c
    n = x % 10
    if n == 2:
        c = str('dva')
    elif n == 3:
        c = str('tri')
    elif n == 4:
        c = str('styri')
    elif n == 5:
        c = str('pat')
    elif n == 6:
        c = str('sest')
    elif n == 7:
        c = str('sedem')
    elif n == 8:
        c = str('osem')
    elif n == 9:
        c = str('devat')

    print('Na poli '+ pole +' '+ a+b+c+' '+ vrany)


import argparse
import sys

# We need to import pywrap_tensorflow prior to the toco wrapper.
# pylint: disable=invalid-import-order,g-bad-import-order
from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
from tensorflow.python import _pywrap_toco_api
from absl import app

FLAGS = None

def execute(unused_args):
  """Runs the converter."""
  with open(FLAGS.model_proto_file, "rb") as model_file:
    model_str = model_file.read()

  with open(FLAGS.toco_proto_file, "rb") as toco_file:
    toco_str = toco_file.read()

  with open(FLAGS.model_input_file, "rb") as input_file:
    input_str = input_file.read()

  debug_info_str = None
  if FLAGS.debug_proto_file:
    with open(FLAGS.debug_proto_file, "rb") as debug_info_file:
      debug_info_str = debug_info_file.read()

  enable_mlir_converter = FLAGS.enable_mlir_converter

  output_str = _pywrap_toco_api.TocoConvert(
      model_str,
      toco_str,
      input_str,
      False,  # extended_return
      debug_info_str,
      enable_mlir_converter)
  open(FLAGS.model_output_file, "wb").write(output_str)
  sys.exit(0)

def main():
  global FLAGS
  parser = argparse.ArgumentParser(
      description="Invoke toco using protos as input.")
  parser.add_argument(
      "model_proto_file",
      type=str,
      help="File containing serialized proto that describes the model.")
  parser.add_argument(
      "toco_proto_file",
      type=str,
      help="File containing serialized proto describing how TOCO should run.")
  parser.add_argument(
      "model_input_file", type=str, help="Input model is read from this file.")
  parser.add_argument(
      "model_output_file",
      type=str,
      help="Result of applying TOCO conversion is written here.")
  parser.add_argument(
      "--debug_proto_file",
      type=str,
      default="",
      help=("File containing serialized `GraphDebugInfo` proto that describes "
            "logging information."))
  parser.add_argument(
      "--enable_mlir_converter",
      action="store_true",
      help=("Boolean indicating whether to enable MLIR-based conversion "
            "instead of TOCO conversion. (default False)"))

  FLAGS, unparsed = parser.parse_known_args()

  app.run(main=execute, argv=[sys.argv[0]] + unparsed)

if __name__ == "__main__":
  main()


'''
A binary gap within a positive integer N is any maximal sequence of consecutive zeros
that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2.
The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3.
The number 20 has binary representation 10100 and contains one binary gap of length 1.
The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
function solution(N);
that, given a positive integer N, returns the length of its longest binary gap.
The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5,
because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0,
because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..2,147,483,647].

'''
import re

def convert_to_binary(n):
    return bin(n).replace("0b", "")

def count_zeros(n):
    pattern = "^[1]+$"
    result = re.match(pattern, str(n))
    if result:
        return 0
    if str(n).endswith("1"):
        to_string = str(n)
        store = to_string.split("1")
        zero_store = []
        for i in store:
            if "0" in i:
                zero_store.append(i)
        binary_gap = max(zero_store)
        binary_gap = len(binary_gap)
        return binary_gap
    else:
        return 0

def solution1(n):
    num = convert_to_binary(n)
    final_result = count_zeros(num)
    return final_result

# print(solution1(15))

'''
An array A consisting of N integers is given.
Rotation of the array means that each element is shifted right by one index,
and the last element of the array is moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]
(elements are shifted right by one index and 6 is moved to the first place).
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

Write a function:

def solution(A, K)

that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

For example, given

    A = [3, 8, 9, 7, 6]
    K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:

    [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
    [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
    [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given

    A = [0, 0, 0]
    K = 1
the function should return [0, 0, 0]

Given

    A = [1, 2, 3, 4]
    K = 4
the function should return [1, 2, 3, 4]

Assume that:

N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
'''

def solution2(a, k):
    for i in range(1, k + 1):
        print(i)
        a.insert(0, a.pop())
        print(a)
    return a

# print(solution2([1, 2, 3, 4], 3))

'''
A non-empty array A consisting of N integers is given. The array contains an odd number of elements,
and each element of the array can be paired with another element that has the same value,
except for one element that is left unpaired.

For example, in array A such that:

    A[0] = 9  A[1] = 3  A[2] = 9
    A[3] = 3  A[4] = 9  A[5] = 7
    A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
Write a function:

def solution(A)

that, given an array A consisting of N integers fulfilling the above conditions,
returns the value of the unpaired element.

For example, given array A such that:

    A[0] = 9  A[1] = 3  A[2] = 9
    A[3] = 3  A[4] = 9  A[5] = 7
    A[6] = 9
the function should return 7, as explained in the example above.

Write an efficient algorithm for the following assumptions:

N is an odd integer within the range [1..1,000,000];
each element of array A is an integer within the range [1..1,000,000,000];
all but one of the values in A occur an even number of times.
'''

def solution3(A):
    for i in A:
        if A.count(i) == 1:
            return i

# print(solution3([9,3,9,3,9,7,9]))

'''
A small frog wants to get to the other side of the road.
The frog is currently located at position X and wants to get to a position greater than or equal to Y.
The small frog always jumps a fixed distance, D.

Count the minimal number of jumps that the small frog must perform to reach its target.

Write a function:

def solution(X, Y, D)

that, given three integers X, Y and D,
returns the minimal number of jumps from position X to a position equal to or greater than Y.

For example, given:

  X = 10
  Y = 85
  D = 30
the function should return 3, because the frog will be positioned as follows:

after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Write an efficient algorithm for the following assumptions:

X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
'''

def solution4(X,Y,D):
    count = 0
    while X < Y:
        X = X + D
        count += 1
    return count

# print(solution4(10, 85, 30))

'''
Task 1 Your function takes an array of integers (arr), and an integer (x).
You need to find the position in arr that splits the array in two,
where one side has as many occurrences of x as the other side has occurrences of any number but x
(there was some additional info about edge cases, but that's the gist of it).
So, given an array like this: [5, 5, 2, 3, 5, 1, 6] and x being "5", the function should return "4"
(Position 4, holding the number "3" above is the point where you have 2 5's on the one side,
and two "not fives" on the other.
'''
import math

def split_arr(arr):
    first = 0
    second = 0
    if len(arr) % 2 != 0:
        first = math.ceil(len(arr) / 2)
    # print(first)
    # print(arr[first])

'''
Given five positive integers,
find the minimum and maximum values that can be calculated by summing exactly four of the five integers.
Then print the respective minimum and maximum values as a single line of two space-separated long integers.
'''
def maxMin(array):
    store = []
    num = 0
    count = 1
    while count < len(array):
        num += int(array[count])
        count += 1
        array.pop()
    store.append(num)
    print(store)

maxMin([1,2,3,4,5])


from PIL import Image, ImageOps
import numpy as np
from matplotlib import pylab as plt

for k in range(10000):
    img = np.array(Image.open('./image/depth_logarithmic_gray/' + str(k+3000) + '.jpg').convert('I'), 'float32')
    def calc_double(n):
        return n + 40

    img2 = list(map(calc_double, img))

    for i in range(600):
        for j in range(800):
            if img2[i][j] > 255:
                img2[i][j] = 255

    np.save('./image/depth_gray/' + str(k+3000) + '.npy',img2)
    print(str(k+3000) + '.jpg saved')


#creating functions
def Add():
    FNum = (input("First Number: "))
    SNum = (input("Second Number: "))
    print (float(FNum) + float(SNum))
def Subtract():
    FNum = (input("First Number: "))
    SNum = (input("Second Number: "))
    print (float(FNum) - float(SNum))
def Multiply():
    FNum = (input("First Number: "))
    SNum = (input("Second Number: "))
    print (float(FNum) * float(SNum))
def Divide():
    FNum = (input("First Number: "))
    SNum = (input("Second Number: "))
    if int(SNum) == 0:
        print ("Cannot Divide by Zero")
    else:
        print (float(FNum) / float(SNum))
print ("Simple Calculator \nDo not divide by zero!")
done = 'n'

while str(done) != 'y' or 'Y':
    Op = input("What Operation(+ - / *)? ")
    if Op == "+":
        Add()
    elif Op == "-":
        Subtract()
    elif Op == "/":
        Divide()
    elif Op == "*":
        Multiply()
    elif Op == "quit":
        break
    else:
        print("Incorrect Operator")
    done = input("Done? (y)es or (n)o: ")


__version__ = '1.1.0'

# Action log Mon Feb 13 11:37:29 2023

# Macro name: Syn/Ves Mesh Pairing with Measures 04-24-2023 19:28

# ********** BEGIN MACRO ********** #
"""
:name: Syn/Ves Mesh Pairing with Measures 04-24-2023 19:28
:execution: execute
"""

### Import

# Science Stack
import numpy as np
import pandas as pd

# Mesh analysis
import pyvista as pv

# File handling
from PyQt5.QtWidgets import QFileDialog
import os
import time
from PyQt5.QtCore import Qt, pyqtSignal, QObject, QThread, QSize, QByteArray

import logging

start_time = time.time()
# MICRON_MOD: float = 1000000
### User input

def MakePairs(synCom: pd.DataFrame, vesCom: pd.DataFrame, searchVolRad: float, synMeshDir: str, vesMeshDir: str, pb: pyqtSignal):
    searchVolRad = float(searchVolRad)
    candidatePairs = pd.DataFrame({'synLabel': [], 'synX': [], 'synY': [], 'synZ': [], 'vesLabel':[], 'vesX': [], 'vesY': [], 'vesZ': [], 'comDist': []})

    synCom = synCom.set_index('labels')
    vesCom = vesCom.set_index('labels')

    # Load the coordinates for each synapse

    logging.info("Loading all coordinates...")

    # synCom = synCom.head(10)

    for synLabel in synCom.index:

        pb.emit(int((synLabel+1)/len(synCom.index) * 50))

        print(f"SYN {synLabel}")

        synX = float(synCom.loc[synLabel,'comX'])
        synY = float(synCom.loc[synLabel,'comY'])
        synZ = float(synCom.loc[synLabel,'comZ'])

        # Load the coordinates for each vesicle cloud

        for vesLabel in vesCom.index:

            # print(f"VES {vesLabel}")

            vesX = float(vesCom.loc[vesLabel, 'comX'])
            vesY = float(vesCom.loc[vesLabel, 'comY'])
            vesZ = float(vesCom.loc[vesLabel, 'comZ'])

            # If the vesicle cloud has a CoM within the search radius of the synapse, calculate the distance between them and add a row the dataframe of candidate pairs

            if ((vesX >= (synX - searchVolRad)) and (vesX <= (synX + searchVolRad))) and ((vesY >= (synY - searchVolRad)) and (vesY <= (synY + searchVolRad))) and ((vesZ >= (synZ - searchVolRad)) and (vesZ <= (synZ + searchVolRad))):
                comDist = np.sqrt((synX - vesX)**2 + (synY - vesY)**2 + (synZ - vesZ)**2)
                newRow = {'synLabel': [synLabel], 'synX': [synX], 'synY': [synY], 'synZ': [synZ], 'vesLabel': [vesLabel], 'vesX': [vesX], 'vesY': [vesY], 'vesZ': [vesZ], 'comDist': [comDist]}
                newDf = pd.DataFrame(newRow)
                # candidatePairs = candidatePairs.append(newRow, ignore_index = True)
                candidatePairs = pd.concat([candidatePairs, newDf], ignore_index=True)

    # Convert labels to integers

    candidatePairs = candidatePairs.astype({'synLabel':'int'})
    candidatePairs = candidatePairs.astype({'vesLabel':'int'})

    logging.info("Finished loading coordinates!")

    # Save the list of candidate pairs as a csv

    # candidatePairsDir = synVesPairsDir + 'synVesCandidatePairsFromCom.csv'
    # candidatePairs.to_csv(candidatePairsDir, encoding = 'utf-8-sig', index = False)

    ### Calculate minimum distance for each candidate mesh pair

    # Prepare a dataframe containing information about each candidate pair and the shortest distance between their meshes

    meshNND_candidates = pd.DataFrame({'synLabel': [], 'synX': [], 'synY': [], 'synZ': [], 'synHalfSA': [], 'synVol': [], 'synSphere': [], 'synMaxFeret': [], 'synMinFeret': [], 'synAspectRatio': [],
                'vesLabel': [], 'vesX': [], 'vesY': [], 'vesZ': [], 'vesSA': [], 'vesVol': [], 'vesSphere': [], 'vesMaxFeret': [], 'vesMinFeret': [], 'vesAspectRatio': [], 'comDist': [],
                'synVertX': [], 'synVertY': [], 'synVertZ': [],
                'vesVertX': [], 'vesVertY': [], 'vesVertZ': [],'meshNND': []})

    # Go through each row of the candidate pairs dataframe

    logging.info("Iterating through candidate pairs...")

    for i in candidatePairs.index:

        pb.emit(int((i+1)/len(candidatePairs.index) * 49)+50)

        # Load labels for the synapse and the vesicle cloud in the candidate pair
        synLabel = int(candidatePairs.synLabel[i])
        vesLabel = int(candidatePairs.vesLabel[i])

        print(synLabel)
        print(vesLabel)
        print("\n")

        # Load the distance between CoMs for the pair
        comDist = candidatePairs.comDist[i]

        # Write directories for each mesh
        synMeshFile = synMeshDir + '/' + str(synLabel)+ '.stl'
        vesMeshFile = vesMeshDir + '/' + str(vesLabel)+ '.stl'

        # Use PyVista to read the meshes
        reader = pv.get_reader(synMeshFile)
        synMesh = reader.read()

        reader1 = pv.get_reader(vesMeshFile)
        vesMesh = reader1.read()

        # For each point on the synapse mesh, find the nearest point on the vesicle cloud mesh
        # Calculate the distance between these points and record the minimum distance between any two points

        closest_cells, closest_points = vesMesh.find_closest_cell(synMesh.points, return_closest_point=True)
        d_exact = np.linalg.norm(synMesh.points - closest_points, axis=1)
        meshNND_m = np.min(d_exact)

        # Make an array of coordinates for each point on the synapse mesh
        # In the same row, add the coordinates for the closest point on the vesicle mesh and the distance between points
        # Convert the array to a dataframe

        synPointsPaired = np.hstack((synMesh.points, closest_points))
        synPointsPaired = np.hstack((synPointsPaired, np.atleast_2d(d_exact).T))
        synPointsPaired = pd.DataFrame(synPointsPaired)
        synPointsPaired.columns = ['svx', 'svy', 'svz', 'vvx', 'vvy', 'vvz', 'dist']

        # Find the points that have the shortest distance bewteen them and make a dataframe of their coordinates

        synPointsPairedMin = pd.DataFrame(synPointsPaired.loc[synPointsPaired.dist == meshNND_m])

        # Synapse meshes may have multiple points where they are the minimum distance from the vesicle mesh
        # We need these coordinates to visualize the nearest neighbor distance, but only one is necessary
        # Arbitrarily select the first pair of vertices listed with minimum distance between them

        synVertX = (synPointsPairedMin.iloc[0, 0]) * 10**(6)
        synVertY = (synPointsPairedMin.iloc[0, 1]) * 10**(6)
        synVertZ = (synPointsPairedMin.iloc[0, 2]) * 10**(6)

        vesVertX = (synPointsPairedMin.iloc[0, 3]) * 10**(6)
        vesVertY = (synPointsPairedMin.iloc[0, 4]) * 10**(6)
        vesVertZ = (synPointsPairedMin.iloc[0, 5]) * 10**(6)

        # Convert Mesh NND to nm

        meshNND = meshNND_m * 10**(9)

        # Lookup voxel measurements for each syn/ves

        synHalfSA = synCom.loc[synLabel, 'halfSA']
        synVol = synCom.loc[synLabel, 'vol']
        synSphere = synCom.loc[synLabel, 'sphericity']
        synMaxFeret = synCom.loc[synLabel, 'maxFeretLength']
        synMinFeret = synCom.loc[synLabel, 'minFeretLength']
        synAspectRatio = synCom.loc[synLabel, 'aspectRatio']

        vesSA = vesCom.loc[vesLabel, 'SA']
        vesVol = vesCom.loc[vesLabel, 'vol']
        vesSphere = vesCom.loc[vesLabel, 'sphericity']
        vesMaxFeret = vesCom.loc[vesLabel, 'maxFeretLength']
        vesMinFeret = vesCom.loc[vesLabel, 'minFeretLength']
        vesAspectRatio = vesCom.loc[vesLabel, 'aspectRatio']

        # Add a new row to the dataframe containing candidate pairs and the distances between their meshes

        newRow = {'synLabel': [synLabel], 'synX': [candidatePairs.synX[i]], 'synY': [candidatePairs.synY[i]], 'synZ': [candidatePairs.synZ[i]], 'synHalfSA': [synHalfSA], 'synVol': [synVol], 'synSphere': [synSphere], 'synMaxFeret': [synMaxFeret], 'synMinFeret': [synMinFeret], 'synAspectRatio': [synAspectRatio],
                    'vesLabel': [vesLabel], 'vesX': [candidatePairs.vesX[i]], 'vesY': [candidatePairs.vesY[i]], 'vesZ': [candidatePairs.vesZ[i]], 'vesSA': [vesSA], 'vesVol': [vesVol], 'vesSphere': [vesSphere], 'vesMaxFeret': [vesMaxFeret], 'vesMinFeret': [vesMinFeret], 'vesAspectRatio': [vesAspectRatio], 'comDist': [comDist],
                    'synVertX': [synVertX], 'synVertY': [synVertY], 'synVertZ': [synVertZ],
                    'vesVertX': [vesVertX], 'vesVertY': [vesVertY], 'vesVertZ': [vesVertZ],'meshNND': [meshNND]}

        newDf = pd.DataFrame(newRow)

        # meshNND_candidates = meshNND_candidates.append(newRow, ignore_index = True)
        meshNND_candidates = pd.concat([meshNND_candidates, newDf], ignore_index=True)

    # Make a list of synapse labels
    uniqueSynLabels = meshNND_candidates.synLabel.unique()
    uniqueSynLabels = uniqueSynLabels.tolist()

    logging.info("Finished iIterating  candidate pairs!")

    # Prepare a dataframe of synapse-vesicle cloud pairs with the shortest distance between meshes
    synVesPairs = pd.DataFrame({'synLabel': [], 'synX': [], 'synY': [], 'synZ': [], 'synHalfSA': [], 'synVol': [], 'synSphere': [], 'synMaxFeret': [], 'synMinFeret': [], 'synAspectRatio': [],
                'vesLabel': [], 'vesX': [], 'vesY': [], 'vesZ': [], 'vesSA': [], 'vesVol': [], 'vesSphere': [], 'vesMaxFeret': [], 'vesMinFeret': [], 'vesAspectRatio': [], 'comDist': [],
                'synVertX': [], 'synVertY': [], 'synVertZ': [],
                'vesVertX': [], 'vesVertY': [], 'vesVertZ': [],'meshNND': []})

    for label in uniqueSynLabels:

        tempDF = meshNND_candidates[meshNND_candidates['synLabel'] == label]
        newDf = pd.DataFrame(tempDF[tempDF.meshNND == tempDF.meshNND.min()])
        synVesPairs = pd.concat([synVesPairs, newDf], ignore_index=True)

    # Convert labels to integers

    synVesPairs = synVesPairs.astype({'synLabel':'int'})
    synVesPairs = synVesPairs.astype({'vesLabel':'int'})

    # Make a dataframe of unpaired vesicle pools and their measurements
    unpairedVes = pd.DataFrame({'label': [], 'comX': [], 'comY': [], 'comZ': [], 'SA': [], 'vol': [], 'sphericity': [], 'maxFeret': [], 'minFeret': [], 'aspectRatio': []})

    vesComList = vesCom.index.tolist()
    vesLabelList = synVesPairs.vesLabel.tolist()

    logging.info("Noting unpaired vesicles...")

    for label in vesComList:

        if label not in vesLabelList:

            comX = vesCom.loc[label, 'comX']
            comY = vesCom.loc[label, 'comY']
            comZ = vesCom.loc[label, 'comZ']
            SA = vesCom.loc[label, 'SA']
            vol = vesCom.loc[label, 'vol']
            sphere = vesCom.loc[label, 'sphericity']
            maxFeret = vesCom.loc[label, 'maxFeretLength']
            minFeret = vesCom.loc[label, 'minFeretLength']
            aspectRatio = vesCom.loc[label, 'aspectRatio']

            newRow = {'label': [label], 'comX': [comX], 'comY': [comY], 'comZ': [comZ], 'SA': [SA], 'vol': [vol], 'sphericity': [sphere], 'maxFeret': [maxFeret], 'minFeret': [minFeret], 'aspectRatio': [aspectRatio]}
            newDf = pd.DataFrame(newRow)
            # unpairedVes = unpairedVes.append(newRow, ignore_index = True)
            unpairedVes = pd.concat([unpairedVes, newDf], ignore_index = True)

    logging.info("Pairing finished!!!")

    return(candidatePairs, synVesPairs, unpairedVes)

    # ********** END MACRO ********** #


import functools
import threading
import time
import sys

def calc_time(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        finish = time.time()
        print(f'elapsed time: {finish-start}')
        return result
    return wrapper

@calc_time
def func(n):
    print(f'start : {n}')
    for i in range(10):
        print(f'{n}: {i}')
    print(f'finish: {n}')

@calc_time
def main():
    # define threads
    threads = []
    for i in range(5):
        thread = threading.Thread(target=func, name=f'thread-{i}', args=([i]))
        threads.append(thread)

    # start threads
    for thread in threads:
        thread.start()

    # wait until finished
    for thread in threads:
        thread.join()

    return 0

if __name__ == '__main__':
    sys.exit(main())


import pygame

class print_screen(): # kwadrat 50 pix , 10x14
    def main(tab_main,WIDTH,HEIGHT,screen,BORDER_MAIN,square,tab_moving):
        w=0.625*WIDTH # 500
        h=20*square
        start_x=WIDTH//20
        start_y=HEIGHT//100
        pygame.draw.rect(screen,(50, 168, 82),(WIDTH//20-BORDER_MAIN,HEIGHT//100-BORDER_MAIN,w+2*BORDER_MAIN,h+2*BORDER_MAIN),BORDER_MAIN)
        pygame.draw.rect(screen,(0,0,0),(start_x,start_y,w,h))

        n=10
        m=20
        line=2
        for i in range(n+1):
            pygame.draw.line(screen,(55,51,111),(i*square+start_x-line//2,start_y),(i*square+start_x-line//2,start_y+h-line//2),line)

        for i in range(m+1):
            pygame.draw.line(screen,(55,51,111),(start_x,i*square+start_y-line//2),(w+start_x-line//2,i*square+start_y-line//2),line)

        for i in range(m):
            for j in range(n):
                if tab_moving[i][j]==1:
                    pygame.draw.rect(screen,(245, 66, 81),(start_x+line//2+j*square,start_y+line//2+i*square,square-line,square-line))

        for i in range(m):
            for j in range(n):
                if tab_main[i][j]==1:
                    pygame.draw.rect(screen,(58, 133, 119),(start_x+line//2+j*square,start_y+line//2+i*square,square-line,square-line))

    def menu(tab_next,WIDTH,HEIGHT,BORDER_MAIN,screen,score):
        start_x=0.625*WIDTH+BORDER_MAIN+40
        start_y=0
        # score
        pygame.draw.rect(screen,(135, 89, 73),(start_x+0.12*(WIDTH-start_x),0.215*HEIGHT,200,80))
        font_score = pygame.font.SysFont("monospace", 35, True)
        score_spec = font_score.render("Score: "+str(score),500,(145, 158, 25))
        score_pos = score_spec.get_rect(center=((start_x+WIDTH)//2, 0.25*HEIGHT))
        screen.blit(score_spec,score_pos)

        # next block
        w=WIDTH-start_x
        square_next=40

        font_next = pygame.font.SysFont("monospace", 30)
        next_spec = font_next.render("Next: ",500,(0,0,0))
        next_pos = next_spec.get_rect(center=(w*0.4+start_x, 0.4*HEIGHT))
        screen.blit(next_spec,next_pos)

        pygame.draw.rect(screen,(0,0,0),(start_x+w//2-2*square_next,HEIGHT*0.42,4*square_next,4*square_next))
        line=2
        for i in range(5):
            pygame.draw.line(screen,(55,51,111),(i*square_next+start_x+w//2-2*square_next,HEIGHT*0.42),(i*square_next+start_x+w//2-2*square_next,HEIGHT*0.42+4*square_next),line)

        for i in range(5):
            pygame.draw.line(screen,(55,51,111),(start_x+w//2-2*square_next,i*square_next+HEIGHT*0.42),(start_x+w//2+2*square_next,i*square_next+HEIGHT*0.42),line)

        for i in range(4):
            for j in range(4):
                if tab_next[i][j]==1:
                    pygame.draw.rect(screen,(58, 133, 119),(start_x+w//2-2*square_next+j*square_next+line,HEIGHT*0.42+line+i*square_next,square_next-line,square_next-line))

        # key
        key=["Controls: ",
        "Press space to start",
        "UP - Rotate block ",
        "LEFT - Move left ",
        "RIGHT - Move right ",
        "DOWN - Move down"]
        n=len(key)
        space=20
        font_key = pygame.font.SysFont("monospace", 20)
        for i in range(n):
            key_spec = font_key.render(key[i],500,(145, 158, 25))
            # key_pos = key_spec.get_rect((WIDTH-start_x)*0.3+start_x, i*space+0.8*HEIGHT)
            screen.blit(key_spec,((WIDTH-start_x)*0.05+start_x, i*space+0.7*HEIGHT))
        # pygame.draw(key, (10, 10), (0,0,0))

    def print_all(tab_main,tab_next,WIDTH,HEIGHT,screen,BORDER_MAIN,square,score,tab_moving):
        print_screen.main(tab_main,WIDTH,HEIGHT,screen,BORDER_MAIN,square,tab_moving)
        print_screen.menu(tab_next,WIDTH,HEIGHT,BORDER_MAIN,screen,score)


import json
import sys
sys.path.append('../src')
import uuid
import unittest
import yaml
import requests
import os
from pprint import pprint as pp

import aws_lambda_logging
import logging

logger = logging.getLogger()
loglevel = "INFO"
logging.basicConfig(level=logging.ERROR)

Branch = "Prod"

Host = os.environ.get('PORPER_ENDPOINT')
authToken = os.environ.get('AUTH_TOKEN')
region = os.environ.get('AWS_DEFAULT_REGION')

test_group = {
            "customer_id": "64b3bbf4-1f3d-446f-b697-06c2a68f2053",
            "name": "Testing321"
}

def genUrl(Host, Branch, Path):
    return "https://{}/{}{}".format(Host, Branch, Path)

def run_lambda(
    method='post',
    path='/sla',
    headers={'Authorization': authToken},
    body=None,
    env=""
):

    if env == "local":
        import api_handler
        event = {
            'httpMethod': method.upper(),
            'path': path,
            'headers': headers,
        }
        if body:
            event['body'] = body
        context = {}
        ret = api_handler.lambda_handler(event, context)
        ret['body'] = json.loads(ret['body'])
        return ret

    elif env == "remote":
        headers = {
            "Content-Type": "application/json",
            "Authorization": "{}".format(authToken)
        }
        url = genUrl(Host, Branch, path)
        if method == "delete":
            ret = requests.delete(url, headers=headers)
        elif method == "put":
            ret = requests.put(url, headers=headers, data=body)
        elif method == "get":
            ret = requests.get(url, headers=headers)
        else:
            ret = requests.post(url, headers=headers, data=body)
        body = ret.json()
        return {
            "body": body,
            "statusCode": ret.status_code
        }

def get_content(filepath, filename):
    with open(filepath + filename) as data:
        return data.read()

class ProxyUserTest(unittest.TestCase):
    def __init__(self, testName, env):
        super(ProxyUserTest, self).__init__(testName)
        self.env = env

    def test_user_get(self):
        ret = run_lambda(
            path=f"/user",
            method="get",
            env=self.env
        )
        from pprint import pprint as pp
        pp(ret)
        assert len(ret['body']) > 0 and type(ret['body']) == list

class ProxyGroupTest(unittest.TestCase):
    def __init__(self, testName, env):
        super(ProxyGroupTest, self).__init__(testName)
        self.env = env

    def test_group_post(self):
        ret = run_lambda(
            path=f"/group",
            method="post",
            body=json.dumps(test_group),
            env=self.env
        )
        from pprint import pprint as pp
        print("response====================")
        pp(ret)
        try:
            id = ret["body"]["id"]
        except:
            id = ret["body"]
        run_lambda(method="delete", path=f'/group', body=json.dumps({"id": id}), env=self.env)
        assert ret["statusCode"] == 200
        assert ret["body"]["name"] == "Testing321"

    def test_group_put(self):
        ret = run_lambda(
            path=f"/group",
            method="post",
            body=json.dumps(test_group),
            env=self.env
        )

        from pprint import pprint as pp
        print("response====================")
        pp(ret)
        try:
            id = ret["body"]["id"]
        except:
            id = ret["body"]

        ret = run_lambda(
            path=f"/group",
            method="put",
            body=json.dumps({"id": id, "name": "Testing654321"}),
            env=self.env
        )

        run_lambda(method="delete", path=f'/group', body=json.dumps({"id": id}), env=self.env)
        assert ret["statusCode"] == 200
        assert ret["body"]["name"] == "Testing654321"

if __name__ == '__main__':

    if sys.argv[1] == "local":
        env = "local"
    elif sys.argv[1] == "remote":
        env = "remote"
    else:
        print("only local or remote are allowed")
        sys.exit()

    suite = unittest.TestSuite()

    suite.addTest(ProxyUserTest("test_user_get", env))

    suite.addTest(ProxyGroupTest("test_group_post", env))
    suite.addTest(ProxyGroupTest("test_group_put", env))

    test_runner = unittest.TextTestRunner(verbosity=2, resultclass=unittest.TextTestResult) # .run(suite)
    result = test_runner.run(suite)
    sys.exit(not result.wasSuccessful())


# to reproduce, please download my GCJ framework http://github.com/dusek/gcj
# and place this file as problems/2009/round1C/A.py and run
# bin/solve.sh 2009.round1C A <your input file> > <your output file>
# I had problems uploading ZIP archive of the linked repository as source code
# to GCJ
import gcj
import math

class Solver(gcj.Solver):
    def _solve_one(self):
        N=self._getintline()
        R=3*[0]
        V=3*[0]
        Dims=range(len(R))
        for fly in range(N):
            line=self._getlineitems(float)
            r=line[:3]
            v=line[3:]
            for dim in Dims:
                R[dim]+=r[dim]
                V[dim]+=v[dim]
        for dim in Dims:
            R[dim]/=N
            V[dim]/=N
        if V[0]!=0 or V[1]!=0 or V[2]!=0:
            RV=0
            VV=0
            for dim in Dims:
                RV+=R[dim]*V[dim]
                VV+=V[dim]*V[dim]
            t_min=-RV/VV
            if t_min < 0:
                t_min=0
        else:
            t_min=0
        R_min=3*[0]
        for dim in Dims:
            R_min[dim]=R[dim]+t_min*V[dim]
        d_min=0
        for dim in Dims:
            d_min+=R_min[dim]*R_min[dim]
        d_min=math.sqrt(d_min)
        return "%.20f %.20f" % (d_min, t_min)


'''
UPI: HCAM630
NAME: HEATH LOGAN CAMPBELL

'''
import sys
from functools import cmp_to_key
from datetime import datetime

def distX(a, b):
  return a[0] - b[0]

def distY(a, b):
  return a[1] - b[1]

def dist(a, b):
  return distX(a, b) * distX(a, b) + distY(a, b) * distY(a, b)

'''
takes a min point
'''
def min(a, b):
  if (a < b):
    return a
  return b

'''
Brute forces all the points to find the closest
'''
def brute(points):
    minDist = dist(points[0], points[1])
    pointsCount = len(points)
    if pointsCount == 2:
        return minDist
    for i in range(pointsCount-1):
        for j in range(i + 1, pointsCount):
            if i != 0 and j != 1:
              continue
            curDist = dist(points[i], points[j])
            if curDist < minDist:
                minDist = curDist
    return minDist

def bruteForce(points):
    min = sys.maxsize

    for i in range(len(points)):
      for j in range(i+1, len(points)):
            if (dist(points[i], points[j]) < min):
                min = dist(points[i], points[j]);

    return min

def stripClosest(listX, listY, minDist):
    pointXCount = len(listX)
    pointXX = listX[pointXCount // 2][0]
    listOfYs = [x for x in listY if pointXX - minDist <= x[0] <= pointXX + minDist]
    best = minDist
    pointYCount = len(listOfYs)
    for i in range(pointYCount - 1):
        for j in range(i + 1, min(i + 7, pointYCount)):
            dst = dist(listOfYs[i], listOfYs[j])
            if dst < best:
                best = dst
    return best

def closestUtil(sortedByX, ay):
    rangeDiff = len(sortedByX)
    if(rangeDiff <= 3):
        return bruteForce(sortedByX)
    mid = (rangeDiff) // 2;

    leftX = sortedByX[:mid]
    rightX = sortedByX[mid:]

    midpoint = sortedByX[mid][0]

    leftY = list()
    rightY = list()
    for x in ay:
        if x[0] <= midpoint:
          leftY.append(x)
        else:
          rightY.append(x)

    out1 = closestUtil(leftX, leftY)
    out2 = closestUtil(rightX, rightY)

    if out1 <= out2:
        minDist = out1
    else:
        minDist = out2

    stripDist = stripClosest(sortedByX, ay, minDist)
    if minDist <= stripDist:
        return minDist
    else:
        return stripDist

points = []

while(True):
    predecessor = (sys.stdin.readline().rstrip("\n"))
    # if line is blank, we leave
    if(predecessor == ''):
        break
    cordPair = list(map(int, predecessor.split()))
    points.append(cordPair)

start_time = datetime.now()
# Takes about 1.2 second to sort
sortedByX = sorted(points, key=lambda x: x[0])
sortedByY = sorted(points, key=lambda x: x[1])
time_elapsed = datetime.now() - start_time
print('Time elapsed (ms) {}'.format(time_elapsed))
print("sorted")
print(closestUtil(sortedByX, sortedByY))


from pymongo import MongoClient

HOST = "localhost"
PORT = 2222

client = MongoClient(HOST, PORT)
db = client['BouncerEventsDB']
evtColl = db['eventCollection']

def insertItem(item):
    ts = item.pop('time_stamp')
    found = evtColl.find_one(item)
    if not found:
        item['time_stamp'] = ts
        found = item
    else:
        found['time_stamp'] = list(set(found['time_stamp'] + ts))

    evtColl.save(found)

def insertItems(items):
    names = evtColl.find_one({'meta':'names'})
    for i in items:
        i.pop('num')

        #i['time_stamp'] = list(i['time_stamp'])
        ts = list(i.pop('time_stamp'))
        found = evtColl.find_one(i)
        if not found:
            i['time_stamp'] = ts
            found = i
        else:
            found['time_stamp'] = list(set(found['time_stamp'] + ts))

        if not found.get('completed'):
            found['completed'] = []

        e = i['evt_name']
        en = names.get(e)
        if not en:
            names[e] = {
                'fired':0,
                'completed':0,
                i['siminar_id'] :{
                    'fired':0,
                    'completed':0,
                    }
                }

        names[e]['fired'] = len(found['time_stamp'])
        si = names[e].get(i['siminar_id'])
        if not si:
            si = names[e][i['siminar_id']]
            si = 0
        si['fired'] = len(found['time_stamp'])
        evtColl.save(found)

    evtColl.save(names)