import requests
import tkinter as tk
from tkinter import ttk, Frame

def report(d):
    district = d.get()

    lf3 = ttk.LabelFrame(gui, text = "District Data: " + district, style = "Red.TLabelframe")
    lf3.place(x=690, y=350)
    Frame(lf3, width=670, height=380, background = 'Light Blue').pack()

    try:
        dist_pop = data[state_code]["districts"][district]["meta"]["population"]
        dist_v1 = data[state_code]["districts"][district]["total"]["vaccinated1"]
        dist_v2 = data[state_code]["districts"][district]["total"]["vaccinated2"]
        dist_v1_p = (dist_v1/dist_pop)*100
        dist_v2_p = (dist_v2/dist_pop)*100
    except:
        pass

    yy = 430

    try:
        for key, value in data[state_code]["districts"][district]["delta"].items():
             tk.Label(gui, text="Today's Report: " + date1, font=('Calibri Bold', 16), fg="dark blue", bg="Light Blue").place(x=700, y=380)
             p1 = key.replace('{', " ")
             p1 = p1.replace('}', " ")
             tk.Label(gui, text=p1, font=('Calibri Bold', 14), fg="Black", bg="Light Blue").place(x=700, y=yy)
             tk.Label(gui, text=value, font=('Calibri', 14), fg="Black", bg="Light Blue").place(x=900, y=yy)
             yy = yy+30
    except:
        tk.Label(gui, text="Today's Data Upload is in Progress\nPlease Try After Sometime", font=('Calibri Bold', 15), fg="red", bg="Light Blue").place(x=700, y=450)
    cnf, dead, rec = 0, 0, 0
    yy = 430
    for key, value in data[state_code]["districts"][district]["total"].items():
         tk.Label(gui, text="Cumulative Till Date", font=('Calibri Bold', 16), fg="dark blue", bg="Light Blue").place(x=1050, y=380)

         p1 = key.replace('{', " ")
         p1 = p1.replace('}', " ")

         if p1 == "confirmed":
             cnf = value
         if p1 == "deceased":
             dead = value
         if p1 == "recovered":
             rec = value

         tk.Label(gui, text=p1, font=('Calibri Bold', 14), fg="Black", bg="Light Blue").place(x=1050, y=yy)
         tk.Label(gui, text=value, font=('Calibri', 14), fg="Black", bg="Light Blue").place(x=1250, y=yy)
         yy = yy+30
    try:
        active = cnf-dead-rec
        rec_rate = (rec/cnf)*100
    except:
        tk.Label(gui, text="District wise break up is not available", font=('Calibri Bold', 20), fg="Red", bg="Light Blue").place(x=700, y=650)
        return()
    tk.Label(gui, text="Active Caseload: " + str(active), font=('Calibri Bold', 20), fg="Red", bg="Light Blue").place(x=700, y=660)
    tk.Label(gui, text="Recovery Rate  : " + str(round(rec_rate,1)) + " %", font=('Calibri Bold', 20), fg="Dark Green", bg="Light Blue").place(x=700, y=700)
    tk.Label(gui, text="Population: " + str(dist_pop), font=('Calibri Bold', 20), fg="brown", bg="Light Blue").place(x=1020, y=660)
    tk.Label(gui, text="Vaccination: ", font=('Calibri Bold', 20), fg="Dark Green", bg="Light Blue").place(x=1020, y=700)
    tk.Label(gui, text="Dose 1: " + str(round(dist_v1_p,1)) + " %" + "\nDose 2:   " + str(round(dist_v2_p,1)) + " %", font=('Calibri Bold', 14), fg="Dark Green", bg="Light Blue").place(x=1180, y=695)

def select_district(s):
    state = s.get()
    global key, data, gui, state_code, date1

    lf2 = ttk.LabelFrame(gui, text = "State Data: " + state, style = "Red.TLabelframe")
    lf2.place(x=10, y=350)
    Frame(lf2, width=670, height=380, background = 'Light Blue').pack()

    lf3 = ttk.LabelFrame(gui, text = "District Data", style = "Red.TLabelframe")
    lf3.place(x=690, y=350)
    Frame(lf3, width=670, height=380, background = 'Light Blue').pack()

    if   state == "Andaman & Nicobar Islands":          state_code = "AN"
    elif state == "Andhra Pradesh":                     state_code = "AP"
    elif state == "Arunachal Pradesh":                  state_code = "AR"
    elif state == "Assam":                              state_code = "AS"
    elif state == "Bihar":                              state_code = "BR"
    elif state == "Chandigarh":                         state_code = "CH"
    elif state == "Chattisgarh":                        state_code = "CT"
    elif state == "Dadra & Nagar Haveli \ Daman & Diu": state_code = "DN"
    elif state == "Delhi":                              state_code = "DL"
    elif state == "Goa":                                state_code = "GA"
    elif state == "Gujarat":                            state_code = "GJ"
    elif state == "Haryana":                            state_code = "HR"
    elif state == "Himachal Pradesh":                   state_code = "HP"
    elif state == "Jammu & Kashmir":                    state_code = "JK"
    elif state == "Jharkhand":                          state_code = "JH"
    elif state == "Karnataka":                          state_code = "KA"
    elif state == "Kerala":                             state_code = "KL"
    elif state == "Ladakh":                             state_code = "LA"
    elif state == "Lakshadweep":                        state_code = "LD"
    elif state == "Madhya Pradesh":                     state_code = "MP"
    elif state == "Maharashtra":                        state_code = "MH"
    elif state == "Manipur":                            state_code = "MN"
    elif state == "Meghalaya":                          state_code = "ML"
    elif state == "Mizoram":                            state_code = "MZ"
    elif state == "Nagaland":                           state_code = "NL"
    elif state == "Odisha":                             state_code = "OR"
    elif state == "Puducherry":                         state_code = "PY"
    elif state == "Punjab":                             state_code = "PB"
    elif state == "Rajasthan":                          state_code = "RJ"
    elif state == "Sikkim":                             state_code = "SK"
    elif state == "Tamil Nadu":                         state_code = "TN"
    elif state == "Telangana":                          state_code = "TG"
    elif state == "Tripura":                            state_code = "TR"
    elif state == "Uttar Pradesh":                      state_code = "UP"
    elif state == "Uttarakhand":                        state_code = "UT"
    elif state == "West Bengal":                        state_code = "WB"

    p1 = []
    dist = data[state_code]['districts']
    dist = list(dist.keys())

    selected_dist = tk.StringVar(gui)
    tk.Label(gui, text="Select District: ", font=('Calibri Bold', 16), fg="Black", bg="Light Blue").place(x=380, y=190)
    cb1 = ttk.Combobox(gui, textvariable=selected_dist, width=35, height=20, values=dist, font=('Halvetica', 12))
    cb1.place(x=550, y=195)
    cb1.current(0)
    tk.Button(gui, text = "Submit", command = lambda: report(selected_dist), font=('Calibri Bold', 12), fg="white", bg="Dark Blue", width = 10).place(x=950, y=190)

    cnf, dead, rec = 0, 0, 0
    yy = 430
    try:
        state_pop = data[state_code]["meta"]["population"]
        state_v1 = data[state_code]["total"]["vaccinated1"]
        state_v2 = data[state_code]["total"]["vaccinated2"]
        state_v1_p = (state_v1/state_pop)*100
        state_v2_p = (state_v2/state_pop)*100
    except:
        pass
    try:
        for key, value in data[state_code]['delta'].items():
             date1 = data[state_code]["meta"]["date"]
             tk.Label(gui, text="Today's Report: " + date1, font=('Calibri Bold', 16), fg="dark blue", bg="Light Blue").place(x=20, y=380)

             p1 = key.replace('{', " ")
             p1 = p1.replace('}', " ")

             tk.Label(gui, text=p1, font=('Calibri Bold', 14), fg="Black", bg="Light Blue").place(x=20, y=yy)
             tk.Label(gui, text=value, font=('Calibri', 14), fg="Black", bg="Light Blue").place(x=220, y=yy)
             yy = yy+30
    except:
        tk.Label(gui, text="Today's Data Upload is in Progress\nPlease Try After Sometime", font=('Calibri Bold', 15), fg="red", bg="Light Blue").place(x=20, y=450)

    yy = 430
    for key, value in data[state_code]['total'].items():
         tk.Label(gui, text="Cumulative Till Date", font=('Calibri Bold', 16), fg="dark blue", bg="Light Blue").place(x=350, y=380)

         p1 = key.replace('{', " ")
         p1 = p1.replace('}', " ")

         if p1 == "confirmed":
             cnf = value
         if p1 == "deceased":
             dead = value
         if p1 == "recovered":
             rec = value

         tk.Label(gui, text=p1, font=('Calibri Bold', 14), fg="Black", bg="Light Blue").place(x=350, y=yy)
         tk.Label(gui, text=value, font=('Calibri', 14), fg="Black", bg="Light Blue").place(x=550, y=yy)
         yy = yy+30

    active = cnf-dead-rec
    rec_rate = (rec/cnf)*100
    tk.Label(gui, text="Active Caseload: " + str(active), font=('Calibri Bold', 20), fg="Red", bg="Light Blue").place(x=20, y=660)
    tk.Label(gui, text="Recovery Rate  : " + str(round(rec_rate,1)) + " %", font=('Calibri Bold', 20), fg="Dark Green", bg="Light Blue").place(x=20, y=700)
    tk.Label(gui, text="Population: " + str(state_pop), font=('Calibri Bold', 20), fg="brown", bg="Light Blue").place(x=350, y=660)
    tk.Label(gui, text="Vaccination: ", font=('Calibri Bold', 20), fg="Dark Green", bg="Light Blue").place(x=350, y=700)
    tk.Label(gui, text="Dose 1: " + str(round(state_v1_p,1)) + " %" + "\nDose 2:   " + str(round(state_v2_p,1)) + " %", font=('Calibri Bold', 14), fg="Dark Green", bg="Light Blue").place(x=520, y=695)

def home():

    global data
    response = requests.get("https://api.covid19india.org/v4/min/data.min.json", verify=False)
    data = response.json()
    # key1 = list(data.keys())
    # key1.remove('TT')

    india_cnf = data['TT']["total"]["confirmed"]
    india_rec = data['TT']["total"]["recovered"]
    india_dead = data['TT']["total"]["deceased"]
    india_oth = data['TT']["total"]["other"]
    india_active = india_cnf-india_rec-india_dead-india_oth
    v1 = data['TT']["total"]["vaccinated1"]
    v2 = data['TT']["total"]["vaccinated2"]
    dat = data['TT']["meta"]["date"]
    pop = data['TT']["meta"]["population"]

    pv1 = (v1/pop)*100
    pv2 = (v2/pop)*100

    try:
        india_cnf_today = data['TT']["delta"]["confirmed"]
        india_dead_today = data['TT']["delta"]["deceased"]
        india_rec_today = data['TT']["delta"]["recovered"]
        india_active_today = india_cnf_today-india_dead_today-india_rec_today
    except:
        india_cnf_today = 0
        india_dead_today = 0
        india_rec_today = 0
        india_active_today = 0

    global s
    s = ttk.Style()
    s.configure('Red.TLabelframe.Label', font=('Arial Bold', 16), foreground ='Dark Blue')

    lf1 = ttk.LabelFrame(gui, text = "Choose State and District", style = "Red.TLabelframe")
    lf1.place(x=10, y=100)
    Frame(lf1, width=1346, height=210, background = 'Light Blue').pack()

    lf2 = ttk.LabelFrame(gui, text = "State Data", style = "Red.TLabelframe")
    lf2.place(x=10, y=350)
    Frame(lf2, width=670, height=380, background = 'Light Blue').pack()

    lf3 = ttk.LabelFrame(gui, text = "District Data", style = "Red.TLabelframe")
    lf3.place(x=690, y=350)
    Frame(lf3, width=670, height=380, background = 'Light Blue').pack()

    tk.Label(gui, text="Select State: ", font=('Calibri Bold', 16), fg="Black", bg="Light Blue").place(x=380, y=150)

    states_list = ["Andaman & Nicobar Islands", "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chandigarh", "Chattisgarh", "Dadra & Nagar Haveli \ Daman & Diu",
              "Delhi", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jammu & Kashmir", "Jharkhand", "Karnataka", "Kerala", "Ladakh", "Lakshadweep", "Madhya Pradesh",
              "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Puducherry", "Punjab", "Rajasthan", "Sikkim",
              "Tamil Nadu", "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal"]

    selected_state = tk.StringVar(gui)

    cb1 = ttk.Combobox(gui, textvariable=selected_state, width=35, height=20, values=states_list, font=('Halvetica', 12))
    cb1.place(x=550, y=155)
    cb1.current(0)

    tk.Label(gui, text="Last Updated:\n" + str(dat), font=('Calibri Bold', 16), fg="brown", bg="Light Blue").place(x=150, y=150)
    tk.Label(gui, text="Population:\n" + str(pop), font=('Calibri Bold', 16), fg="brown", bg="Light Blue").place(x=1140, y=150)

    tk.Label(gui, text="Confirmed: " + str(india_cnf), font=('Calibri Bold', 16), fg="brown", bg="Light Blue").place(x=20, y=250)
    tk.Label(gui, text="Active   : " + str(india_active), font=('Calibri Bold', 16), fg="dark blue", bg="Light Blue").place(x=300, y=250)
    tk.Label(gui, text="Recovery: " + str(india_rec), font=('Calibri Bold', 16), fg="dark green", bg="Light Blue").place(x=550, y=250)
    tk.Label(gui, text="Deceased : " + str(india_dead), font=('Calibri Bold', 16), fg="red", bg="Light Blue").place(x=820, y=250)
    tk.Label(gui, text="Vaccine  : " + str(v1+v2), font=('Calibri Bold', 16), fg="green", bg="Light Blue").place(x=1070, y=250)

    tk.Label(gui, text=str(india_cnf_today), font=('Calibri Bold', 12), fg="brown", bg="Light Blue").place(x=100, y=280)
    tk.Label(gui, text=str(india_active_today), font=('Calibri Bold', 12), fg="dark blue", bg="Light Blue").place(x=350, y=280)
    tk.Label(gui, text=str(india_rec_today), font=('Calibri Bold', 12), fg="dark green", bg="Light Blue").place(x=620, y=280)
    tk.Label(gui, text=str(india_dead_today), font=('Calibri Bold', 12), fg="red", bg="Light Blue").place(x=900, y=280)
    tk.Label(gui, text="Dose 1: " + str(v1) + " (" + str(round(pv1, 1)) + " %)", font=('Calibri Bold', 12), fg="green", bg="Light Blue").place(x=1070, y=280)
    tk.Label(gui, text="Dose 2: " + str(v2) + " (" + str(round(pv2, 1)) + " %)", font=('Calibri Bold', 12), fg="green", bg="Light Blue").place(x=1070, y=305)

    tk.Button(gui, text = "Submit", command = lambda: select_district(selected_state), font=('Calibri Bold', 12), fg="white", bg="Dark Blue", width = 10).place(x=950, y=150)
    tk.Button(gui, text = "Refresh", command = lambda: home(), font=('Calibri Bold', 12), fg="white", bg="Dark Blue").place(x=1250, y=50)
    response.close()

global gui
gui = tk.Tk()
gui.title("COVID-19 INDIA")
gui.geometry("1366x768")
gui.resizable(0,0)
gui.configure(background='Light Blue')
tk.Label(gui, text="COVID-19 DASHBOARD", font=('Arial Bold', 54), fg="dark blue", bg="Light Blue").place(x=300, y=1)
home()
gui.mainloop()


T = int(input())
for i in range(T):
    n = int(input())
    a = [int(x) for x in input().split(' ')]
    res = set()
    index = list()
    for j in range(len(a)):
        before = len(res)
        res.add(a[j])
        after = len(res)
        if before == after:
            for k in range(len(a)):
                if a[k] == a[j]:
                    index.append(k+1)
                    break
    if len(index) == 0:
        print(-1)
    else:
        print(min(index))


from collections import OrderedDict

from cppbind import default_config
from cppbind.common.error import Error
from cppbind.common.yaml_process import to_value
from cppbind.context_manager.var_eval import VariableEvaluator
from cppbind.ir.ast import (
    Node,
    RootNode,
    ROOT_KIND_NAME,
    DIR_KIND_NAME,
    FILE_KIND_NAME
)
from cppbind.parser.cppbind_api_parser import APIParser
from cppbind.utils import init_jinja_env

ALL_PLATFORMS = sorted(list(default_config.platforms))

class ContextManager:
    """
    A class for evaluating current context variables
    using current context to assign the result to the current node.
    """

    def __init__(self, ctx_desc, platform, language):
        self.ctx_desc = ctx_desc
        self.platform = platform
        self.language = language
        jinja_env = init_jinja_env(language)
        self.cppbind_api_parser = APIParser(ctx_desc, jinja_env, platform, language)
        self.var_evaluator = VariableEvaluator(jinja_env)

    def eval_root_attrs(self, ctx, var_values, location=None):
        """Eval context variables for root node"""
        args = None
        api = Node.API_NONE

        # update context with var values to use them during evaluation
        ctx.update(var_values)

        parsed_api = self.cppbind_api_parser.parse_yaml_api(RootNode.ROOT_KEY, ctx)
        if parsed_api:
            api, args = parsed_api

        args = args or {}
        # overwrite parsed variables with command line values (it has higher priority)
        args.update(var_values)

        return api, self.__process_attrs(ROOT_KIND_NAME, args, location, ctx)

    def eval_dir_attrs(self, name, ctx, location=None):
        """Eval context variables for dir node"""
        api = args = None
        parsed_api = self.cppbind_api_parser.parse_yaml_api(name, ctx)
        if parsed_api:
            api, args = parsed_api
        return api, self.__process_attrs(DIR_KIND_NAME, args, location, ctx)

    def eval_file_attrs(self, name, ctx, location=None):
        """Eval context variables for file node"""
        parsed_api = self.cppbind_api_parser.parse_yaml_api(name, ctx)
        if parsed_api:
            api, args = parsed_api
            if api:
                return api, self.__process_attrs(FILE_KIND_NAME, args, location, ctx)
        return None

    def eval_clang_attrs(self, name, kind, api_section, ctx, location):
        """Eval context variables for clang node"""
        parsed_api = self.cppbind_api_parser.parse_api(name, api_section, location, ctx)
        if parsed_api:
            api, args = parsed_api
            if api:
                return api, self.__process_attrs(kind, args, location, ctx)
        return None

    def __process_attrs(self, kind, args, location, ctx=None):
        """
        Evaluate/calculate current context variables values by its' kind and current context.
        """
        ctx = ctx or OrderedDict()
        args = args or OrderedDict()
        res = OrderedDict()

        # dummy object for identifying undefined and null value defined variables
        undefined = object()

        # add all missing attributes
        for att_name, properties in self.ctx_desc.get_var_def().items():
            new_att_val = args.get(att_name, undefined)

            allowed = kind in properties["allowed_on"]
            if new_att_val is undefined:
                # check mandatory attribute existence
                if kind in properties["required_on"]:
                    Error.error(f"Attribute '{att_name}' is mandatory attribute on {kind}.",
                                location.file_name if location else None,
                                location.line_number if location else None)
                    break

                # inherit from parent or add default value
                if properties.get('inheritable'):
                    # directory based nodes may not have parent
                    if ctx:
                        new_att_val = ctx.get(att_name, undefined)

                if allowed:
                    if new_att_val is undefined:
                        # use default value
                        new_att_val = ContextManager.get_attr_default_value(
                            properties, self.platform, self.language, undefined)

                        if new_att_val is not undefined:
                            new_att_val = self.var_evaluator.eval_var_value(properties,
                                                                            new_att_val,
                                                                            ctx,
                                                                            att_name,
                                                                            location)
            else:
                # attribute is set check weather or not it is allowed.
                if not allowed:
                    Error.error(f"Attribute {att_name} is not allowed on {kind}.",
                                location.file_name if location else None,
                                location.line_number if location else None)
                    break

                new_att_val = self.var_evaluator.eval_var_value(properties,
                                                                new_att_val,
                                                                ctx,
                                                                att_name,
                                                                location)

            # validate variable values
            if new_att_val not in (None, undefined):
                self.cppbind_api_parser.validate_attr(att_name, new_att_val)

            options = to_value(ContextManager.get_var_property_value(properties, self.platform, self.language, 'options'))

            if new_att_val not in (None, undefined) and options is not None:
                if new_att_val not in options:
                    Error.error(f"Value mismatch for '{att_name}' variable: "
                                f"value {new_att_val} is not in list of allowed options",
                                location.file_name if location else None,
                                location.line_number if location else None)

            if new_att_val is not undefined:
                # add attr to current node context so that it can be used for coming attributes
                ctx[att_name] = new_att_val
                res[att_name] = new_att_val

        return res

    @staticmethod
    def get_attr_default_value(props, plat, lang, default=None):
        return ContextManager.get_var_property_value(props, plat, lang, 'default', default)

    @staticmethod
    def get_var_property_value(props, plat, lang, prop, default=None):
        """
        Retrieve language/platform specific default value for current variable.
        """

        # detect illegal specification of plat/lang option
        if plat + f'.{prop}' in props and lang + f'.{prop}' in props:
            Error.critical(
                f"Conflict of attributes in attributes definition file: {plat}.default and {lang}.default: "
                f"only one of them must be defined separately, or they must be both specified")

        # if plat/lang specific key is preset, return corresponding section
        # we search for specific key by descending order of priority
        for key in (plat + '.' + lang + f'.{prop}', plat + f'.{prop}', lang + f'.{prop}', prop):
            if key in props:
                return props[key]

        return default

    def filter_by_plat_lang(self, var_values):
        """
        Filter current platform/language specific values from initial context provided via command line arguments
        """
        res = {}

        if var_values is None:
            return res

        # convert argparse.Namespace into dict be able to lookup and iterate over it
        var_values = var_values.__dict__

        # pick those variable names which are present in variable definitions
        var_def = self.ctx_desc.get_var_def()
        var_names = set(name.split('.')[-1] for name in var_values if name in var_def)

        for name in var_names:
            prop = var_def[name]
            if 'cmd_line' not in prop['allowed_on']:
                continue

            plat_lang_opt = f"{self.platform}.{self.language}.{name}"
            plat_opt = f"{self.platform}.{name}"
            lang_opt = f"{self.language}.{name}"

            # search for value from highest to lowest priority (plat+lang+name, plat+name, lang+name, name)
            for opt in (plat_lang_opt, plat_opt, lang_opt, name):
                if opt in var_values and var_values[opt] is not None:
                    res[name] = var_values[opt]
                    # no need for later searching since we already found an option with the highest possible priority
                    break

        return res


import random
import numpy as np
import scipy
from scipy import ndimage
from PIL import Image, ImageEnhance, ImageOps
from tensorflow.python.keras.backend import image_data_format

# utility function for global contrast normalization
def normalize(train, test):
	# truncate rgb to 0-1
	train = train / 255.0
	test = test / 255.0

	# zero centering and std normalization
	mean = np.mean(train, axis=0)
	std = np.std(train, axis=0)
	epsilon = 1e-7 # avoid dividing by zero

	train = (train - mean) / (std + epsilon)
	test = (test - mean) / (std + epsilon)

	return train, test

# zero component analysis whitening (normalize data first)
def zca_whitening(train, test):
	cov = np.cov(train, rowvar=False) # covariance matrix
	u, s, _ = np.linalg.svd(cov) # singular value decomposition
	epsilon = 0.1 # whitening coefficient

	# build zca matrix
	zca_matrix = u.dot(np.diag(1.0 / np.sqrt(s + epsilon))).dot(u.T)
	train = zca_matrix.dot(train.T).T
	test = zca_matrix.dot(test.T).T

	return train, test

# per pixel principal component analysis whitening (normalize data first)
# needs more testing
def per_pixel_pca(train, test):
	cov = np.cov(train, rowvar=False) # covariance matrix
	eval, evec = np.linalg.eigh(cov) # eigenvalues and -vectors
	idx = np.argsort(eval)[::-1] # reverse indices

	# sort and get the best 3 eigenvectors
	eval = eval[idx]
	evec = evec[:, :3]
	features = (evec).column_stack().matrix()

	# apply PCA
	train = evec.T.dot(train.T).T
	test = evec.T.dot(test.T).T

	# normal distribution parameters
	mu = 0
	sigma = 0.1

	# scale eigenvalues w/ randomized normal distribution
	se = np.zeros((3, 1))
	se[0][0] = np.random.normal(mu, sigma) * eval[0]
	se[1][0] = np.random.normal(mu, sigma) * eval[1]
	se[2][0] = np.random.normal(mu, sigma) * eval[2]
	val = features * se.matrix()

	# add magnitudes to principal component multiples
	train[...,0] += val[0]
	train[...,1] += val[1]
	train[...,2] += val[2]

	test[...,0] += val[0]
	test[...,1] += val[1]
	test[...,2] += val[2]

	return train, test

# cutout & random erasing preprocessing function for ImageDataGenerator
# implementation by Yusuke Uchida & Kosuke Takeuchi https://github.com/yu4u/cutout-random-erasing
def get_random_eraser(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255, pixel_level=False):
    def eraser(input_img):
        if input_img.ndim == 3:
            img_h, img_w, img_c = input_img.shape
        elif input_img.ndim == 2:
            img_h, img_w = input_img.shape

        p_1 = np.random.rand()

        if p_1 > p:
            return input_img

        while True:
            s = np.random.uniform(s_l, s_h) * img_h * img_w
            r = np.random.uniform(r_1, r_2)
            w = int(np.sqrt(s / r))
            h = int(np.sqrt(s * r))
            left = np.random.randint(0, img_w)
            top = np.random.randint(0, img_h)

            if left + w <= img_w and top + h <= img_h:
                break

        if pixel_level:
            if input_img.ndim == 3:
                c = np.random.uniform(v_l, v_h, (h, w, img_c))
            if input_img.ndim == 2:
                c = np.random.uniform(v_l, v_h, (h, w))
        else:
            c = np.random.uniform(v_l, v_h)

        input_img[top:top + h, left:left + w] = c

        return input_img

    return eraser

# cutmix augmentation ImageDataGenerator
# https://github.com/wakamezake/CutMix
class CutMixGenerator:
    def __init__(self, X_train, y_train, batch_size=32, alpha=0.2,
                 shuffle=True, data_gen=None):
        self.X_train = X_train
        self.y_train = y_train
        self.batch_size = batch_size
        self.alpha = alpha
        self.shuffle = shuffle
        self.sample_num = len(X_train)
        self.data_gen = data_gen

    def __call__(self):
        while True:
            indexes = self.__get_exploration_order()
            itr_num = int(len(indexes) // (self.batch_size * 2))

            for i in range(itr_num):
                batch_ids = indexes[i * self.batch_size * 2:(i + 1) * self.batch_size * 2]
                X, y = self.__data_generation(batch_ids)

                yield X, y

    def __get_exploration_order(self):
        indexes = np.arange(self.sample_num)

        if self.shuffle:
            np.random.shuffle(indexes)

        return indexes

    def __data_generation(self, batch_ids):
        _, h, w, c = self.X_train.shape
        _, class_num = self.y_train.shape
        batch_index = batch_ids[:self.batch_size]
        rand_index = np.random.permutation(batch_index)
        X1 = self.X_train[batch_index]
        X2 = self.X_train[rand_index]
        y1 = self.y_train[batch_index]
        y2 = self.y_train[rand_index]
        lam = np.random.beta(self.alpha, self.alpha)

        bx1, by1, bx2, by2 = get_rand_bbox(w, h, lam)
        X1[:, bx1:bx2, by1:by2, :] = X2[:, bx1:bx2, by1:by2, :]
        X = X1
        y = y1 * lam + y2 * (1 - lam)

        if self.data_gen:
            for i in range(self.batch_size):
                X[i] = self.data_gen.random_transform(X[i])

        return X, y

def is_channel_last(image):
    channel = image.shape[2]
    assert len(image.shape) == 3
    assert channel == 3 or channel == 1
    assert image_data_format() == "channels_last"

def get_rand_bbox(width, height, l):
    r_x = np.random.randint(width)
    r_y = np.random.randint(height)
    r_l = np.sqrt(1 - l)
    r_w = np.int(width * r_l)
    r_h = np.int(height * r_l)
    bb_x_1 = np.clip(r_x - r_w // 2, 0, width)
    bb_y_1 = np.clip(r_y - r_h // 2, 0, height)
    bb_x_2 = np.clip(r_x + r_w // 2, 0, width)
    bb_y_2 = np.clip(r_y + r_h // 2, 0, height)
    return bb_x_1, bb_y_1, bb_x_2, bb_y_2

# autoaugment ImageDataGenerator
# https://github.com/4uiiurz1/keras-auto-augment
class AutoAugmentGenerator:
    def __init__(self, args):
        self.datagen = ImageDataGenerator(width_shift_range=0.1, height_shift_range=0.1, fill_mode='constant', cval=0, horizontal_flip=True)

        self.means = np.array([0.4914009 , 0.48215896, 0.4465308])
        self.stds = np.array([0.24703279, 0.24348423, 0.26158753])

        self.args = args
        if args.auto_augment:
            self.policies = [
                ['Invert', 0.1, 7, 'Contrast', 0.2, 6],
                ['Rotate', 0.7, 2, 'TranslateX', 0.3, 9],
                ['Sharpness', 0.8, 1, 'Sharpness', 0.9, 3],
                ['ShearY', 0.5, 8, 'TranslateY', 0.7, 9],
                ['AutoContrast', 0.5, 8, 'Equalize', 0.9, 2],
                ['ShearY', 0.2, 7, 'Posterize', 0.3, 7],
                ['Color', 0.4, 3, 'Brightness', 0.6, 7],
                ['Sharpness', 0.3, 9, 'Brightness', 0.7, 9],
                ['Equalize', 0.6, 5, 'Equalize', 0.5, 1],
                ['Contrast', 0.6, 7, 'Sharpness', 0.6, 5],
                ['Color', 0.7, 7, 'TranslateX', 0.5, 8],
                ['Equalize', 0.3, 7, 'AutoContrast', 0.4, 8],
                ['TranslateY', 0.4, 3, 'Sharpness', 0.2, 6],
                ['Brightness', 0.9, 6, 'Color', 0.2, 8],
                ['Solarize', 0.5, 2, 'Invert', 0, 0.3],
                ['Equalize', 0.2, 0, 'AutoContrast', 0.6, 0],
                ['Equalize', 0.2, 8, 'Equalize', 0.6, 4],
                ['Color', 0.9, 9, 'Equalize', 0.6, 6],
                ['AutoContrast', 0.8, 4, 'Solarize', 0.2, 8],
                ['Brightness', 0.1, 3, 'Color', 0.7, 0],
                ['Solarize', 0.4, 5, 'AutoContrast', 0.9, 3],
                ['TranslateY', 0.9, 9, 'TranslateY', 0.7, 9],
                ['AutoContrast', 0.9, 2, 'Solarize', 0.8, 3],
                ['Equalize', 0.8, 8, 'Invert', 0.1, 3],
                ['TranslateY', 0.7, 9, 'AutoContrast', 0.9, 1],
            ]

    def flow(self, x, y=None, batch_size=32, shuffle=True, sample_weight=None,
             seed=None, save_to_dir=None, save_prefix='', save_format='png', subset=None):
        batches = self.datagen.flow(x, y, batch_size, shuffle, sample_weight,
                               seed, save_to_dir, save_prefix, save_format, subset)

        while True:
            x_batch, y_batch = next(batches)

            if self.args.cutout:
                for i in range(x_batch.shape[0]):
                    x_batch[i] = cutout(x_batch[i])

            if self.args.auto_augment:
                x_batch = x_batch.astype('uint8')
                for i in range(x_batch.shape[0]):
                    x_batch[i] = apply_policy(x_batch[i], self.policies[random.randrange(len(self.policies))])

            yield x_batch, y_batch

operations = {
    'ShearX': lambda img, magnitude: shear_x(img, magnitude),
    'ShearY': lambda img, magnitude: shear_y(img, magnitude),
    'TranslateX': lambda img, magnitude: translate_x(img, magnitude),
    'TranslateY': lambda img, magnitude: translate_y(img, magnitude),
    'Rotate': lambda img, magnitude: rotate(img, magnitude),
    'AutoContrast': lambda img, magnitude: auto_contrast(img, magnitude),
    'Invert': lambda img, magnitude: invert(img, magnitude),
    'Equalize': lambda img, magnitude: equalize(img, magnitude),
    'Solarize': lambda img, magnitude: solarize(img, magnitude),
    'Posterize': lambda img, magnitude: posterize(img, magnitude),
    'Contrast': lambda img, magnitude: contrast(img, magnitude),
    'Color': lambda img, magnitude: color(img, magnitude),
    'Brightness': lambda img, magnitude: brightness(img, magnitude),
    'Sharpness': lambda img, magnitude: sharpness(img, magnitude),
    'Cutout': lambda img, magnitude: cutout(img, magnitude),
}

def apply_policy(img, policy):
    if random.random() < policy[1]:
        img = operations[policy[0]](img, policy[2])
    if random.random() < policy[4]:
        img = operations[policy[3]](img, policy[5])

    return img

def transform_matrix_offset_center(matrix, x, y):
    o_x = float(x) / 2 + 0.5
    o_y = float(y) / 2 + 0.5
    offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])
    reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]])
    transform_matrix = offset_matrix @ matrix @ reset_matrix
    return transform_matrix

def shear_x(img, magnitude):
    magnitudes = np.linspace(-0.3, 0.3, 11)

    transform_matrix = np.array([[1, random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]), 0],
                                 [0, 1, 0],
                                 [0, 0, 1]])
    transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1])
    affine_matrix = transform_matrix[:2, :2]
    offset = transform_matrix[:2, 2]
    img = np.stack([ndimage.interpolation.affine_transform(
                    img[:, :, c],
                    affine_matrix,
                    offset) for c in range(img.shape[2])], axis=2)
    return img

def shear_y(img, magnitude):
    magnitudes = np.linspace(-0.3, 0.3, 11)

    transform_matrix = np.array([[1, 0, 0],
                                 [random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]), 1, 0],
                                 [0, 0, 1]])
    transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1])
    affine_matrix = transform_matrix[:2, :2]
    offset = transform_matrix[:2, 2]
    img = np.stack([ndimage.interpolation.affine_transform(
                    img[:, :, c],
                    affine_matrix,
                    offset) for c in range(img.shape[2])], axis=2)
    return img

def translate_x(img, magnitude):
    magnitudes = np.linspace(-150/331, 150/331, 11)

    transform_matrix = np.array([[1, 0, 0],
                                 [0, 1, img.shape[1]*random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])],
                                 [0, 0, 1]])
    transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1])
    affine_matrix = transform_matrix[:2, :2]
    offset = transform_matrix[:2, 2]
    img = np.stack([ndimage.interpolation.affine_transform(
                    img[:, :, c],
                    affine_matrix,
                    offset) for c in range(img.shape[2])], axis=2)
    return img

def translate_y(img, magnitude):
    magnitudes = np.linspace(-150/331, 150/331, 11)

    transform_matrix = np.array([[1, 0, img.shape[0]*random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])],
                                 [0, 1, 0],
                                 [0, 0, 1]])
    transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1])
    affine_matrix = transform_matrix[:2, :2]
    offset = transform_matrix[:2, 2]
    img = np.stack([ndimage.interpolation.affine_transform(
                    img[:, :, c],
                    affine_matrix,
                    offset) for c in range(img.shape[2])], axis=2)
    return img

def rotate(img, magnitude):
    magnitudes = np.linspace(-30, 30, 11)

    theta = np.deg2rad(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))
    transform_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
                                 [np.sin(theta), np.cos(theta), 0],
                                 [0, 0, 1]])
    transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1])
    affine_matrix = transform_matrix[:2, :2]
    offset = transform_matrix[:2, 2]
    img = np.stack([ndimage.interpolation.affine_transform(
                    img[:, :, c],
                    affine_matrix,
                    offset) for c in range(img.shape[2])], axis=2)
    return img

def auto_contrast(img, magnitude):
    img = Image.fromarray(img)
    img = ImageOps.autocontrast(img)
    img = np.array(img)
    return img

def invert(img, magnitude):
    img = Image.fromarray(img)
    img = ImageOps.invert(img)
    img = np.array(img)
    return img

def equalize(img, magnitude):
    img = Image.fromarray(img)
    img = ImageOps.equalize(img)
    img = np.array(img)
    return img

def solarize(img, magnitude):
    magnitudes = np.linspace(0, 256, 11)

    img = Image.fromarray(img)
    img = ImageOps.solarize(img, random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))
    img = np.array(img)
    return img

def posterize(img, magnitude):
    magnitudes = np.linspace(4, 8, 11)

    img = Image.fromarray(img)
    img = ImageOps.posterize(img, int(round(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))))
    img = np.array(img)
    return img

def contrast(img, magnitude):
    magnitudes = np.linspace(0.1, 1.9, 11)

    img = Image.fromarray(img)
    img = ImageEnhance.Contrast(img).enhance(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))
    img = np.array(img)
    return img

def color(img, magnitude):
    magnitudes = np.linspace(0.1, 1.9, 11)

    img = Image.fromarray(img)
    img = ImageEnhance.Color(img).enhance(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))
    img = np.array(img)
    return img

def brightness(img, magnitude):
    magnitudes = np.linspace(0.1, 1.9, 11)

    img = Image.fromarray(img)
    img = ImageEnhance.Brightness(img).enhance(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))
    img = np.array(img)
    return img

def sharpness(img, magnitude):
    magnitudes = np.linspace(0.1, 1.9, 11)

    img = Image.fromarray(img)
    img = ImageEnhance.Sharpness(img).enhance(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))
    img = np.array(img)
    return img

def cutout(org_img, magnitude=None):
    magnitudes = np.linspace(0, 60/331, 11)

    img = np.copy(org_img)
    mask_val = img.mean()

    if magnitude is None:
        mask_size = 16
    else:
        mask_size = int(round(img.shape[0]*random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])))
    top = np.random.randint(0 - mask_size//2, img.shape[0] - mask_size)
    left = np.random.randint(0 - mask_size//2, img.shape[1] - mask_size)
    bottom = top + mask_size
    right = left + mask_size

    if top < 0:
        top = 0
    if left < 0:
        left = 0

    img[top:bottom, left:right, :].fill(mask_val)

    return img


import json

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt

from .models import CustomUser, Image, Notification, Result

def index(request):
    """index."""
    return HttpResponse("Hello, world. You're at the polls index.")

def create_image(request):
    """Create image."""
    return None

def get_recommended_images(request):
    """Get recommended images."""
    images = Image.objects.filter(is_recommended=True)
    results = [{
        'id': image.pk,
        'url': image.url,
    } for image in images]
    return JsonResponse({'results': results})

def get_public_images(request):
    """Get public images."""
    images = Image.objects.filter(is_public=True, is_banned=False)
    results = [{
        'id': image.pk,
        'user_id': image.user.pk,
        'url': image.url,
    } for image in images]
    return JsonResponse({'results': results})

@csrf_exempt
def get_images(request, user_id):
    """Get images."""
    if request.method == 'GET':
        try:
            images = Image.objects.filter(user_id=user_id, is_deleted=False).order_by('-created_datetime')[:100]
            results = [{
                'id': image.pk,
                'user_id': image.user.pk,
                'url': image.url,
                'original_uri': image.original_uri,
                'created_datetime': image.created_datetime,
                'modified_datetime': image.modified_datetime,
            } for image in images]
            return JsonResponse({'results': results})
        except ValueError:
            return JsonResponse({'results': []})

    elif request.method == 'POST':
        data = json.loads(request.body.decode("utf-8"))
        image = Image.objects.create_analytics(
            url=data.get('url'),
            original_uri=data.get('original_uri'),
        )

        user, _ = CustomUser.objects.get_or_create(id=user_id, username=user_id)
        image.user = user
        image.save()
        image.analyze(save=True)
        image.sync_firebase()
        results = [{
            'id': image.pk,
            'user_id': image.user.pk,
            'url': image.url,
            'original_uri': image.original_uri,
        }]
        return JsonResponse({'results': results})

@csrf_exempt
def get_image(request, user_id, image_id):
    """Get image."""
    if request.method == 'GET':
        try:
            images = Image.objects.filter(user_id=user_id, id=image_id, is_deleted=False)
            results = [{
                'id': image.pk,
                'user_id': image.user.pk,
                'url': image.url,
                'original_uri': image.original_uri,
                'tags': list(image.tags.order_by('-score').values_list('name', flat=True)),
            } for image in images]
            return JsonResponse({'results': results})
        except ValueError:
            return JsonResponse({'results': []})
    elif request.method == 'DELETE':
        try:
            image = Image.objects.get(user_id=user_id, id=image_id, is_deleted=False)
            image.is_deleted = True
            image.save()
            return JsonResponse({'results': 'success'})
        except ValueError:
            return JsonResponse({'results': 'failure'})

@csrf_exempt
def get_notifications(request, user_id):
    """Get notifications."""
    if request.method == 'GET':
        try:
            notifications = Notification.objects \
                .filter(user_id=user_id, is_deleted=False) \
                .order_by('-created_datetime')[:100]
            results = [{
            } for notification in notifications]
            return JsonResponse({'results': results})
        except ValueError:
            return JsonResponse({'results': {}})

@csrf_exempt
def results_endpoint(request, user_id, image_id):
    """Get results."""
    if request.method == 'GET':
        try:
            image = Image.objects.get(user_id=user_id, is_deleted=False, id=image_id)
            return JsonResponse({'results': image.get_results()})
        except ValueError:
            return JsonResponse({'results': {}})

    elif request.method == 'POST':
        try:
            image = Image.objects.get(user_id=user_id, is_deleted=False, id=image_id)

            data = json.loads(request.body.decode("utf-8"))
            if data.get('payload'):
                Result.objects.create(
                    image_id=image_id,
                    category=Result.HUMAN,
                    name=data.get('payload', {}).get('type'),
                    feature=Result.CODE,
                    user_id=user_id,
                    payload=json.dumps(data.get('payload')),
                )
                image.sync_firebase()

            return JsonResponse({'results': image.get_results()})
        except ValueError:
            return JsonResponse({'results': {}})

        results = [{
            'id': image.pk,
            'user_id': image.user.pk,
            'url': image.url,
            'original_uri': image.original_uri,
        }]
        return JsonResponse({'results': results})


import turtle as t # Импортим черепаху
k = 30 # Значение масштаба
t.tracer(0) # skip
for i in range(7): # Создаем цикл по условию задания, где "7" - количество повторений
    t.forward(10*k) # Шагаем по условию задания, при этом делаем масштаб(*k)
    t.right(120) # Шагаем по условию задания
t.up() # Поднимаем черепаху с колен, для того чтоб проставить точки
for x in range(11): # Создаем цикл с кол-вом точек по ширине фигуры, ставьте в зависимости от вашей фигуры
    for y in range(10): # Создаем цикл с кол-вом точек по высоте фигуры
        turtle.goto(x*k, -y*k) # Делаем масштаб и указываем направление для точек
        turtle.dot(4) # Ставим точки
t.update() # skip update
t.done() # well done
# Далее просто считаем кол-во точек в фигуре и профитаем!!!


from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views

urlpatterns = [
    # django admin
    url(r'^django-admin/', admin.site.urls),
    # login / logout
    url(r'^login$', views.LoginView.as_view(template_name='login.html'), name='login'),
    url(r'^logout$', views.LogoutView.as_view(next_page='/'), name='logout'),
    # permissions managment
    url(r'^', include('permissions.urls')),
    # account managment
    url(r'^', include('accounts.urls')),
    # tracker
    url(r'^', include('tracker.urls')),
]


from collections import defaultdict

class IntcodeComputer:
    def __init__(self, intcode, silent=False,
                 feedback_mode=False, ascii_mode=False):
        self.intcode = defaultdict(int, {i: x for i, x in enumerate(intcode)})
        self.original_intcode = self.intcode.copy()
        self.silent = silent
        self.feedback_mode = feedback_mode
        self.ascii_mode = ascii_mode
        self.inputs = None
        self.pointer = 0
        self.relative_base = 0
        self.has_halted = False
        self.is_paused = False
        self.output = None
        self.get_position = (
            self.get_position_in_position_mode,
            self.get_position_in_immediate_mode,
            self.get_position_in_relative_mode
        )
        self.opcode_methods = {
            1: self.add,
            2: self.multiply,
            3: self.read,
            4: self.print_and_or_pause,
            5: self.jump_if_true,
            6: self.jump_if_false,
            7: self.less_than,
            8: self.equals,
            9: self.change_relative_base,
            99: self.halt
        }

    def reset(self):
        self.intcode = self.original_intcode.copy()
        self.pointer = 0
        self.relative_base = 0
        self.has_halted = False
        self.is_paused = False
        self.output = None

    def get_next_instruction(self):
        instruction = str(self.intcode[self.pointer])
        opcode = int(instruction[-2:])
        parameters = [int(i) for i in instruction[-3::-1]]
        return opcode, parameters

    def run(self, inputs=None):
        if inputs is not None:
            if self.ascii_mode:
                inputs = [ord(inp) for inp in inputs]
                ascii_newline = ord("\n")
                if inputs[-1] != ascii_newline:
                    inputs.append(ascii_newline)
            # Reverse input because popping from the end is better.
            self.inputs = list(reversed(inputs))
        self.output = None
        self.is_paused = False
        while not (self.has_halted or self.is_paused):
            opcode, parameters = self.get_next_instruction()
            self.opcode_methods[opcode](parameters)
        if self.ascii_mode and self.output is not None:
            if self.output <= 0x10ffff:  # max value for chr()
                self.output = chr(self.output)
            else:
                self.output = str(self.output)
        return self.output

    def run_ascii(self, instructions=None):
        # Catch all the output into one string.
        # This is a bit hacky with the try...except... but I can't be bothered
        # to figure out where the errors come from.
        # This will also remain a method separate from self.run().
        output = [self.run(instructions)]
        while not self.has_halted:
            try:
                output.append(self.run())
            except (AttributeError, IndexError):
                break
        return "".join(x for x in output if x is not None)

    def get_positions(self, parameters, n):
        parameters += [0] * (n - len(parameters))
        return [self.get_position[param](pos)
                for pos, param in enumerate(parameters)]

    def get_position_in_position_mode(self, position):
        return self.intcode[self.pointer + position + 1]

    def get_position_in_immediate_mode(self, position):
        return self.pointer + position + 1

    def get_position_in_relative_mode(self, position):
        return self.intcode[self.pointer + position + 1] + self.relative_base

    def add(self, parameters):
        a, b, target = self.get_positions(parameters, 3)
        self.intcode[target] = self.intcode[a] + self.intcode[b]
        self.pointer += 4

    def multiply(self, parameters):
        a, b, target = self.get_positions(parameters, 3)
        self.intcode[target] = self.intcode[a] * self.intcode[b]
        self.pointer += 4

    def read(self, parameters):
        position = self.get_positions(parameters, 1)[0]
        self.intcode[position] = self.inputs.pop()
        self.pointer += 2

    def print_and_or_pause(self, parameters):
        position = self.get_positions(parameters, 1)[0]
        self.output = self.intcode[position]
        if not self.silent:
            print(self.output)
        if self.feedback_mode:
            self.is_paused = True
        self.pointer += 2

    def jump_if_true(self, parameters):
        position, target = self.get_positions(parameters, 2)
        if self.intcode[position]:
            self.pointer = self.intcode[target]
        else:
            self.pointer += 3

    def jump_if_false(self, parameters):
        position, target = self.get_positions(parameters, 2)
        if self.intcode[position] == 0:
            self.pointer = self.intcode[target]
        else:
            self.pointer += 3

    def less_than(self, parameters):
        a, b, target = self.get_positions(parameters, 3)
        self.intcode[target] = int(self.intcode[a] < self.intcode[b])
        self.pointer += 4

    def equals(self, parameters):
        a, b, target = self.get_positions(parameters, 3)
        self.intcode[target] = int(self.intcode[a] == self.intcode[b])
        self.pointer += 4

    def change_relative_base(self, parameters):
        position = self.get_positions(parameters, 1)[0]
        self.relative_base += self.intcode[position]
        self.pointer += 2

    def halt(self, parameters):
        self.has_halted = True


# -*- coding: utf-8 -*-
"""Tests for pyneric.meta"""

import inspect
from unittest import TestCase

from future.utils import with_metaclass

import pyneric

class MetadataBehaviourTestCase(TestCase):

    def test_invalid_metadata_attr(self):
        self.assertRaises(TypeError, pyneric.MetadataBehaviour,
                          metadata_attr=object())

    def test_invalid_propagate_attr(self):
        self.assertRaises(TypeError, pyneric.MetadataBehaviour,
                          propagate_attr=object())

    def test_invalid_base_override_attr(self):
        self.assertRaises(TypeError, pyneric.MetadataBehaviour,
                          base_override_attr=object())

    def test_invalid_storage_attr(self):
        self.assertRaises(TypeError, pyneric.MetadataBehaviour,
                          storage_attr=object())

    def test_invalid_storage_class(self):
        self.assertRaises(TypeError, pyneric.MetadataBehaviour,
                          storage_class=object())

class MetaclassTestCase(TestCase):

    def test_basic(self):
        a_value = object()
        class M(pyneric.Metaclass):
            __metadata__ = dict(a=a_value)
        class C(with_metaclass(M, object)):
            pass
        self.assertTrue(inspect.isdatadescriptor(M.a))
        expected = dict(a=a_value, __propagate__=set(), __base_overrides__={})
        self.assertEqual(expected, M._get_metadata())
        self.assertEqual(expected, C._get_metadata())
        self.assertEqual(a_value, C.a)
        obj = C()
        self.assertRaises(AttributeError, getattr, obj, 'a')
        new_value = object()
        self.assertRaises(AttributeError, setattr, C, 'a', new_value)
        # Test that a non-propagated metadata attribute is not affected by an
        # object's own attribute of the same name.
        obj.a = new_value
        self.assertEqual(new_value, obj.a)
        self.assertEqual(a_value, C.a)

    def test_basic_metadata_iterable(self):
        a_value = object()
        class M(pyneric.Metaclass):
            __metadata__ = ('a',)
            a = a_value
        class C(with_metaclass(M, object)):
            pass
        self.assertTrue(inspect.isdatadescriptor(M.a))
        expected = dict(a=a_value, __propagate__=set(), __base_overrides__={})
        self.assertEqual(expected, M._get_metadata())
        self.assertEqual(expected, C._get_metadata())
        self.assertEqual(a_value, C.a)
        obj = C()
        self.assertRaises(AttributeError, getattr, obj, 'a')
        new_value = object()
        self.assertRaises(AttributeError, setattr, C, 'a', new_value)
        # Test that a non-propagated metadata attribute is not affected by an
        # object's own attribute of the same name.
        obj.a = new_value
        self.assertEqual(new_value, obj.a)
        self.assertEqual(a_value, C.a)

    def test_validation(self):
        a_value = dict()
        class CustomException(Exception):
            """Exception for validation test"""
        class M(pyneric.Metaclass):
            __metadata__ = dict(a=a_value)
            @staticmethod
            def validate_a(value):
                if not isinstance(value, dict):
                    raise CustomException("must be a dict")
        class C(with_metaclass(M, object)):
            a = {'valid': 'dict'}
        self.assertRaises(CustomException, type, 'C',
                          (with_metaclass(M, object),),
                          dict(a={'invalid', 'set', 'not', 'a', 'dict'}))
        self.assertRaises(CustomException, type, 'C1', (C,),
                          dict(a={'invalid', 'set', 'not', 'a', 'dict'}))

    def test_validate_not_callable(self):
        a_value = dict()
        v_value = object()
        class M(pyneric.Metaclass):
            __metadata__ = dict(a=a_value)
            # The "validate_a" attribute is not a function, so "a" metadata is
            # not validated.
            validate_a = v_value
        class C(with_metaclass(M, object)):
            a = {'valid': 'dict'}
        # The value of "a" is not being validated, so it can be a set.
        class C1(with_metaclass(M, object)):
            a = {'set', 'not', 'a', 'dict'}
        class C2(C):
            a = {'set', 'not', 'a', 'dict'}

    def test_valid(self):
        a_value = object()
        b_value = object()
        c_value = object()
        d_value = object()
        class M(pyneric.Metaclass):
            __metadata__ = dict(a=None, b=None, c=c_value)
            __propagate__ = ('a', 'c')
            @property
            def c(cls):
                if hasattr(cls, 'x'):
                    return "different value"
                return cls._get_metadata('c')
        class C(with_metaclass(M, object)):
            a = a_value
            d = d_value
        self.assertTrue(inspect.isdatadescriptor(M.a))
        self.assertTrue(inspect.isdatadescriptor(M.b))
        self.assertTrue(inspect.isdatadescriptor(M.c))
        self.assertRaises(AttributeError, getattr, M, 'd')
        expected = dict(a=None, b=None, c=c_value, __propagate__={'a', 'c'},
                        __base_overrides__={})
        self.assertEqual(expected, M._get_metadata())
        expected.update(a=a_value)
        self.assertEqual(expected, C._get_metadata())
        self.assertEqual(a_value, C.a)
        self.assertIsNone(C.b)
        self.assertEqual(c_value, C.c)
        self.assertEqual(d_value, C.d)
        obj = C()
        self.assertEqual(a_value, obj.a)
        self.assertRaises(AttributeError, getattr, obj, 'b')
        self.assertEqual(c_value, obj.c)
        self.assertEqual(d_value, obj.d)
        obj.b = b_value
        new_value = object()
        self.assertRaises(AttributeError, setattr, C, 'a', new_value)
        self.assertRaises(AttributeError, setattr, C, 'b', new_value)
        self.assertRaises(AttributeError, setattr, C, 'c', new_value)
        C.d = new_value
        self.assertEqual(new_value, C.d)
        self.assertEqual(a_value, obj.a)
        self.assertEqual(b_value, obj.b)
        self.assertEqual(c_value, obj.c)
        self.assertEqual(new_value, obj.d)
        self.assertRaises(AttributeError, setattr, obj, 'a', new_value)
        obj.b = new_value
        self.assertRaises(AttributeError, setattr, obj, 'c', new_value)
        newer_value = object()
        obj.d = newer_value
        self.assertEqual(new_value, obj.b)
        self.assertEqual(newer_value, obj.d)
        self.assertEqual(c_value, C.c)
        C.x = None
        self.assertEqual('different value', C.c)

    def test_invalid_metadata_attribute(self):
        class M(pyneric.Metaclass):
            pass
        self.assertRaises(AttributeError, M._get_metadata, 'x')

    def test_invalid_metadata(self):
        self.assertRaises(TypeError, type, 'M', (pyneric.Metaclass,),
                          dict(__metadata__=object()))

class MetaclassCustomBehaviourTestCase(TestCase):

    def test_no_propagate_attr(self):
        behaviour = pyneric.MetadataBehaviour(propagate_attr=None)
        a_value = object()
        b_value = dict(a=None)
        p_value = {'a'}
        class M(pyneric.Metaclass):
            __metadata_behaviour__ = behaviour
            __metadata__ = dict(a=a_value)
            # Prove that __propagate__ is not part of metadata behaviour.
            __propagate__ = p_value
            # Prove that base overrides are not affected.
            __base_overrides__ = b_value
        class C(with_metaclass(M, object)):
            pass
        self.assertTrue(inspect.isdatadescriptor(M.a))
        # Note that there is no "__propagate__" attribute in the metadata.
        expected = dict(a=a_value, __base_overrides__=b_value)
        self.assertEqual(expected, M._get_metadata())
        expected.update(a=None)
        self.assertEqual(expected, C._get_metadata())
        # Prove that __propagate__ is not part of metadata behaviour.
        self.assertEqual(p_value, M.__propagate__)
        self.assertEqual(p_value, C.__propagate__)
        # Prove that base overrides are not affected.
        self.assertEqual(None, C.a)
        # Prove that propagation of "a" does not occur.
        self.assertRaises(AttributeError, getattr, C(), 'a')

    def test_no_base_override_attr(self):
        behaviour = pyneric.MetadataBehaviour(base_override_attr=None)
        a_value = object()
        b_value = dict(a=None)
        p_value = {'a'}
        class M(pyneric.Metaclass):
            __metadata_behaviour__ = behaviour
            __metadata__ = dict(a=a_value)
            # Prove that propagation is not affected.
            __propagate__ = p_value
            # Prove that __base_overrides__ is not part of metadata behaviour.
            __base_overrides__ = b_value
        class C(with_metaclass(M, object)):
            pass
        self.assertTrue(inspect.isdatadescriptor(M.a))
        # Note that there is no "__base_overrides__" attribute in the metadata.
        expected = dict(a=a_value, __propagate__=p_value)
        self.assertEqual(expected, M._get_metadata())
        self.assertEqual(expected, C._get_metadata())
        # Prove that __base_overrides__ is not part of metadata behaviour.
        self.assertEqual(b_value, M.__base_overrides__)
        self.assertEqual(b_value, C.__base_overrides__)
        # Prove that "a" was not overridden.
        self.assertEqual(a_value, C.a)
        # Prove that propagation is not affected.
        self.assertEqual(a_value, C().a)

    def test_validation_disabled(self):
        behaviour = pyneric.MetadataBehaviour(validate_prefix=None)
        a_value = dict()
        class M(pyneric.Metaclass):
            __metadata_behaviour__ = behaviour
            __metadata__ = dict(a=a_value)
            @staticmethod
            def validate_a(value):
                if not isinstance(value, dict):
                    raise TypeError("must be a dict")
        class C(with_metaclass(M, object)):
            a = {'valid': 'dict'}
        # The value of "a" is not being validated, so it can be a set.
        class C1(with_metaclass(M, object)):
            a = {'set', 'not', 'a', 'dict'}
        class C2(C):
            a = {'set', 'not', 'a', 'dict'}

    def test_validation_with_transformation(self):
        behaviour = pyneric.MetadataBehaviour(validate_transforms=True)
        a_value = dict()
        class CustomException(Exception):
            """Exception for validation test"""
        class M(pyneric.Metaclass):
            __metadata_behaviour__ = behaviour
            __metadata__ = dict(a=a_value)
            @staticmethod
            def validate_a(value):
                if not isinstance(value, dict):
                    raise CustomException("must be a dict")
                return list(value)
        class C(with_metaclass(M, object)):
            a = {'valid': 'dict'}
        self.assertEqual(['valid'], C.a)
        # still also raises exception when appropriate
        self.assertRaises(CustomException, type, 'C',
                          (with_metaclass(M, object),),
                          dict(a={'invalid', 'set', 'not', 'a', 'dict'}))
        self.assertRaises(CustomException, type, 'C1', (C,),
                          dict(a={'invalid', 'set', 'not', 'a', 'dict'}))
        class C1(C):
            a = {'another': 4, 'one': 1, 'transformed': 0}
        self.assertIsInstance(C1.a, list)
        self.assertEqual({'another', 'one', 'transformed'}, set(C1.a))

    def test_metadata_behaviour_similar_to_django_model(self):
        class CustomMetadataBehaviour(pyneric.MetadataBehaviour):
            def __init__(self, storage_class, metadata_attr='Meta',
                         storage_attr='_meta', propagate_attr=None):
                super(CustomMetadataBehaviour, self).__init__(
                    metadata_attr=metadata_attr,
                    propagate_attr=propagate_attr,
                    storage_attr=storage_attr,
                    storage_class=storage_class)
            def _get_local_metadata(self, dict, base_attrs=()):
                """Django-like metadata retrieval function."""
                try:
                    meta_class = dict[self.metadata_attr]
                except KeyError:
                    return {}
                # Django does not currently test that it is a class.
                if not inspect.isclass(meta_class):
                    raise TypeError(
                        "The '{}' attribute must be a class."
                        .format(self.metadata_attr))
                result = {}
                for k, v in meta_class.__dict__.items():
                    if (k.startswith('_') and
                        k not in (self.propagate_attr,
                                  self.base_override_attr)):
                        continue
                    result[k] = v
                return result
        class MetadataStorage(object):
            def __init__(self, **kwargs):
                for attr, value in kwargs.items():
                    setattr(self, attr, value)
        class M(pyneric.Metaclass):
            __metadata_behaviour__ = CustomMetadataBehaviour(MetadataStorage)
            class Meta:
                app_label = None
                db_table = None
                abstract = False
                __base_overrides__ = dict(abstract=False)
        class C(with_metaclass(M, object)):
            class Meta:
                db_table = 'tbl'
                abstract = True
        class C1(C):
            class Meta:
                db_table = 'tbl1'
        self.assertEqual('tbl', C.db_table)
        self.assertEqual(True, C.abstract)
        self.assertEqual('tbl1', C1.db_table)
        self.assertEqual(False, C1.abstract)


def bwt(s, sa):
    """Given string s returns BWT(s), using suffix array"""
    bw = []
    for idx in sa:
        if idx == 0:
            bw.append("$")
        else:
            bw.append(s[idx - 1])
    return "".join(bw)


import boto3, botocore

from b2flow.python.tools.config import get, logger

class Driver:
    def __init__(self, bucket_name: str = get('B2FLOW__PYTHON__TOOLS__BUCKET'),
                 endpoint_url: str = get('B2FLOW__PYTHON__TOOLS__HOSTNAME')):

        self.bucket_name = bucket_name
        session = boto3.session.Session(aws_access_key_id='identity', aws_secret_access_key='credential')
        config = boto3.session.Config(s3={'addressing_style': 'path'})
        self.client = session.client('s3', endpoint_url=endpoint_url, config=config)
        self.resource = session.resource('s3', endpoint_url=endpoint_url, config=config)

        try:
            self.client.create_bucket(Bucket=bucket_name)
        except botocore.exceptions.ClientError:
            pass

    def write(self, body: bytes, filepath: str):
        self.client.put_object(Bucket=self.bucket_name, Body=body, Key=filepath)
        logger.info("write", self.bucket_name, filepath, f"{len(body)}bytes")

    def read(self, filepath: str):
        obj = self.client.get_object(Bucket=self.bucket_name, Key=filepath)
        body = obj['Body'].read()
        logger.info("read", self.bucket_name, filepath, f"{len(body)}bytes")
        return body

    def list(self, prefix: str = ""):
        objects = self.client.list_objects(Bucket=self.bucket_name, Prefix=prefix).get("Contents") or []
        logger.info("list", self.bucket_name, prefix, f"{len(objects)} objects")
        return objects


def numop7():
    num=int(input())
    numb = bin(num)[2:]
    for i in range(0,len(numb)):
        if(numb[i]=='0'):
            numb=numb[0:i]+'1'+numb[i+1:]
        else:
            numb=numb[0:i]+'0'+numb[i+1:]
    res=int('0b'+numb,2)
    print(res)
    return

numop7()


import math
import random
def moduloExp(nValue, nValue2, notExceed ):
    number, exponent, residue =nValue, nValue2, 1
    while(exponent > 1):
        if(exponent % 2 == 0 and exponent > 1):
            exponent=exponent//2
            number=(number * number) % notExceed

        if(exponent % 2 == 1 and exponent > 1):
            residue=(residue * number) % notExceed
            exponent-=1
            number=(number * number) % notExceed
            exponent=exponent//2

    return (number * residue) % notExceed

def avarage(password):
    sum=0
    appended=[]
    for char in password:
        value=ord(char)
        appended.append(value)
        sum+=value

    return (sum//len(password))

def pascalValue(password):
    nValue=len(password)
    rValue=nValue
    sum=0
    for value in password:
        numerator=(math.factorial(nValue))
        denominator=(math.factorial(nValue - rValue)) * (math.factorial(rValue))
        comb=numerator//denominator
        modulo=(ord(value) * comb) % 61
        rValue-=1
        sum+=modulo
    return sum % 61

def getRandomPoint(prevCord, grad, modulo):
    xCord=(prevCord[0]**2) + (prevCord[1]**2) + (10 * prevCord[0]) + (12 * prevCord[1])
    xCord=(xCord % 22) - (modulo//2)
    yCord=((grad * xCord) - ((grad * prevCord[0]) - prevCord[1]))
    yCord=(yCord % 22) - (modulo//2)+1
    xyCord=[xCord, yCord]
    return  xyCord

def getGeneratorPoint(password, modulo):
    x=avarage(password) % modulo
    y=pascalValue(password) % modulo
    prevCord=[x,y]
    for char in password:
        grad=ord(char)
        newCord=getRandomPoint(prevCord, grad, modulo)
        prevCord[0], prevCord[1] = newCord[0], newCord[1]

    return prevCord

def get_char(input_number ):
    characters=["1", "2", "3", "4", "5", "6", "7", "8", "9",
                "A", "B", "C", "D", "E", "F", "G", "H", "J",
                "K", "L", "M", "N", "P", "Q", "R", "S", "T",
                "U", "V", "W", "X", "Y", "Z", "a", "b", "c",
                "d", "e", "f", "g", "h", "i", "j", "k", "m",
                "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z",
               ]
    charValue= input_number % 58
    return characters[charValue]

def get_index(char ):
    characters=["1", "2", "3", "4", "5", "6", "7", "8", "9",
                "A", "B", "C", "D", "E", "F", "G", "H", "J",
                "K", "L", "M", "N", "P", "Q", "R", "S", "T",
                "U", "V", "W", "X", "Y", "Z", "a", "b", "c",
                "d", "e", "f", "g", "h", "i", "j", "k", "m",
                "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z",
               ]

    if(char in characters):
        for index in range(58):
            indexChar=characters[index]
            if(indexChar==char):
                return index
    return None

def getTerm(nthTerm):
    return (2**nthTerm) -1

print(getTerm(17))

print(moduloExp(2, 30, 31))

def getValue(point, center):
    a, b = center[0], center[1]
    x, y =point[0], point[1]
    return ((x-a)**3) + ((y - b)**3)

def getPointCount(radius, center):
    count=0
    a, b = center[0], center[1]
    for x in range(-radius+a, radius+1+a):
        for y in range(-radius + b, radius + 1 + b):
            point=[x, y]
            pointValue=getValue(point, center)
            if(pointValue <= radius):
                count+=1

    return count

def egcd(a, b):
    if a== 0:
        return (b, 0, 1)
    else:
        g, y, x=egcd(b%a, a)
        return (g, x-(b//a)*y, y)

def getInverseModulo(a, n):
    lm, hm=1, 0
    low, high= a% n, n
    while low > 1:
        ratio=high//low
        nm, new = hm -lm * ratio, high - low * ratio
        lm, low, hm, high = nm, new, lm, low

    return lm % n

def getNewGradient(radius, center, point, modulo):
    sign=0
    numerator=(radius**2) - (center[0]**2 + center[1]**2) - (2 * (point[0] - center[0]))
    denominator=2 * (point[1] - center[1])
    if(numerator < 0):
        sign+=1
    if(denominator < 0):
        sign+=1
    gradient=(numerator * getInverseModulo(denominator, modulo)) % modulo
    if(sign == 1):
        gradient==gradient - modulo
    return gradient

def getGradient(radius, center, prevPoint, modulo):
    prevX, prevY=prevPoint[0], prevPoint[1]
    centerX, centerY=center[0], center[1]

    upper=((radius**2) - ((centerX**2) + (centerY**2)) -(2 * (prevX -centerX))) % modulo
    lower=(2 * (prevY - centerY)) % modulo
    gradient=(upper * getInverseModulo(lower, modulo)) % modulo
    return gradient

def getNewPoint(prevPoint, gradient, center, modulo):
    prevX, prevY=prevPoint[0], prevPoint[1]
    centerX, centerY=center[0], center[1]
    newX=((gradient**2 - prevX) % modulo)-(prevX % modulo)
    newY=((gradient**2 - prevY)  % modulo)-(prevY % modulo)
    return [newX, newY]

def getHash(password):
    prevPoint=[3, 47]
    modulo=2017
    string=" "
    radius=1
    center=[5, 3]
    length=64

    for number in range(length):
        gradient=getGradient(radius, center, prevPoint, modulo)
        newPoint=getNewPoint(prevPoint, gradient, center, modulo)
        value=getValue(newPoint, center) % 61
        radius+=value
        string+=get_char(value)
        prevPoint=newPoint
    return string

def getTurningPoint(gradient, point, center, radius, modulo):
    beta=(-gradient * point[0]) + point[1]
    aValue=(1 + (gradient**2)) % modulo
    if(gradient < 0):
        aValue = aValue - modulo
    bValue=(2 * ((gradient * beta) - center[0]- (center[1]) * gradient))
    if(bValue < 0):
        bValue=bValue % modulo - modulo
    else:
        bValue=bValue % modulo
    cValue=((beta**2) + (2 * center[1] * beta) + (center[0]**2) + (center[1]**2))
    if(cValue < 0):
        cValue=cValue % modulo - modulo
    else:
        cValue=cValue % modulo
    #print(gradient,"    ",[aValue, bValue, cValue])
    xValue=((-bValue) * (getInverseModulo((2 * aValue), modulo))) % modulo
    yValue=(((4 * (aValue) * cValue) - (bValue**2)) * (getInverseModulo((4 * aValue), modulo))) % modulo
    return [(xValue % modulo) - (point[0] % modulo), (yValue % modulo) - (point[1] % modulo)]

def getPoint(center, point1, point2, radius, modulo):
    g1, g2=getNewGradient(radius, center, point1, modulo), getNewGradient(radius, point1, point2, modulo)
    numerator=((g2 * point2[0]) -(g1 * point1[0])) - (point2[1] - point1[1])
    denominator=getInverseModulo((g2 - g1), modulo)
    xValue=(numerator * denominator) % modulo
    y2Value=((g2 * (xValue - point2[0])) + point2[1]) % modulo
    y1Value=((g1 * (xValue - point1[0])) + point1[1]) % modulo
    yValue=(y2Value)
    return [(xValue-point2[0])%modulo, (yValue - point2[1])%modulo]

def getHashString(point, center, modulo):
    string=" "
    radius=1
    for value in range(64):
        gradient=getNewGradient(radius, center, point, modulo)
        newPoint=getTurningPoint(gradient, point, center, radius, modulo)
        newRadius=getValue(newPoint, center) % modulo
        newRadius-=((newPoint[0] - point[0])**2) + ((newPoint[1] - point[1])**2)
        string+=get_char(newRadius % 61)

        #print(str(value).ljust(10), str(newPoint).ljust(15), str(newRadius).ljust(10))
        radius=(newRadius) % modulo
        center=point
        point=newPoint
    return string

def getNthPoint(point, center, modulo, number):
    radius=modulo
    for value in range(number):
        gradient=getNewGradient(radius, center, point, modulo)
        newPoint=getTurningPoint(gradient, point, center, radius, modulo)
        newRadius=getValue(newPoint, center) % modulo
        newRadius-=((newPoint[0] - point[0])**2) + ((newPoint[1] - point[1])**2)
        radius=(newRadius) % modulo
        center=point
        point=newPoint

    return point

def getNormalGradient(point, newPoint, modulo):
    dy=newPoint[1] - point[1]
    dx=newPoint[0] -point[0]
    gradient=(dy) * (getInverseModulo(dx, modulo))
    return gradient % modulo

def getAbsent(set):
    list=[]
    for number in range(58):
        if not(number in set):
            list.append(number)
    return list

def getMixing(list1, list2):
    string=""
    for number in list2:
        string+=get_char(list1[number])

    return string

def getCycString(xyIndex, center, radius, modulus, cStart, cEnd, yRange):
    cycString=""; mappedString=""; combString=""
    mappedCount=[]
    for index in range(cStart, cEnd):
        point=[index, xyIndex]
        if(yRange == False):
            point[0], point[1] = xyIndex, index
        gradient=getNewGradient(radius, center, point, modulo)
        newPoint=getTurningPoint(gradient, point, center, radius, modulo)
        value1=getValue(point, center)
        value2=getValue(newPoint, center)
        value3=getValue([value1,value2], newPoint)
        char1=get_char(value1)
        char2=get_char(value2)
        char3=get_char(value3)
        if(char1 == "3"):
            mappedCount.append(char3)

        cycString+=char1
        mappedString+=char2
        combString+=char3

    return [cycString, mappedString, combString, mappedCount]

def getCycStringModified(xyPoint, center, radius, modulus, count, yRange):
    cycString=""; mappedString=""; combString=""
    x, y = xyPoint[0], xyPoint[1]
    mappedCount=[]
    if(yRange == True):
        for index in range(x + radius, x + radius + count):
            point=[index, y]
            gradient=getNewGradient(radius, center, point, modulo)
            newPoint=getTurningPoint(gradient, point, center, radius, modulo)
            value1=getValue(point, center)
            value2=getValue(newPoint, center)
            value3=getValue([value1,value2], newPoint)
            char1=get_char(value1)
            char2=get_char(value2)
            char3=get_char(value3)
            if(char1 == "3"):
                mappedCount.append(char3)

            cycString+=char1
            mappedString+=char2
            combString+=char3
    if(yRange == False):
        for index in range(y*29, y*29 + count):
            point=[x, index]
            gradient=getNewGradient(radius, center, point, modulo)
            newPoint=getTurningPoint(gradient, point, center, radius, modulo)
            value1=getValue(point, center)
            value2=getValue(newPoint, center)
            value3=getValue([value1,value2], newPoint)
            char1=get_char(value1)
            char2=get_char(value2)
            char3=get_char(value3)
            if(char1 == "3"):
                mappedCount.append(char3)

            cycString+=char1
            mappedString+=char2
            combString+=char3

    return [cycString, mappedString, combString, mappedCount]

def appendZero(value, modulus):
    vLen=len(str(value)); modLen=len(str(modulus))
    zero=""
    for int in range(modLen - vLen):
        zero+="0"

    return zero + str(value)

def printAll(center, radius, modulo, count, pointRange, det):
    unique=[]
    prev=0
    mappedTo=[]
    if(det == 1 or det == 3):
        for yIndex in range(pointRange):
            cyc=getCycString(yIndex, center, radius, modulo, 0, count, True)
            unique.append(cyc[2])
            index=get_index(cyc[2][len(cyc) - 1])
            deff=index - prev
            print(str([yIndex+1, "X"]).rjust(15),"  ",str(cyc[0]).rjust(12) , str(index).rjust(4), str(deff%58).rjust(4))
            print(str(((yIndex+1) % modulo)).rjust(15),"  ",str(cyc[1]).rjust(12), str(len(set(cyc[1]))).rjust(4))
            print(str((yIndex+1) % 29).rjust(15),"  ",str(cyc[2]).rjust(12), str(len(set(cyc[2]))).rjust(4))
            pointName=appendZero(yIndex, modulo)+"X"+appendZero(center[0], modulo)+appendZero(center[1], modulo)
            pointName+=appendZero(radius, modulo)+str(modulo)
            print(pointName)
            if(len(cyc[3]) > 0):
                mappedTo.append(get_index(cyc[3][0]))
            print("    ")
            prev=index
    if(det == 2 or det == 3):
        for xIndex in range(pointRange):
            cyc=getCycString(xIndex, center, radius, modulo, 0, count, False)
            unique.append(cyc[2])
            index=get_index(cyc[2][len(cyc) - 4])
            deff=index - prev
            print(str([(xIndex+1), "Y"]).rjust(15),"  ",str(cyc[0]).rjust(12) , str(index).rjust(4), str(deff%58).rjust(4))
            print(str((xIndex + 1) % modulo).rjust(15),"  ",str(cyc[1]).rjust(12), str(len(set(cyc[1]))).rjust(4))
            print(str((xIndex+1) % 29).rjust(15),"  ",str(cyc[2]).rjust(12), str(len(set(cyc[2]))).rjust(4))
            pointName=appendZero(xIndex, modulo)+"Y"+appendZero(center[0], modulo)+appendZero(center[1], modulo)
            pointName+=appendZero(radius, modulo)+str(modulo)
            print(pointName)
            if(len(cyc[3]) > 0):
                mappedTo.append(get_index(cyc[3][0]))
            print(" ")
            prev=index
    return unique

def getSetOperation(stringA, stringB):
    union=set(stringA) | set(stringB)
    intersect=set(stringA) & set(stringB)
    Adeff=set(stringA) - set(stringB)
    Bdeff=set(stringB) - set(stringA)
    symDeff=set(stringA) ^ set(stringB)
    return[union, intersect, Adeff, Bdeff, symDeff]

def getPointString(xyValue, center, radius, prime, isX):
    cyc=getCycString(xyValue, center, radius, modulo, 0, 58, isX)
    return cyc

def getPeriod(matchString, xyIndex, center, radius, modulus, upTo, yRange):
    for start in range(5, upTo):
        if(yRange==True):
            cyc=getCycString(xyIndex, center, radius, modulus, start, start+1, yRange)
            if(cyc[2] == matchString[0]):
                interval=len(matchString)
                cyc2=getCycString(xyIndex, center, radius, modulus, start, start+interval, yRange)
                if(cyc2[2] == matchString):
                    return start
        if(yRange == False):
            interval=len(matchString)
            cyc=getCycString(start, center, radius, modulus, 0, interval, yRange)
            if(cyc[2] == matchString):
                return start

def base58(message):
    string=""; remList=[]
    m=message.encode(encoding='utf_8', errors='strict')
    binaryList=bytearray(m)
    messageArray=""
    for element in binaryList:
        binzero="00000000"
        bins=bin(element)[2:]
        length=len(bins)
        array=binzero[:8 - length] + bins
        messageArray+=array

    mult, reminder = int(messageArray, 2), 0
    while(mult > 0):
        reminder=mult % 58
        mult=mult//58
        remList.append(reminder)
    for intValue in range(len(remList)):
        value=remList[len(remList) -1 - intValue]
        string+=get_char(value)
    return string

def getPointBase58(point):
    padding="100000000000000000000000000000000000000000000000000000000000000000000000000000000"
    pointX, pointY = bin(point[0])[2:], bin(point[1])[2:]
    lenPointX, lenPointY = len(pointX), len(pointY)
    paddedPointX=padding[:80-lenPointX] + pointX
    paddedPointY=padding[:80-lenPointY] + pointY
    pointXY="1" + paddedPointX + paddedPointY
    remList=[]; string=""
    mult, reminder = int(pointXY, 2), 0
    while(mult > 0):
        reminder=mult % 58
        mult=mult//58
        remList.append(reminder)
    for intValue in range(len(remList)):
        value=remList[len(remList) -1 - intValue]
        string+=get_char(value)
    return string

def numberBase58(value):
    remList=[]; string=""
    mult, reminder = value, 0
    while(mult > 0):
        reminder=mult % 58
        mult=mult//58
        remList.append(reminder)
    for intValue in range(len(remList)):
        value=remList[len(remList) -1 - intValue]
        string+=get_char(value)
    return string

def encrypMessage(base58, key):
    """
    key is a list contain the following in order
    xyValue---depend on boolean specification(true=x, false=y)
    center--center coordinates of a cycle
    prime & radius---prime and radius are the same, only one value needed
    boolean---for xyValue specification
    """
    mLength=len(str(base58))
    xyValue, center, prime= key[0], key[1], key[2]
    encryptedMessage=""
    x_cyc=getCycString(xyValue[0], center, prime, prime, 0, mLength, False)
    y_cyc=getCycString(xyValue[1], center, prime, prime, 0, mLength, True)
    y_eKey=y_cyc[2]; x_eKey=x_cyc[2]
    for index in range(mLength):
        mChar=base58[index]
        x_kChar, y_kChar = x_eKey[index], y_eKey[index]
        xy_kChar=get_index(x_kChar) + get_index(y_kChar)
        sum=get_index(mChar) + xy_kChar
        mkChar=get_char(sum)
        #print([x_kChar, y_kChar],"----->", [get_char(xy_kChar)],"----->",[mkChar])
        encryptedMessage+=mkChar
    return encryptedMessage

def decrypMessage(base58, key):
    """
    key is a list contain the following in order
    xyValue---depend on boolean specification(true=x, false=y)
    center--center coordinates of a cycle
    prime & radius---prime and radius are the same, only one value needed
    boolean---for xyValue specification
    """
    mLength=len(str(base58))
    xyValue, center, prime= key[0], key[1], key[2]
    encryptedMessage=""
    x_cyc=getCycString(xyValue[0], center, prime, prime, 0, mLength, False)
    y_cyc=getCycString(xyValue[1], center, prime, prime, 0, mLength, True)
    y_eKey=y_cyc[2]; x_eKey=x_cyc[2]
    for index in range(mLength):
        mChar=base58[index]
        x_kChar, y_kChar = x_eKey[index], y_eKey[index]
        xy_kChar=get_index(x_kChar) + get_index(y_kChar)
        sum=get_index(mChar) - (get_index(x_kChar) + get_index(y_kChar))
        mkChar=get_char(sum)
        #print([x_kChar, y_kChar],"----->", [get_char(xy_kChar)],"----->",[mkChar])
        encryptedMessage+=mkChar
    return encryptedMessage

def getCombString(point, center, modulo, start, length):
    x_cyc=getCycString(point[0], center, modulo, modulo, start, start+length, 0)
    y_cyc=getCycString(point[1], center, modulo, modulo, start, start+length, 1)
    xyString=""
    for index in range(length):
        xChar, yChar=x_cyc[2][index], y_cyc[2][index]
        xValue, yValue = get_index(xChar), get_index(yChar)
        xyValue=(xValue + yValue) +index
        xyChar=get_char(xyValue)
        xyString+=xyChar
    return xyString
difference=[]
def getCombStringKey(keyOne, keyTwo):
    combKey=""
    for index in range(len(keyOne)):
        val1=get_index(keyOne[index])
        val2=get_index(keyTwo[index])
        valInv1=getInverseModulo(val1, 61)
        valInv2=getInverseModulo(val2, 61)
        difference.append((valInv1 + valInv2 - val1) % 58)
        combKey+=get_char(valInv1 + valInv2 + index)
    return combKey

def getStringInv(string):
    newString=""
    for index in range(len(string)):
        inValue=get_index(string[index])
        newString+=get_char(58 - inValue)
    return newString

def getStringSum(string):
    sum=0
    for index in range(len(string)):
        indexValue=get_index(string[index])
        sum+=indexValue
    return sum

def getDestCoordinate(string, modulo):
    x, y = 0, 0
    for index in range(len(string)):
        indexValue=get_index(string[index])
        direction=indexValue % 4
        if(direction == 0):
            y+=indexValue
        if(direction == 1):
            y-=indexValue
        if(direction == 2):
            x+=indexValue
        if(direction == 3):
            x-=indexValue
    return [x % modulo,y % modulo]

center=[32124587,21123546]
modulo=9294554271129007931
radius=modulo

message="mama anakula ugali na nyama ya kuku"
print(ord("a"))
messageBase58=base58(message)
print(messageBase58)
print("   ")
b=bytearray(message.encode(encoding='utf_8', errors='strict'))
messageArray=""
for element in b:
    binzero="00000000"
    bins=bin(element)[2:]
    length=len(bins)
    array=binzero[:8 - length] + bins
    messageArray+=array
message.encode(encoding='utf_8', errors='strict')
messageBase58=base58(message)
key=[[3, 31], center, modulo]
key2=[[0, 12], center, modulo]
eMessage=encrypMessage(messageBase58, key)
print(messageBase58)
print(eMessage)
print(decrypMessage(eMessage, key2))

#point=[3, 3]
import hashlib as hash
modulo=989324828347146575663272
point=[23485975677, 46578364768]
center=[134222378689,342889765612]
repeat=modulo * 58
pointXY=getPointBase58(point)
centerXY=getPointBase58(center)
print(pointXY.ljust(35), centerXY.rjust(22))
key=getCombString(point, center, modulo, 0, 34)
print(key, "    ","P","  ", str(len(set(key)))+"   "+str(getStringSum(key)))
key2=getCombString(point, center, modulo, repeat//8, 34 )
print(key2, "    ","P","  ", str(len(set(key2)))+"   "+str(getStringSum(key2)))
print("    ")
pointHash=hash.sha256(pointXY.encode(encoding='utf_8', errors='strict')).hexdigest()
centerHash=hash.sha256(centerXY.encode(encoding='utf_8', errors='strict')).hexdigest()
print(pointHash)
print(centerHash)
print(numberBase58(int(pointHash, 16)))
print(numberBase58(int(centerHash, 16)))
print(" ")
print(getPointBase58([modulo-1, modulo-1]))
print(modulo**2)
print(58**28)
print(16**64)
print(58**58)