import os;
import sqlite3;
from sqlite3 import Error;
from shutil import copyfile
from datetime import datetime
from prettytable import PrettyTable

MONTHS = {'JAN': '01', 'FEB': '02', 'MAR': '03', 'APR': '04', 'MAY': '05', 'JUN': '06', 'JUL': '07', 'AUG': '08', 'SEP' : '09', 'OCT': '10', 'NOV': '11', 'DEC': '12'}
LEVELS = {'INDI':'0', 'NAME':'1', 'SEX':'1', 'BIRT':'1', 'DEAT':'1', 'FAMC':'1', 'FAMS':'1', 'FAM':'0', 'MARR':'1', 'HUSB':'1', 'WIFE':'1', 'CHIL':'1', 'DIV':'1', 'DATE':'2', 'HEAD':'0', 'TRLR':'0', 'NOTE':'0'}
TAGS = LEVELS.keys()
EXTENSION = '.ged'

'''
#TARIK + OSCAR TEST STUFF
TEST_ID = True
TEST_HUSBAND_NAME = True
TEST_WIFE_NAME = True
TEST_HUSBAND_ID = True
TEST_WIFE_ID = True
TEST_MARRAGE_VALID = True
'''

def file():
    geds = []
    for file in os.listdir(os.path.dirname(os.path.realpath(__file__))):
        if file.endswith(EXTENSION):
            geds.append(file)
    if(len(geds) <= 1):
        if(len(geds) == 0):
            print("NO FILE FOUND: Place "+EXTENSION+" in same folder as python script.")
        return geds[0]
    else:
        print("Files in Local Directory: ")
        for file in geds:
            print("- " + file)
        print('\n')
        while(True):
            name = input("Enter desired GEDCOM file name: ")
            if not EXTENSION in name:
                name += EXTENSION
            if name in geds:
                return name
            print("FILE NAME NOT FOUND, TRY AGAIN.\n")

def read(file):
    gedcom = open(file,'r')
    output = open(file.replace(EXTENSION, '.txt'),'w')
    for line in gedcom:
        id = None
        output.write("--> " + line.rstrip() + "\n")
        data = line.split(' ')
        level = data[0].rstrip()

        if ('INDI' or 'FAM') in line:
            id = data[1].rstrip()
            tag = data[2].rstrip()
            arguments = line.replace((level+ " " + id + " " + tag), 'id').rstrip()
        else:
            tag = data[1].rstrip()
            arguments = line.replace((level + " " + tag + " "), '').rstrip()

        if tag in TAGS and LEVELS[tag] == level:
            valid = 'Y'
        else:
            valid = 'N'

        str = "<-- " + level + "|" + tag + "|" + valid + "|" + arguments + "\n"

        output.write(str)
        print(str.rstrip())

    gedcom.close()
    output.close()
    return output

def tables(database):
    conn = sqlite3.connect(database)
    cursor = conn.cursor()

    print("\nGedcom Data - Individuals:\n")

    table = PrettyTable(["ID", "Name", "Gender", "Birthday", "Age", "Alive", "Death", "Child", "Spouse"])
    cursor.execute('SELECT * from Individuals')
    row = cursor.fetchone()
    while row is not None:
        table.add_row(row)
        row = cursor.fetchone()

    print(table)
    print("\nGedcom Data - Families:\n")

    table = PrettyTable(['ID', 'Married', 'Divorced', 'Husband_ID', 'Husband_Name', 'Wife_ID', 'Wife_Name', 'Children'])
    cursor.execute('SELECT * from Families')
    row = cursor.fetchone()
    while row is not None:
        table.add_row(row)
        row = cursor.fetchone()

    print(table)
    cursor.close()

def database(gedcom, database):
    file = open(gedcom,'r')
    lastLevel = 0
    familyTime, Divorced, Alive = False, False, True
    id, Name, Gender, Birthday, Age, Death, Child, Spouse, ID, Married, Husband_ID, Husband_Name, Wife_ID, Children, Wife_Name, dateType = ('None',)*16

    try:
        os.remove(os.getcwd()+'/'+database)
    except:
        pass

    if not os.path.exists(database):
        copyfile(os.getcwd()+"/template.sqlite3", os.getcwd()+'/'+database)

    for line in file:
        data = line.split(' ')
        level = data[0].rstrip()

        if (level == "0" and lastLevel == "1" and Gender != 'None' and familyTime == False):
            if Alive == False:
                Age = int(Death[2]) - int(Birthday[2])
            elif (Birthday != 'None'):
                Age = datetime.now().year - int(Birthday[2])
            db = sqlite3.connect(database)
            cursor = db.cursor()
            cursor.execute('''INSERT INTO Individuals(Name,Gender,Birthday,Age,Alive,Death,Child,Spouse,ID)
                  VALUES(?,?,?,?,?,?,?,?,?);''', (str(Name), str(Gender), str(Birthday), str(Age), str(Alive), str(Death), str(Child), str(Spouse), str(id)))
            db.commit()
            db.close()
            Alive = True
            Birthday, Death, Child = ('None',)*3

        if (level == "0") and ('FAM') in line:
            familyTime = True

        if (not familyTime):
#         #this is for individuals only, must make different one for fam
            if ('INDI') in line:
                id = data[1].rstrip().replace('@', '')
            if ('FAMS') in line:
                Spouse = data[2].rstrip().replace('@', '')
            if ('FAMC') in line:
                if (Child == 'None'):
                    Child = data[2].rstrip().replace('@', '')
                else:
                    Child = Child + data[2].rstrip().replace('@', '')
            if ('NAME') in line:
                Name = data[2:]
                if (len(data[2:]) > 1):
                    Name = [Name[0]] + [Name[1].rstrip('/').rstrip('/\n').replace('/', ' ')]
            if ('SEX') in line:
                Gender = data[2].rstrip('\n')
            if dateType == 'BIRT':
                Birthday = data[2:]
                Birthday = Birthday[:2] + [Birthday[2].rstrip('\n')]
                dateType = 'None'
            if dateType == 'DEAT':
                Death = data[2:]
                Death = Death[:2] + [Death[2].rstrip('\n')]
                Alive = False
                dateType = 'None'
            if ('BIRT') in line:
                dateType = 'BIRT'
            if ('DEAT') in line:
                dateType = 'DEAT'
            lastLevel = level

        if (familyTime):
            if (level == "0" and lastLevel == "1" and (Husband_ID != 'None' or Wife_ID != 'None')):
                db = sqlite3.connect(database)
                cursor = db.cursor()
                cursor.execute("SELECT Name FROM Individuals WHERE ID = '"+Wife_ID+"'")
                Wife_Name = cursor.fetchone()[0]
                cursor.execute("SELECT Name FROM Individuals WHERE ID = '"+Husband_ID+"'")
                Husband_Name = cursor.fetchone()[0]
                cursor.execute('''INSERT INTO Families(ID,Married,Divorced,Husband_ID,Husband_Name,Wife_ID,Wife_Name,Children)
                      VALUES(?,?,?,?,?,?,?,?);''', (str(ID), str(Married), str(Divorced), str(Husband_ID), str(Husband_Name), str(Wife_ID), str(Wife_Name), str(Children)))
                db.commit()
                db.close()
                Divorced = False;
                ID, Married, Husband_ID, Husband_Name, Wife_ID, Wife_Name, Children = ('None',)*7
            if ('FAM') in line:
                ID = data[1].rstrip().replace('@', '')
            if ('HUSB') in line:
                Husband_ID = data[2].rstrip().replace('@', '')
                Husband_Name = 'TEMP'
            if ('WIFE') in line:
                Wife_ID = data[2].rstrip().replace('@', '')
                Wife_Name = 'TEMP'
            if ('CHIL') in line:
                if (Children == 'None'):
                    Children = [data[2].rstrip().replace('@', '')]
                else:
                    Children += [data[2].rstrip().replace('@', '')]
            if dateType == 'MARR':
                Married = data[2:]
                Married = Married[:2] + [Married[2].rstrip('\n')]
                dateType = 'None'
            if ('MARR') in line:
                dateType = 'MARR'
            if ('DIV') in line:
                Divorced = True

'''
            #TARIK TEST STUFF
            #Sets are unique, if the len of the set ID isn't the same as len of list ID, not all are unique
            if len(id) > len(set(id)):
                TEST_ID = False
            if len(Husband_Name) > len(set(Husband_Name)):
                TEST_HUSBAND_NAME = False
            if len(Wife_Name) > len(set(Wife_Name)):
                TEST_WIFE_NAME = False
            if len(Husband_ID) > len(set(Husband_ID)):
                TEST_HUSBAND_ID = False
            if len(Wife_ID) > len(set(Wife_ID)):
                TEST_Wife_ID = False
            #OSCAR TEST STUFF
            if Married != 'None':
                MarriedPeople = GetFromDB('individuals', '*', 'spouse', "!= [NULL]")
                Married_ID_Date = []
                for x in MarriedPeople:
                    Married_ID_Date = ([x[0],x[1]])
                    Gender = x[2]
                    if ((Gender == "M") | (GetFromDB('families', 'Married', 'Husband_ID', Married_ID_Date[0])[2] < Married_ID_Date[1])):
                        TEST_MARRAGE_VALID = False
                        break

                    if ((Gender == "F") | (GetFromDB('families', 'Married', 'Husband_ID', Married_ID_Date[0])[2] < Married_ID_Date[1])):
                        TEST_MARRAGE_VALID = False
                        break

#OSCAR TEST STUFF
def GetFromDB(table, column, thisData, condition):
    connection = sqlite3.connect('database.sqlite3')
    cursor = connection.cursor()
    cursor.execute('SELECT '+ column +' from ' + table + ' where' + thisData + + condition )
    row = cursor.fetchone()
    data = []
    while row is not None:
        data.append(row)
        row = cursor.fetchone()
    return data

#TARIK TESTING STUFF
def TAGS_SIZE(TAGS):
    return len(TAGS) == 17
def LEVELS_SIZE(LEVELS):
    return len(LEVELS) == 17
def uniqueID():
    return TEST_ID
def uniqueHusbandID():
    return TEST_HUSBAND_ID
def uniqueWifeID():
    return TEST_WIFE_ID
def uniqueHusbandName():
    return TEST_HUSBAND_NAME
def uniqueWifeName():
    return TEST_WIFE_NAME
'''

'''
def us06(divorce_date, husband_death, wife_death):
    "Marriage should occur before death of either spouse"
    if not divorce_date or not (husband_death, wife_death):
        return False
'''
import ast

def us02(db, marriage_date, individual_ID): #Oscar
    "Birth should occur before marriage of an individual"
    if not marriage_date:
        return False
    query = queryDict(db, "Individuals", individual_ID, "Birthday")['Birthday']
    if(query == "None"):
        return False
    query = ''.join(c for c in query if c not in " (){}<>[]''")
    query = query.split(',')
    ib = datetime(int(query[2]), int(MONTHS[query[1]]), int(query[0]))
    md = datetime(int(marriage_date[2]), int(MONTHS[marriage_date[1]]), int(marriage_date[0]))
    return md < ib

def us10(marriage_date, husband_birth, wife_birth): #Oscar
    """Marriage should be at least 14 years after birth of both spouses
       (parents must be at least 14 years old)"""
    if not marriage_date:
        return False
    test = True
    md = datetime(int(marriage_date[2]) - 14, int(MONTHS[marriage_date[1]]), int(marriage_date[0]))
    if(husband_birth):
        hb = datetime(int(husband_birth[2]), int(MONTHS[husband_birth[1]]), int(husband_birth[0]))
        test *= hb < md
    if(wife_birth):
        wb = datetime(int(wife_birth[2]), int(MONTHS[wife_birth[1]]), int(wife_birth[0]))
        test *= wb < md
    return test

def us09_test(file):
    return null

def us09(mother_death, father_death, child_birth): #AUSTIN
    ''' Child born after mother deaths and before 9 months of fathers death'''
    if not child_birth or not (mother_death and father_death):
        return False
    cb = datetime(int(child_birth[2]), int(MONTHS[child_birth[1]]), int(child_birth[0]))
    md = datetime(int(mother_death[2]), int(MONTHS[mother_death[1]]), int(mother_death[0]))
    fd = datetime(int(father_death[2]), int(MONTHS[father_death[1]]), int(father_death[0]))
    if(father_death and not mother_death):
        return ((fd.year - cb.year) * 12 + fd.month - cb.month) >= 9
    elif(mother_death and not father_death):
        return md > cb
    return md > cb and ((fd.year - cb.year) * 12 + fd.month - cb.month) >= 9

#NOT FINISHED
def us21(gender, spose_gender): #AUSTIN
    ''' Husband is male, wife is female '''
    return (gender.upper()+spose_gender.upper()) in {'MF', 'FM'};

def queryDict(db, table, id, tag):
    con = sqlite3.connect(db)
    con.row_factory = lambda c, r: dict(zip([col[0] for col in c.description], r))
    cur = con.cursor()
    cur.execute("SELECT "+tag+" FROM "+table+" WHERE ID = '"+id+"'")
    return cur.fetchone()

if __name__ == '__main__':
    ged = file()
    db = ged.replace(EXTENSION, '.sqlite3')
    database(ged, db)
    tables(db)


import json
import psycopg2
from utilities.conn_util_sm import get_conn_string

def lambdaHandler(event, context):

    sql_1 = {
        'text': 'select * from public.get_students()',
        'params': ()
    }

    sql_2 = {
        'text': 'select * from public.get_a_student(%s)',
        'params': (1,)
    }

    sql = sql_2

    rows = []
    try:
        conn_str = get_conn_string(
            'rds-postgres-example', 'experiment')

        conn = psycopg2.connect(conn_str)
        cur = conn.cursor()
        cur.execute(sql.get('text'), sql.get('params'))

        rows = cur.fetchall()
        cur.close()

    except:
        get_conn_string.cache_clear()
        raise

    finally:
        if conn is not None:
            conn.close()

    print(rows)

    return {
        'statusCode': 200,
        'body': json.dumps(rows)
    }


from collections import namedtuple
from typing import Dict, Tuple, List, Any, Callable
from overrides import overrides
from parser.utils.utils_conllu import parse_line, DEFAULT_FIELDS, process_multiword_tokens
from conllu import parse_incr
from allennlp.common.file_utils import cached_path
import logging
from allennlp.data.tokenizers.word_splitter import SpacyWordSplitter

UD_Sentence = namedtuple(typename='UD_Sentence',
                      field_names=['ids', 'words', 'lemmas', 'upos_tags',
                                   'xpos_tags', 'feats', 'heads', 'rels',
                                   'multiword_ids', 'multiword_forms'],
                      defaults=[None]*10)

class UniversalDependenciesDatasetReader(object):
    def __init__(self):
        self.sentences = []
        self.ids = []
        self.ROOT = "<ROOT>"

    def load(self, file_path):
        # if `file_path` is a URL, redirect to the cache
        file_path = cached_path(file_path)
        counter = 1
        with open(file_path, 'r') as conllu_file:

            for annotation in parse_incr(conllu_file):
                # CoNLLU annotations sometimes add back in words that have been elided
                # in the original sentence; we remove these, as we're just predicting
                # dependencies for the original sentence.
                # We filter by None here as elided words have a non-integer word id,
                # and we replace these word ids with None in process_multiword_tokens.
                annotation = process_multiword_tokens(annotation)
                multiword_tokens = [x for x in annotation if x["multi_id"] is not None]
                annotation = [x for x in annotation if x["id"] is not None]

                if len(annotation) == 0:
                    continue

                def get_field(tag: str, map_fn: Callable[[Any], Any] = None) -> List[Any]:
                    map_fn = map_fn if map_fn is not None else lambda x: x
                    return [map_fn(x[tag]) if x[tag] is not None else "_" for x in annotation if tag in x]

                # Extract multiword token rows (not used for prediction, purely for evaluation)
                ids = [x["id"] for x in annotation]
                multiword_ids = [x["multi_id"] for x in multiword_tokens]
                multiword_forms = [x["form"] for x in multiword_tokens]

                words = get_field("form")
                lemmas = get_field("lemma")
                upos_tags = get_field("upostag")
                xpos_tags = get_field("xpostag")
                feats = get_field("feats", lambda x: "|".join(k + "=" + v for k, v in x.items())
                                                     if hasattr(x, "items") else "_")
                heads = get_field("head")
                dep_rels = get_field("deprel")
                sentence = UD_Sentence(ids,words,lemmas,upos_tags,xpos_tags,feats,heads, dep_rels,multiword_ids,multiword_forms)
                self.sentences.append(sentence)
                self.ids.append(counter)
                counter = counter + 1

    def __len__(self):
        return len(self.ids)

    def __getitem__(self, item):
        return self.sentences[item]

    @property
    def words(self):
        return [[self.ROOT] + list(sentence.words) for sentence in self.sentences]

    @property
    def tags(self):
        return [[self.ROOT] + list(sentence.upos_tags) for sentence in self.sentences]

    @property
    def heads(self):
        return [[0] + list(map(int, sentence.heads)) for sentence in self.sentences]

    @property
    def rels(self):
        return [[self.ROOT] + list(sentence.rels) for sentence in self.sentences]

    @heads.setter
    def heads(self, sequences):
        self.sentences = [sentence._replace(heads=sequence)
                          for sentence, sequence in zip(self.sentences, sequences)]

    @rels.setter
    def rels(self, sequences):
        self.sentences = [sentence._replace(rels=sequence)
                          for sentence, sequence in zip(self.sentences, sequences)]

    def save(self, fname):
        with open(fname, 'w') as f:
            for item in self.sentences:
                output = self.write(item)
                f.write(output)

    def write(self, outputs) :
        outputs = dict(outputs._asdict())
        word_count = len([word for word in outputs["words"]])
        lines = zip(*[outputs[k] if k in outputs else ["_"] * word_count
                      for k in ["ids", "words", "lemmas", "upos_tags", "xpos_tags", "feats",
                                "heads", "rels"]])

        multiword_map = None
        if outputs["multiword_ids"]:
            multiword_ids = [[id] + [int(x) for x in id.split("-")] for id in outputs["multiword_ids"]]
            multiword_forms = outputs["multiword_forms"]
            multiword_map = {start: (id_, form) for (id_, start, end), form in zip(multiword_ids, multiword_forms)}

        output_lines = []
        for i, line in enumerate(lines):
            line = [str(l) for l in line]

            # Handle multiword tokens
            if multiword_map and i+1 in multiword_map:
                id_, form = multiword_map[i+1]
                row = f"{id_}\t{form}" + "".join(["\t_"] * 8)
                output_lines.append(row)

            row = "\t".join(line) + "".join(["\t_"] * 2)
            output_lines.append(row)

        return "\n".join(output_lines) + "\n\n"

class UniversalDependenciesRawDatasetReader(UniversalDependenciesDatasetReader):
    def __init__(self, language):
        super().__init__()
        self.tokenizer = SpacyWordSplitter(language=language,pos_tags=True)

    @overrides
    def load(self, file_path):
        file_path = cached_path(file_path)
        counter = 1
        with open(file_path, 'r') as conllu_file:
            for sentence in conllu_file:
                if sentence:
                    words = [word.text for word in self.tokenizer.split_words(sentence)]
                    upos_tags = [word.tag_ for word in self.tokenizer.split_words(sentence)]
                    xpos_tags = upos_tags
                    seq_len = len(words)
                    ids = [i+1 for i in range(seq_len)]
                    lemmas = ["_" for i in range(seq_len)]
                    feats = lemmas
                    heads = [1 for i in range(seq_len)]
                    dep_rels = ["<UNK>" for i in range(seq_len)]
                    multiword_ids = []
                    multiword_forms = []
                    sentence = UD_Sentence(ids,words,lemmas,upos_tags,xpos_tags,feats,heads, dep_rels,multiword_ids,multiword_forms)
                    self.sentences.append(sentence)
                    self.ids.append(counter)
                    counter = counter + 1


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('productos', views.productos, name='productos'),
    path('horarios', views.horarios, name='horarios'),
    path('registro', views.registro, name='registro'),
    path('chango', views.chango, name='chango'),
    path('proximamente', views.proximamente, name='proximamente'),
    path('listado', views.listado, name='listado'),
    path('crear', views.crear, name='crear'),
    path('eliminar/<int:id>', views.eliminar, name='eliminar'),
    path('editar/<int:id>', views.editar, name='editar'),
]


# -------------------------------------------------------------------------------------------------------------
# Exercise #16: Map, Filter, Reduce
# Developer:    Amr Gaafer
# Date:         10.09.2022
# -------------------------------------------------------------------------------------------------------------

import os
os.system('cls')        # cls command

print("Task#1: map():")
def remove_chars(s):
    return s[slice(1,len(s)-1)]
friends_map = ["AEmanS", "AAhmedS", "DSamehF", "LOsamaL"]

# Test 1
cleaned_list  = map(remove_chars, friends_map)
for s in cleaned_list:
    print(f'"{s}"')

# Test 2
cleaned_list  = map(lambda s: s[slice(1,len(s)-1)]+": from lambda", friends_map)
for s in cleaned_list:
    print(f'"{s}"')

print("Task#2: filter():")
def get_names(s):
    return s.endswith('m')
friends_filter = ["Osama", "Wessam", "Amal", "Essam", "Gamal", "Othman"]

# Test 1
names = filter(get_names, friends_filter)
for s in names:
    print(f'"{s}"')

# Test 2
names = filter(lambda s: s.endswith('m'), friends_filter)
for s in names:
    print(f'"{s} : from lambda"')

print("Task#3: reduce():")
from functools import reduce

def my_multiplication(num1, num2):
    return num1 * num2
nums = [2, 4, 6, 2]

# Test 1
print(reduce(my_multiplication, nums))

# Test 2
print(reduce(lambda num1, num2: num1 * num2, nums))

print("Task#4: enumerate():")
skills = ("HTML", "CSS", 10, "PHP", "Python", 20, "JavaScript")

# Solution 1
print("Solution 1:")
for count, skill in enumerate(reversed(skills), 50):
    if type(skill) == str:
        print('"', count, " - " ,skill, '"', sep='')

# Solution 2
print("Solution 2:")
for skill in enumerate(reversed(skills), 50):
    if(type(skill[1])) != int:
        print(skill)


#!/usr/bin/env python3
##!/bin/sh
#"exec" "python3" "-m" "scoop" "$0"

from collections import Counter
from datetime import datetime
from deap import creator, base, tools, algorithms
from deap.tools.emo import assignCrowdingDist
from itertools import count
from numpy.random import randint, random, seed
from pathways import *
from scoop import futures
import multiprocessing
import numpy as np
import pickle
import shutil, os, sys
import sys

n = len(P)
all_present = (1 << n) - 1
rules_shape = n, max_k, 2

MU = 1024 # Needs to be divisible by 4!
CXPB = 0.9

TRIES = 128

POP_FILE = "pop.dat"
POP_FILE = POP_FILE if len(sys.argv) == 1 else sys.argv[1]

def uniformly_random_individual():
    return randint(all_present, dtype=np.uint32, size=rules_shape)

def random_individual(k=4):
    data = np.full((n, max_k, 2), (1 << n) - 1, dtype=np.uint32)
    for _ in range(k):
        data &= uniformly_random_individual()
    return data

def mutate_k(ind, max_mutations = max_k, indpb = 0.9):
    #print("calling mutate_k")
    for _ in range(max_mutations):
        if random() < indpb:
            ind[randint(n)][randint(max_k)][randint(2)] ^= I << np.uint32(randint(n)) # Flip bit
    return ind

def mutate_anywhere(ind, indpb = 0.02):
    #print("calling mutate_anywhere")

    for m in range(n):
        for k in range(max_k):
            for i in (0,1):
                for j in range(n):
                    if random() < indpb:
                        ind[m][k][i] ^= I << np.uint32(j) # Flip bit
    return ind

def popcount(a):
    a -= np.bitwise_and(np.right_shift(a, 1), 0x55555555)
    a = np.bitwise_and(a, 0x33333333) + np.bitwise_and(np.right_shift(a, 2), 0x33333333)
    return np.right_shift(np.bitwise_and((np.bitwise_and(a + np.right_shift(a, 4), 0xF0F0F0F) * 0x1010101), 0xffffffff), 24)

def hamming(a, b):
    #print("callint hamming")
    return int(popcount(a^b).sum())

def attractor_appearance(rules : np.ndarray, attractor : tuple, maxsteps = 16):
    #print("callint attractor_appearance")
    return model_attractors(interpret_dnf, rules, TRIES,
            canonicalize = True,
            container = Counter,
            maxsteps = maxsteps)[attractor]

def cxTwoPointCopy(ind1, ind2):
    """Execute a two points crossover with copy on the input individuals. The
    copy is required because the slicing in numpy returns a view of the data,
    which leads to a self overwritting in the swap operation. It prevents
    ::

        >>> import numpy
        >>> a = numpy.array((1,2,3,4))
        >>> b = numpy.array((5.6.7.8))
        >>> a[1:3], b[1:3] = b[1:3], a[1:3]
        >>> print(a)
        [1 6 7 4]
        >>> print(b)
        [5 6 7 8]
    """
    #size = len(ind1) = n
    cxpoint1 = randint(1, n)
    cxpoint2 = randint(1, n - 1)
    if cxpoint2 >= cxpoint1:
        cxpoint2 += 1
    else: # Swap the two cx points
        cxpoint1, cxpoint2 = cxpoint2, cxpoint1

    ind1[cxpoint1:cxpoint2], ind2[cxpoint1:cxpoint2] \
        = ind2[cxpoint1:cxpoint2].copy(), ind1[cxpoint1:cxpoint2].copy()

    return ind1, ind2

def cxUniformCopy(ind1, ind2, indpb=0.5):
    """Executes a uniform crossover that modify in place the two
    :term:`sequence` individuals. The attributes are swapped accordingto the
    *indpb* probability.

    :param ind1: The first individual participating in the crossover.
    :param ind2: The second individual participating in the crossover.
    :param indpb: Independent probabily for each attribute to be exchanged.
    :returns: A tuple of two individuals.

    This function uses the :func:`~random.random` function from the python base
    :mod:`random` module.
    """
    for i in range(n):
        if random() < indpb:
            ind1[i], ind2[i] = ind2[i].copy(), ind1[i].copy()

    return ind1, ind2

def cxOnePointCopy(ind1, ind2):
    """Executes a one point crossover on the input :term:`sequence` individuals.
    The two individuals are modified in place. The resulting individuals will
    respectively have the length of the other.

    :param ind1: The first individual participating in the crossover.
    :param ind2: The second individual participating in the crossover.
    :returns: A tuple of two individuals.
    This function uses the :func:`~random.randint` function from the
    python base :mod:`random` module.
    """
    cxpoint = randint(1, n - 1)
    ind1[cxpoint:], ind2[cxpoint:] = ind2[cxpoint:].copy(), ind1[cxpoint:].copy()

    return ind1, ind2

DESIRED_ATTRACTOR = (0b0000000000000000000000000000, 0b1000000000000000000000000000)

RULES_SYM = {head : to_dnf(body, simplify=True) for head,body in rules_original.items()}
RULES = rules_rep(P, RULES_SYM, same_k = True)
assert RULES.shape == rules.shape

def evaluate(ind):
    #print("calling evaluate")
    return attractor_appearance(ind, DESIRED_ATTRACTOR), hamming(ind, RULES)

creator.create("Fitness", base.Fitness, weights=(1, -1))
creator.create("Individual", np.ndarray, fitness=creator.Fitness)
creator.Individual.__hash__ = lambda self: int(self.sum()) # Monkey patch hack for other stuff to work

toolbox = base.Toolbox()
toolbox.register("individual", tools.initIterate, creator.Individual, random_individual)

#toolbox.register("map", futures.map)
processes = int(os.getenv("PROCESSES", 2))
print("Running on %d processes" % processes)
pool = multiprocessing.Pool(processes)
toolbox.register("map", pool.map)

toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("mate", cxTwoPointCopy)
#toolbox.register("mate", cxUniformCopy)
#toolbox.register("mate", cxOnePointCopy)
toolbox.register("mutate", mutate_k)
toolbox.register("evaluate", evaluate)
toolbox.register("select", tools.selNSGA2)
def spea2(pop, mu):
    assignCrowdingDist(pop)
    return tools.selSPEA2(pop, mu)
#toolbox.register("select", spea2)

stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("min", np.min, axis=0)
stats.register("max", np.max, axis=0)

logbook = tools.Logbook()
logbook.header = "gen", "evals", "std", "min", "avg", "max"

def main(seed_=0):
    #seed(seed_)

    stats = tools.Statistics(lambda ind: ind.fitness.values)
    # stats.register("avg", numpy.mean, axis=0)
    # stats.register("std", numpy.std, axis=0)
    stats.register("min", np.min, axis=0)
    stats.register("max", np.max, axis=0)

    logbook = tools.Logbook()
    logbook.header = "gen", "evals", "std", "min", "avg", "max"

    if os.path.isfile(POP_FILE):
        with open(POP_FILE,"rb") as dumpfile:
            pop = pickle.load(dumpfile)
    else:
        pop = toolbox.population(n=MU)

    #pop[0] = creator.Individual(rules)

    # Evaluate the individuals with an invalid fitness
    invalid_ind = [ind for ind in pop if not ind.fitness.valid]
    fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
    for ind, fit in zip(invalid_ind, fitnesses):
        ind.fitness.values = fit

    # This is just to assign the crowding distance to the individuals
    # no actual selection is done
    pop = toolbox.select(pop, len(pop))

    record = stats.compile(pop)
    logbook.record(gen=0, evals=len(invalid_ind), **record)
    print(logbook.stream)

    # Begin the generational process
    try:
        for gen in count(1):

            #with open("gen-%d.pop" % gen,"wb") as dumpfile:
            if os.path.isfile(POP_FILE):
                shutil.move(POP_FILE, POP_FILE+".bak")

            with open(POP_FILE,"wb") as dumpfile:
                pickle.dump(pop, dumpfile)
            # Vary the population

            offspring = tools.selTournamentDCD(pop, len(pop))
            offspring = [toolbox.clone(ind) for ind in offspring]

            for ind1, ind2 in zip(offspring[::2], offspring[1::2]):
                if random() <= CXPB:
                    toolbox.mate(ind1, ind2)

                toolbox.mutate(ind1)
                toolbox.mutate(ind2)
                del ind1.fitness.values, ind2.fitness.values

            # Evaluate the individuals with an invalid fitness
            invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
            fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
            for ind, fit in zip(invalid_ind, fitnesses):
                ind.fitness.values = fit

            # Select the next generation population
            pop = toolbox.select(pop + offspring, MU)
            record = stats.compile(pop)
            logbook.record(gen=gen, evals=len(invalid_ind), **record)
            print(str(datetime.now()))
            print(logbook.stream)
            #print([ind.fitness.values for ind in pop])
    except KeyboardInterrupt:
        return pop, logbook
    #print("Final population hypervolume is %f" % hypervolume(pop, [11.0, 11.0]))

    return pop, logbook

if __name__ == "__main__":
    pop, stats = main()
    for ind in pop:
        print(ind.fitness.values)

    print(stats)


# Ball Catcher - Chytač míčů
import pygame
import random

# Inicializace hry
pygame.init()

# Obrazovka
width = 1200
height = 700
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Ball catcher")

# Nastavení hry
clock = pygame.time.Clock()
fps = 60

# Barvy
green = (14, 116, 0)

# Classy
class Game:
    # constructor
    def __init__(self, our_player, set_of_balls):
        self.score = 0
        self.round_number = 0

        self.round_time = 0
        self.slow_down_cycle = 0

        self.our_player = our_player
        self.set_of_balls = set_of_balls

        # Hudba v pozadí
        pygame.mixer.music.load("media/bg-music-bc.mp3")
        pygame.mixer.music.play(-1, 0.0)

        # fonty
        self.ball_font = pygame.font.Font("fonts/ball-c.ttf", 24)
        self.middle_ball_font = pygame.font.Font("fonts/ball-c.ttf", 60)
        self.large_ball_font = pygame.font.Font("fonts/ball-c.ttf", 100)

        # Obrázky
        soccer_image = pygame.image.load("img/soccer-ball.png")
        baseball_image = pygame.image.load("img/baseball-ball.png")
        football_image = pygame.image.load("img/football-ball.png")
        basketball_image = pygame.image.load("img/basketball-ball.png")

        self.ball_images = [soccer_image, baseball_image, football_image, basketball_image]

        # generujeme míč, který chceme chytit
        self.ball_catch_type = random.randint(0, 3)
        self.ball_catch_image = self.ball_images[self.ball_catch_type]
        self.ball_catch_image_rect = self.ball_catch_image.get_rect()
        self.ball_catch_image_rect.centerx = (width//2)
        self.ball_catch_image_rect.top = 45

    # Kód, který je opětovně volán
    def update(self):
        self.slow_down_cycle += 1
        if self.slow_down_cycle == fps:
            self.round_time += 1
            self.slow_down_cycle = 0

        # kontrola kolize
        self.check_collisions()

        # vykreslení na obrazovku
        self.draw()

    # Vykresluje vše ve hře - texty, hledaný míč
    def draw(self):
        white = (255, 255, 255)
        red = (155, 12, 12)
        brown = (58, 33, 18)
        dark_orange = (193, 92, 3)
        grey = (120, 120, 120)
        colors = [white, red, brown, dark_orange]

        # Nastavení textu
        catch_text = self.ball_font.render("Catch the ball", True, white)
        catch_text_rect = catch_text.get_rect()
        catch_text_rect.centerx = width//2
        catch_text_rect.top = 5

        score_text = self.ball_font.render(f"Score: {self.score}", True, white)
        score_text_rect = score_text.get_rect()
        score_text_rect.topleft = (10, 4)

        lives_text = self.ball_font.render(f"Lives: {self.our_player.lives}", True, white)
        lives_text_rect = lives_text.get_rect()
        lives_text_rect.topleft = (10, 30)

        round_text = self.ball_font.render(f"Round: {self.round_number}", True, white)
        round_text_rect = round_text.get_rect()
        round_text_rect.topleft = (10, 60)

        time_text = self.ball_font.render(f"Round Time: {self.round_time}", True, white)
        time_text_rect = time_text.get_rect()
        time_text_rect.topright = (width - 10, 5)

        # Počet, kolikrát se může hráč vrátit do bezpečné zóny
        back_safe_zone_text = self.ball_font.render(f"Safe Zone Returns: {self.our_player.enter_safe_zone}", True, white)
        back_safe_zone_text_rect = back_safe_zone_text.get_rect()
        back_safe_zone_text_rect.topright = (width - 10, 30)

        safe_zone_screen_text = self.middle_ball_font.render("SAFE ZONE", True, grey)
        safe_zone_screen_text_rect = safe_zone_screen_text.get_rect()
        safe_zone_screen_text_rect.center = (width//2, height - 50)

        press_space_text = self.ball_font.render("Press SPACE to get here", True, grey)
        press_space_text_rect = press_space_text.get_rect()
        press_space_text_rect.center = (180, height - 50)

        # Vykreslení (blitting) do obrazovky
        screen.blit(catch_text, catch_text_rect)
        screen.blit(score_text, score_text_rect)
        screen.blit(lives_text, lives_text_rect)
        screen.blit(round_text, round_text_rect)
        screen.blit(time_text, time_text_rect)
        screen.blit(back_safe_zone_text, back_safe_zone_text_rect)
        screen.blit(safe_zone_screen_text, safe_zone_screen_text_rect)
        screen.blit(press_space_text, press_space_text_rect)

        # Obrázek míče, který máme chytit
        screen.blit(self.ball_catch_image, self.ball_catch_image_rect)

        # Tvary

        # Vykreslení hřiště
        pygame.draw.line(screen, white, (width // 2, 100), (width // 2, height - 102), 4)
        pygame.draw.circle(screen, white, (width//2, 349), 80, 4)
        pygame.draw.rect(screen, white, (0, 200, 150, 300), 4)
        pygame.draw.rect(screen, white, (width - 150, 200, 150, 300), 4)
        pygame.draw.rect(screen, white, (0, 250, 60, 200), 4)
        pygame.draw.rect(screen, white, (width - 60, 250, 60, 200), 4)

        # Rámeček hřiště a zároveň herní plochy pro míče - kde se mohou míče pohybovat
        pygame.draw.rect(screen, colors[self.ball_catch_type], (0, 100, width, height - 200), 4)

        # Kontroluje kolizi hráče s míčem
    def check_collisions(self):
        # s jakým míčem jsme se srazili
        collided_ball = pygame.sprite.spritecollideany(self.our_player, self.set_of_balls)

        if collided_ball:
            # Srazili jsme se se správným míčem
            if collided_ball.type == self.ball_catch_type:
                # Přehrajeme zvuk správného chycení míče
                self.our_player.catch_sound.play()
                # Zvýšíme skóre
                self.score += 10 * self.round_number
                # Odstranění chyceného míče
                collided_ball.remove(self.set_of_balls)
                # Kontrola, zda ještě existují nějaké míče, které můžeme chytat
                if self.set_of_balls:
                    self.choose_new_target()
                else:
                    # Kolo je dokončené - všechny míče jsme chytili
                    self.our_player.reset()
                    self.start_new_round()
            else:
                self.our_player.wrong_sound.play()
                self.our_player.lives -= 1
                # kontrola, zda je hráč naživu - Konec hry
                if self.our_player.lives <= 0:
                    self.pause_game(f"Final Score: {self.score}", "Press ENTER if you want to play again")
                    self.reset_game()
                self.our_player.reset()

    # Zahájí nové kolo - s větším počtem míčů v herní ploše
    def start_new_round(self):
        # Při dokončení kola poskytneme bonus podle toho, jak rychle hráč kolo dokončí: dříve = více bodů
        self.score += int(100 * (self.round_number / (1 + self.round_time)))

        # Resetujeme hodnoty
        self.round_time = 0
        self.slow_down_cycle = 0
        self.round_number += 1
        self.our_player.enter_safe_zone += 1

        # Odebereme všechny míče, abychom mohli sadu naplnit novými míči
        for deleted_ball in self.set_of_balls:
            self.set_of_balls.remove(deleted_ball)

        # Naplníme sadu míčů novými míči
        for i in range(self.round_number):
            self.set_of_balls.add(Ball(random.randint(0, width - 64), random.randint(100, height-164), self.ball_images[0], 0))
            self.set_of_balls.add(
                Ball(random.randint(0, width - 64), random.randint(100, height - 164), self.ball_images[1], 1))
            self.set_of_balls.add(
                Ball(random.randint(0, width - 64), random.randint(100, height - 164), self.ball_images[2], 2))
            self.set_of_balls.add(
                Ball(random.randint(0, width - 64), random.randint(100, height - 164), self.ball_images[3], 3))

        # Vybíráme nový míč, který máme chytit
        self.choose_new_target()

    # Vybírá nový míč, který máme chytit
    def choose_new_target(self):
        new_ball_to_catch = random.choice(self.set_of_balls.sprites())
        self.ball_catch_type = new_ball_to_catch.type
        self.ball_catch_image = new_ball_to_catch.image

    # Pozastavení hry - pauza před zahájením nové hry, na začátku při spuštění
    def pause_game(self, main_text, subheading_text):

        global lets_continue

        # Nastavíme barvy
        white = (255, 255, 255)
        green = (14, 116, 0)

        # Hlavní text pro pauznutí
        main_text_create = self.large_ball_font.render(main_text, True, white)
        main_text_create_rect = main_text_create.get_rect()
        main_text_create_rect.center = (width//2, height//2 - 50)

        # Vedlejší text pro pauznutí
        subheading_text_create = self.middle_ball_font.render(subheading_text, True, white)
        subheading_text_create_rect = subheading_text_create.get_rect()
        subheading_text_create_rect.center = (width//2, height//2 + 50)

        # Obrázky míčů
        soccer_ball_image = pygame.image.load("img/soccer-ball-big.png")
        soccer_ball_image_rect = soccer_ball_image.get_rect()
        soccer_ball_image_rect.center = (160, 120)

        baseball_ball_image = pygame.image.load("img/baseball-ball-big.png")
        baseball_ball_image_rect = baseball_ball_image.get_rect()
        baseball_ball_image_rect.center = (width-160, 120)

        football_ball_image = pygame.image.load("img/football-ball-big.png")
        football_ball_image_rect = football_ball_image.get_rect()
        football_ball_image_rect.center = (160, height-120)

        basketball_ball_image = pygame.image.load("img/basketball-ball-big.png")
        basketball_ball_image_rect = basketball_ball_image.get_rect()
        basketball_ball_image_rect.center = (width-160, height-120)

        # Zobrazení hlavního textu, podnadpisu a obrázků
        screen.fill(green)
        screen.blit(main_text_create, main_text_create_rect)
        screen.blit(subheading_text_create, subheading_text_create_rect)
        screen.blit(soccer_ball_image, soccer_ball_image_rect)
        screen.blit(baseball_ball_image, baseball_ball_image_rect)
        screen.blit(football_ball_image, football_ball_image_rect)
        screen.blit(basketball_ball_image, basketball_ball_image_rect)

        pygame.display.update()

        # Zastavení hry
        paused = True
        while paused:
            for one_event in pygame.event.get():
                if one_event.type == pygame.KEYDOWN:
                    if one_event.key == pygame.K_RETURN:
                        paused = False
                if one_event.type == pygame.QUIT:
                    paused = False
                    lets_continue = False

    # Resetuje hru do výchozího stavu
    def reset_game(self):
        self.score = 0
        self.round_number = 0
        self.our_player.lives = 5
        self.our_player.enter_safe_zone = 3
        self.start_new_round()

        # Spuštění muziky v pozadí
        pygame.mixer.music.play(-1, 0.0)

class Player(pygame.sprite.Sprite):
    # constructor
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("img/player.png")
        self.rect = self.image.get_rect()
        self.rect.centerx = width//2
        self.rect.bottom = height

        # rychlost hráče
        self.lives = 5
        self.enter_safe_zone = 2
        self.speed = 8

        self.catch_sound = pygame.mixer.Sound("media/pick.wav")
        self.catch_sound.set_volume(0.3)

        self.wrong_sound = pygame.mixer.Sound("media/wrong.wav")
        self.wrong_sound.set_volume(0.5)

    # Kód který je opakovaně volán (updatován)
    def update(self):
        keys = pygame.key.get_pressed()
        if (keys[pygame.K_UP] or keys[pygame.K_w]) and self.rect.top > 100:
            self.rect.y -= self.speed
        if (keys[pygame.K_DOWN] or keys[pygame.K_s]) and self.rect.bottom < height:
            self.rect.y += self.speed
        if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and self.rect.left > 0:
            self.rect.x -= self.speed
        if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and self.rect.right < width:
            self.rect.x += self.speed

    # Návrat do bezpečné zóny
    def back_to_safe_zone(self):
        if self.enter_safe_zone > 0:
            self.enter_safe_zone -= 1
            self.rect.bottom = height

    # Vrací hráče zpět na výchozí pozici - doprostřed bezpečné zóny
    def reset(self):
        self.rect.centerx = width//2
        self.rect.bottom = height

class Ball(pygame.sprite.Sprite):
    # constructor
    def __init__(self, x, y, image, ball_type):
        super().__init__()
        # nahrajeme obrázek mozkomora a umístíme ho
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)

        # typy míčů: 0 = fotbal(soccer), 1 = baseball, 2 = americký fotbal, 3 = basketbal
        self.type = ball_type

        # nastavení náhodného směru míče
        self.x = random.choice([-1, 1])
        self.y = random.choice([-1, 1])
        self.speed = random.randint(1, 5)

    # Kód který je opakovaně volán (updatován)
    def update(self):
        # pohyb míče
        self.rect.x += self.x * self.speed
        self.rect.y += self.y * self.speed

        # odraz míče
        if self.rect.left < 0 or self.rect.right > width:
            self.x *= -1
        elif self.rect.bottom > height - 100 or self.rect.top < 100:
            self.y *= -1

# Sada míčů
ball_set = pygame.sprite.Group()

# Skupina hráčů
player_group = pygame.sprite.Group()
one_player = Player()
player_group.add(one_player)

# Nastavení proměnné k pokračování Hlavného cyklu
lets_continue = True

# Objekt Game
my_game = Game(one_player, ball_set)
my_game.pause_game("Ball Catcher", "Press ENTER to start the game")
my_game.start_new_round()

# Hlavní cyklus

while lets_continue:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            lets_continue = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                one_player.back_to_safe_zone()

    # Vkládání zeleného pozadí (blitting)
    screen.fill(green)

    # Updatujeme objekt vytvořený podle classy Game
    my_game.update()

    # Updatujeme sadu míčů
    ball_set.draw(screen)
    ball_set.update()
    # Updatujeme skupinu hráčů (jeden hráč)
    player_group.draw(screen)
    player_group.update()

    # Update obrazovky
    pygame.display.update()

    # Zpomalení cyklu
    clock.tick(fps)

# Ukončení hry
pygame.quit()


from django.shortcuts import render, redirect
from phones.models import Phone

def index(request):
    return redirect('catalog')

def show_catalog(request):
    template = 'catalog.html'
    sort = request.GET.get("sort", "id")
    if sort == 'max_price':
        sort = "-price"
    elif sort == 'min_price':
        sort = "price"
    phones = Phone.objects.order_by(sort)

    context = {'phones': phones}
    return render(request, template, context)

def show_product(request, slug):
    template = 'product.html'
    tel = Phone.objects.get(slug=slug)
    context = {'slug': tel}
    return render(request, template, context)


import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# Load dataset
recipes_df = pd.read_csv('indian_dishes.csv')

# Define vectorizer object
vectorizer = CountVectorizer()

# Create ingredient list string for each recipe
recipes_df['ingredients'] = recipes_df.apply(lambda x: ','.join([str(i) for i in x[1:]]), axis=1)

# Create ingredient count matrix
ingredient_count_matrix = vectorizer.fit_transform(recipes_df['ingredients'])

# Define function to get top n similar recipes
def get_similar_recipes(input_dishes, n, recipes_df):
    # Create ingredient list string for input dishes
    input_dishes_list = ','.join(input_dishes)

    # Add input dishes to dataset
    new_row = {'name': 'input_dishes', 'ingredients': input_dishes_list}
    recipes_df = recipes_df.append(new_row, ignore_index=True)

    # Create ingredient count matrix
    ingredient_count_matrix = vectorizer.fit_transform(recipes_df['ingredients'])

    # Get cosine similarity scores between input dishes and all recipes
    cosine_similarities = cosine_similarity(ingredient_count_matrix)
    cosine_scores = list(enumerate(cosine_similarities[-1]))

    # Sort cosine scores in descending order
    sorted_cosine_scores = sorted(cosine_scores, key=lambda x:x[1], reverse=True)

    # Get top n similar recipes
    top_n_similar_recipes = []
    for i in range(1,n+1):
        top_n_similar_recipes.append(recipes_df.iloc[sorted_cosine_scores[i][0]]['name'])

    # Remove input dishes from dataset
    recipes_df.drop(recipes_df.tail(1).index, inplace=True)

    return top_n_similar_recipes

# Example usage
input_dishes = ['rice', 'chicken', 'tomato', 'onion', 'ginger', 'garlic']
n = 5

similar_recipes = get_similar_recipes(input_dishes, n, recipes_df)

print(similar_recipes)


#####################################################################################################################
# inversion: This module provide specialized functions for computing node inverses and localized inverses.          #
#            It is part of the Cuicuilco framework                                                                  #
# Main functions: localized_inverse, linear_localized_inverse, layer_localized_inverse,                             #
#                 general_expansion_node_localized_inverse, invert_exp_funcs2                                       #
#                                                                                #
# By Alberto Escalante. Alberto.Escalante@ini.rub.de                                                                #
# Ruhr-University-Bochum, Institute for Neural Computation, Group of Prof. Dr. Wiskott                              #
#####################################################################################################################

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy
import scipy
import scipy.optimize

import mdp

from . import more_nodes
from . import sfa_libs

def localized_inverse(self, x_local, y_to_invert, verbose=False):
    """Computes a global localized inverse of a flow as the composition of the
    localized inverses of each layer/node in inverse order
    """
    flow = self.flow
    num_nodes = len(flow)

    # compute all forward signals
    forward_x = [x_local, ]
    current_x = x_local
    for i in range(num_nodes):
        next_x = flow[i].execute(current_x)
        forward_x.append(next_x)
        current_x = next_x

    # then compute each backwards signal
    current_y = y_to_invert
    for i in range(len(flow)-1, -1, -1):
        try:
            node = flow[i]
            # Localized inverse of linear nodes
            linear_nodes = (mdp.nodes.SFANode, mdp.nodes.PCANode, mdp.nodes.WhiteningNode)
            processed = False

            for node_class in linear_nodes:
                if isinstance(node, node_class) and not processed:
                    processed = True
                    current_y = node.localized_inverse(forward_x[i], forward_x[i+1], current_y)

            # "Localized" inverse of invertible nodes
            invertible_nodes = [more_nodes.PInvSwitchboard, more_nodes.PointwiseFunctionNode,
                                more_nodes.RandomPermutationNode]
            for node_class in invertible_nodes:
                if isinstance(node, node_class) and not processed:
                    processed = True
                    current_y = node.inverse(current_y)

            # Localized inverse of Layers (recursion)
            if isinstance(node, mdp.hinet.Layer) and not processed:
                processed = True
                current_y = node.localized_inverse(forward_x[i], forward_x[i+1], current_y)

            # Localized inverse of GeneralExpansionNode
            if isinstance(node, more_nodes.GeneralExpansionNode) and not processed:
                processed = True
                current_y = node.localized_inverse(forward_x[i], forward_x[i+1], current_y)

            if not processed:
                txt = "I was not able to compute the localized inverse of node: %s ", str(node)
                raise Exception(txt)
        except Exception as e:
            self._propagate_exception(e, i)
        if verbose:
            print("Localized Node Inversion finished")

    print("Localized Flow Inversion finished")
    return current_y

def linear_localized_inverse(self, x, y, y_prime):
    """Computes a localized inverse around the point x.
    This assumes that the node is linear and keeps the part of x that is lost
    when mapping to y and then back to x' by using the pseudoinverse
    """
    # print "LinLocInv: x.shape=", x.shape, "y.shape=", y.shape, "y_prime.shape=", y_prime.shape
    x_perp = x - self.inverse(y)
    return x_perp + self.inverse(y_prime)

def layer_localized_inverse(self, x, y, y_prime, verbose=False):
    """Computes a localized inverse around the point x for a given layer
    as the concatenation of the localized inverses of each node contained in the layer

    This is a slightly modified version of mdp.hinet.Layer.inverse
    """
    in_start = 0
    in_stop = 0
    out_start = 0
    out_stop = 0
    x_prime = None

    nodes_with_localized_inverse = (mdp.nodes.SFANode, mdp.nodes.PCANode, mdp.nodes.WhiteningNode)

    for node in self.nodes:
        # print "Layer localized inversion iteration"
        # compared with execute, input and output are switched
        out_start = out_stop
        out_stop += node.input_dim
        in_start = in_stop
        in_stop += node.output_dim

        # print "out_start = %d, out_stop = %d, in_start = %d, in_stop = %d" %(out_start, out_stop, in_start, in_stop)
        if x_prime is None:
            if isinstance(node, nodes_with_localized_inverse):
                node_x = node.localized_inverse(x[:, out_start:out_stop], y[:, in_start:in_stop],
                                                y_prime[:, in_start:in_stop])
            else:
                if verbose:
                    print("Using inverse for node:", node)
                node_x = node.inverse(y_prime[:, in_start:in_stop])

            x_prime = numpy.zeros([node_x.shape[0], self.input_dim], dtype=node_x.dtype)
            x_prime[:, out_start:out_stop] = node_x
        else:
            if isinstance(node, nodes_with_localized_inverse):
                x_prime[:, out_start:out_stop] = node.localized_inverse(x[:, out_start:out_stop],
                                                                        y[:, in_start:in_stop],
                                                                        y_prime[:, in_start:in_stop])
            else:
                x_prime[:, out_start:out_stop] = node.inverse(y_prime[:, in_start:in_stop])
    return x_prime

def general_expansion_node_localized_inverse(self, x, y, y_prime, max_steady_factor=None,
                                             delta_factor=None, min_delta=None):
    """The localized inverse in a general_expansion_node is just the inverse using x as hint (initial point) """
    return self.inverse(y_prime, use_hint=x, max_steady_factor=max_steady_factor, delta_factor=delta_factor,
                        min_delta=min_delta)

# input: exp_x_noisy.shape=[1,dim_exp_x],
# outputs: one dim vectors
def invert_exp_funcs(exp_x_noisy, dim_x, exp_funcs, distance=sfa_libs.distance_best_squared_Euclidean, use_hint=False,
                     max_steady_factor=5, delta_factor=0.7, min_delta=0.0001, verbose=False):
    """This function is deprecated, don't use it """
    num_samples = exp_x_noisy.shape[0]

    if use_hint:
        if verbose:
            print("Using lowest dim_x=%d elements of input for first approximation!" % (dim_x))
        app_x = exp_x_noisy[:, 0:dim_x].copy()
    else:
        app_x = numpy.random.normal(size=(num_samples, dim_x))

    app_exp_x = sfa_libs.apply_funcs_to_signal(exp_funcs, app_x)
    if verbose:
        print("app_exp_x", app_exp_x)

    dim_exp_x = exp_x_noisy.shape[1]

    iterations = 0
    max_steady_iter = numpy.sqrt(dim_x) * max_steady_factor
    for row in range(num_samples):
        app_x_row = app_x[row].reshape(1, dim_x)
        exp_x_noisy_row = exp_x_noisy[row].reshape(1, dim_exp_x)
        app_exp_x_row = app_exp_x[row].reshape(1, dim_exp_x)
        if verbose:
            print("distance is: ", distance)
        dist = distance(exp_x_noisy_row, app_exp_x_row)
        delta = 1.0
        while delta > min_delta:
            steady_iter = 0
            while steady_iter < max_steady_iter:
                iterations = iterations + 1
                i = numpy.random.randint(0, high=dim_x)
                app_x_tmp_row = app_x_row.copy()
                app_x_tmp_row[0, i] = app_x_tmp_row[0, i] + numpy.random.normal(scale=delta)
                app_exp_x_tmp_row = sfa_libs.apply_funcs_to_signal(exp_funcs, app_x_tmp_row)
                dist_tmp = distance(exp_x_noisy_row, app_exp_x_tmp_row)
                if dist_tmp < dist:
                    app_x_row = app_x_tmp_row
                    app_exp_x_row = app_exp_x_tmp_row
                    dist = dist_tmp
                    if verbose:
                        print("app_x_row =", app_x_row)
                        print(", Dist=", dist)
                    steady_iter = 0
                else:
                    steady_iter = steady_iter + 1
            delta = delta * delta_factor
        app_x[row] = app_x_row[0]
        app_exp_x[row] = app_exp_x_row[0]
        if verbose:
            print("GEXP Inv: ", iterations, " iterations. ")
    return app_x, app_exp_x

# *******************************************
# y_noisy.shape is (M), exp_funcs
# only one dimensional vector inputs
# favour solutions close to x_orig
# adding a term  [ k(x-x_orig) ] ** 2 to the minimization problem
def residuals(app_x, y_noisy, exp_funcs, x_orig, k):
    """ Computes error signals as the concatenation of the reconstruction error
    (y_noisy - exp_funcs(app_x)) and the distance from the original (x_orig - app_x)
    using a weighting factor k
    """
    app_x = app_x.reshape((1, len(app_x)))
    app_exp_x = sfa_libs.apply_funcs_to_signal(exp_funcs, app_x)

    div_y = numpy.sqrt(len(y_noisy))
    div_x = numpy.sqrt(len(x_orig))
    return numpy.append((1-k)*(y_noisy-app_exp_x[0]) / div_y, k * (x_orig - app_x[0])/div_x)

# input: exp_x_noisy.shape=[1,dim_exp_x],
# outputs: one dim vectors
# Improved version
def invert_exp_funcs2(exp_x_noisy, dim_x, exp_funcs, distance=sfa_libs.distance_best_squared_Euclidean,
                      use_hint=False, max_steady_factor=5, delta_factor=0.7, min_delta=0.0001, k=0.5, verbose=False):
    """ Function that approximates a preimage of exp_x_noisy notice
    that distance, max_steady_factor, delta, min_delta are deprecated and useless
    """
    num_samples = exp_x_noisy.shape[0]

    if isinstance(use_hint, numpy.ndarray):
        if verbose:
            print("Using suggested approximation!")
        app_x = use_hint.copy()
    elif use_hint:
        if verbose:
            print("Using lowest dim_x=%d elements of input for first approximation!" % (dim_x))
        app_x = exp_x_noisy[:, 0:dim_x].copy()
    else:
        app_x = numpy.random.normal(size=(num_samples, dim_x))

    for row in range(num_samples):
        # app_x_row = app_x[row].reshape(1, dim_x)
        # exp_x_noisy_row = exp_x_noisy[row].reshape(1, dim_exp_x)
        # app_exp_x_row = app_exp_x[row].reshape(1, dim_exp_x)
        # Definition:       scipy.optimize.leastsq(func, x0, args=(), Dfun=None, full_output=0, col_deriv=0,
        #                                         ftol=1.49012e-08, xtol=1.49012e-08, gtol=0.0, maxfev=0, epsfcn=0.0,
        #                                         factor=100, diag=None, warning=True)
        plsq = scipy.optimize.leastsq(residuals, app_x[row], args=(exp_x_noisy[row], exp_funcs, app_x[row], k),
                                      ftol=1.49012e-06, xtol=1.49012e-06, gtol=0.0, maxfev=50*dim_x, epsfcn=0.0,
                                      factor=1.0)
        app_x[row] = plsq[0]

    app_exp_x = sfa_libs.apply_funcs_to_signal(exp_funcs, app_x)
    return app_x, app_exp_x


from PIL import Image
import numpy as np
from scipy.ndimage import filters
import matplotlib.pyplot as plt

# Not complete yet

##Apply the label() function to a thresholded image of your choice. Use histograms
##and the resulting label image to plot the distribution of object sizes in the image.

def label(image = None,threshold = None):
    # get all index with pixel > than threshold
    idx = image[:,:] < threshold
    image[idx] *= 0
    return image
infile = '../Images/baboon.png'
im = np.array(Image.open(infile).convert('L'))
(nr,nc) = im.shape
(dx,dy) = np.gradient(np.double(im))
orientation = np.arctan(np.divide(dx,dy))
(x,y) = np.meshgrid(im.shape[0],im.shape[1])

orientationThreshold = label(orientation, 1)
u = dx
v = dy
plt.figure()
plt.imshow(orientationThreshold)
plt.title('Out')
##plt.quiver(x,y,u,v)
plt.show()

# Here

CHAPTER1-Basic Image Handling and Processing/ex6.py


import os
import json
import boto3
from aws_lambda_powertools import Logger, Tracer

sns_client = boto3.client("sns")
TOPIC_ARN = os.environ.get("SNS_TOPIC_ARN")
# Initialize Logger and Tracer
tracer = Tracer()
logger = Logger()

@tracer.capture_lambda_handler
def lambda_handler(event, context):
    print(json.dumps(event))
    try:
        logger.debug(f"Received event: {json.dumps(event)}")

        event_name = event[0]['eventName']
        logger.info(f"event_name")
        if event_name in [
                "INSERT",
                "MODIFY"
                ]:
            new_image = event[0]['dynamodb'].get("NewImage")
            if (
                    new_image and 'OrderId' in new_image
                    ):
                sns_client.publish(
                        TopicArn=TOPIC_ARN,
                        Message=f"New entry added: {json.dumps(new_image)}",
                        Subject="New Entry in DDB"
                        )

        logger.info("SNS Sent successfully!")
        return {
            "statusCode": 200,
            "body": json.dumps("Function executed successfully!"),
        }

    except Exception as e:
        logger.error(f"Error in processing: {str(e)}")
        return {"statusCode": 500, "body": json.dumps(f"Error in processing: {str(e)}")}


from random import choice
import os
import argparse

dir_path = os.path.dirname(os.path.realpath(__file__))

with open(os.path.join(dir_path, 'safe.txt'), encoding='utf-8') as f:
	safe_facts = [
		fact.rstrip('\r\n ')
		for fact in f.readlines()
		if fact.rstrip('\r\n ') != ''
	]

with open(os.path.join(dir_path, 'unsafe.txt'), encoding='utf-8') as f:
	unsafe_facts = [
		fact.rstrip('\r\n ')
		for fact in f.readlines()
		if fact.rstrip('\r\n ') != ''
	]

all_facts = safe_facts + unsafe_facts

def get_fact(filter_enabled: bool = True, only_unsafe: bool = False) -> str:
	"""This function returns a random fact.

	Parameters
	----------
	filter_enabled : bool
		The `filter_enabled` parameter determines if the function will filter
		out potentially inappropriate facts. Defaults to True.

	only_unsafe : bool
		The `only_unsafe` parameter determines if the function will only give
		unsafe (NSFW) facts. Takes precedence over the `filter_enabled` argument.

	Returns
	------
	str
		A random fact.

	"""

	if only_unsafe:
		return choice(unsafe_facts)
	if filter_enabled is False:
		return choice(all_facts)
	return choice(safe_facts)

def _cli_entrypoint():
	"""Entrypoint for execution via command-line."""

	parser = argparse.ArgumentParser(
		description='Generate random facts from the command-line'
	)

	group = parser.add_mutually_exclusive_group()
	group.add_argument(
		'-m',
		'--mixed',
		action='store_true',
		help='Include safe and unsafe facts'
	)

	group.add_argument(
		'-u',
		'--unsafe',
		action='store_true',
		help='Only include unsafe facts'
	)

	args = parser.parse_args()

	if args.mixed:
		print(get_fact(False))
	elif args.unsafe:
		print(get_fact(only_unsafe=True))
	else:
		print(get_fact())

if __name__ == '__main__':
	_cli_entrypoint()


import spin_scale as m1
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['figure.facecolor'] = '0.2'

f = lambda scalex, scaley: m1.transformation(m1.scaleM(250, 250, scalex, scaley))
f2 = lambda mx, my: m1.transformation(m1.translationM(mx, my))
f3 = lambda angle: m1.transformation(m1.rotateM(200,200, angle))
f4 = lambda angle: m1.transformation(m1.rotateM(250, 250, angle))

C = np.full((500,500), 0, 'int')
rect = [(40,40), (260,40), (260, 260)]
#hex = [(20, 80), (30, 70), (50, 70), (60, 80), (50, 90), (30, 90)]
#hex2 = m1.hexagon(C, *list(map(f3(np.pi), hex)))
#print(hex2)

#m1.rectangle(C, *rect)

# plt.matshow(C, origin='lower', cmap='gray')
# plt.show()

def recImg(mx, my, angle, scalex = .5, scaley = .5):
    C = np.full((500,500), 0, 'int')
    #m1.rectangle(C, *list(map(f(scale, scale), rect)))
    #m1.rectangle(C, *list(map(f2(mx,my), rect)))
    #m1.rectangle(C, *list(map(f3(angle), rect)))
    m1.rectangle(C, *list(map(f(scalex, scaley), map(f4(angle), rect))))
    #m1.hexagon(C, *list(map(f3(np.pi/2), map(f2(mx,my), hex))))
    return C.copy()

steps = 100
images = [recImg(i,20,np.pi *i /steps) for i in range(steps)]

from PIL import Image

image_sequence = []

for frame in images:
    image = Image.fromarray(frame)
    image_sequence.append(image)

image_sequence[0].save('animation3.gif', save_all=True, append_images=image_sequence[1:], duration=20, loop=0)


from dataclasses import dataclass, field
from typing import Any, Callable, Optional, Type, Mapping, AbstractSet

from grongier.dacite.cache import Cache
from grongier.dacite.frozen_dict import FrozenDict

@dataclass
class Config:
    type_hooks: Mapping[Type, Callable[[Any], Any]] = field(default_factory=dict)
    cast: AbstractSet[Type] = field(default_factory=frozenset)
    forward_references: Optional[Mapping[str, Any]] = None
    check_types: bool = True
    strict: bool = False
    strict_unions_match: bool = False
    cache: Cache = Cache()

    def __post_init__(self):
        self.type_hooks = FrozenDict(self.type_hooks)
        self.cast = frozenset(self.cast)
        self.forward_references = FrozenDict(self.forward_references) if self.forward_references else None


from collections import Counter
class Solution(object):
    def countCharacters(self, words, chars):
        """
        :type words: List[str]
        :type chars: str
        :rtype: int
        """
        count = Counter(chars)
        ans=0

        for word in words:
            tempCount = count.copy()
            for c in word:
                tempCount[c] -= 1

                if tempCount[c] < 0:
                    ans -= len(word)
                    break
            ans += len(word)
        return ans


import os
from typing import Union
import kachery_cloud as kcl
from .Figure import Figure

class MultiTimeseries:
    def __init__(self, *, label: str) -> None:
        self._label = label
        self._panels = []
    def add_panel(self, figure: Figure, *, relative_height: Union[float, None]=None):
        self._panels.append({
            'figure': figure,
            'relative_height': relative_height
        })
    def get_composite_figure(self):
        panels = []
        for p in self._panels:
            fig0: Figure = p['figure']
            v = {
                'type': fig0.data['type'],
                'label': fig0.label,
                'figureDataUri': _upload_data_and_return_uri(fig0.get_serialized_figure_data())
            }
            if p['relative_height'] is not None:
                v['relativeHeight'] = p['relative_height']
            panels.append(v)
        data = {
            'type': 'MultiTimeseries',
            'panels': panels
        }
        return Figure(data=data, label=self._label)

def _upload_data_and_return_uri(data):
    data_uri = kcl.store_json(data)
    return data_uri


import serial
from flask import request
from flask_api import FlaskAPI, status

app = FlaskAPI(__name__)
ready = "ready"
port_name = "/dev/cu.usbmodem143201"

def send_str_to_arduino(msg):
    with serial.Serial(port_name, 9600) as ser:
        print("Waiting for arduino...")
        ch = ser.read(len(ready))
        print("Arduino: " + ch.decode())
        msg = msg.ljust(32)
        msg = msg[:32] + "\n"
        print("Message: <", msg.encode(), ">")
        ser.write(msg.encode())
        return msg

@app.route("/api/version")
def version():
    return {"name": "send text to serial", "verison": "0.1"}

@app.route("/api/sendser", methods=["Post"])
def send_ser():
    msg = request.data.get("msg", "")
    if not msg:
        return "", status.HTTP_204_NO_CONTENT
    print(msg)
    sent = send_str_to_arduino(msg)
    return {"sent": sent}, status.HTTP_201_CREATED

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9001, debug=True)


from django.conf.urls import include, url

from django.contrib import admin
admin.autodiscover()

from serve.views import bulkview,subprojectview,mapprojects,indexview,collectionview,collectioninsert,no_objection
urlpatterns = [
    url(r'^search/', indexview, name='index'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^projectin/',collectioninsert),
    url(r'^projectlist/',collectionview),
    url(r'^subprojectlist/',subprojectview),
    url(r'^subprojectin/',mapprojects),
    url(r'^insert/',no_objection),
    url(r'^insertBulk/',bulkinsert),
    url(r'^getbulk/',bulkview)
]


from django.shortcuts import render
from django.db.models import Avg, Count
from django.contrib.auth.models import User
from django.http import HttpResponse
from .models import Rater, Rating, Movie

# Create your views here.
def all_movies(request):
    movies = Movie.objects.all()
    return render(request,
            'review/movies.html',
            {'movies': movies})

def rater_detail(request):
    raters = Rater.objects.all()
    return render(request,
                    'review/rater_detail.html',
                    {'raters':raters})

def show_rater(request, rater_id):
    rater = Rater.objects.get(pk=rater_id)
    ratings = Rating.objects.filter(rater_id=rater.id)
    return render(request,
                  'review/rater_ratings.html',
                  {'ratings': ratings,
                    'rater': rater,
                  })

def top_movies(request):
    popular_movies = Movie.objects.annotate(num_ratings=Count('rating')) \
                                  .filter(num_ratings__gte=50)

    movies = popular_movies.annotate(Avg('rating__rating')) \
                           .order_by('-rating__rating__avg')[:20]

    return render(request,
                  'review/top_movies.html',
                  {'movies': movies})

def profile_info(request, user_id):
    movie_user = User.objects.get(pk=user_id)
    return render(request, 'review/profile.html',
                            {'movie_user': movie_user})


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from einops import rearrange, repeat
from torch import einsum

def compute_imitation_loss(input, target, weights):
    target = torch.where(torch.isnan(target), input, target)  # ignore nan targets
    diff = input - target
    loss = 0.5 * diff ** 2

    assert weights.shape == loss.shape[:-1]
    weights = weights.unsqueeze(-1)
    assert len(loss.shape) == len(weights.shape)
    loss = loss * weights
    return loss

def compute_backbone_l1_loss(features_preds, features_targets, target):
    feature_ditill_loss = 0.0
    if isinstance(features_preds, list):
        for i in range(len(features_preds)):
            downsample_ratio = 2 ** (i + 3)

            feature_target = features_targets[i].detach()
            feature_pred = features_preds[i]

            mask = calculate_box_mask(feature_pred, target, downsample_ratio)  # mask [B, H, W]

            feature_pred = feature_pred.permute(0, *range(2, len(feature_pred.shape)), 1)
            feature_target = feature_target.permute(0, *range(2, len(feature_target.shape)), 1)
            batch_size = int(feature_pred.shape[0])
            positives = feature_pred.new_ones(*feature_pred.shape[:3])
            positives = positives * torch.any(feature_target != 0, dim=-1).float()
            positives = positives * mask.cuda()

            reg_weights = positives.float()
            pos_normalizer = positives.sum().float()
            reg_weights /= pos_normalizer

            pos_inds = reg_weights > 0
            pos_feature_preds = feature_pred[pos_inds]
            pos_feature_targets = feature_target[pos_inds]

            imitation_loss_src = compute_imitation_loss(pos_feature_preds,
                                                          pos_feature_targets,
                                                          weights=reg_weights[pos_inds])  # [N, M]

            imitation_loss = imitation_loss_src.mean(-1)
            imitation_loss = imitation_loss.sum() / batch_size
            feature_ditill_loss = feature_ditill_loss + imitation_loss

    else:
        raise NotImplementedError

    return feature_ditill_loss

def compute_backbone_resize_affinity_loss(features_preds, features_targets):
    feature_ditill_loss = 0.0
    resize_shape = features_preds[-1].shape[-2:]
    if isinstance(features_preds, list):
        for i in range(len(features_preds)):  # 1/8   1/16   1/32
            feature_target = features_targets[i].detach()
            feature_pred = features_preds[i]

            B, C, H, W = feature_pred.shape
            feature_pred_down = F.interpolate(feature_pred, size=resize_shape, mode="bilinear")
            feature_target_down = F.interpolate(feature_target, size=resize_shape, mode="bilinear")

            feature_target_down = feature_target_down.reshape(B, C, -1)
            depth_affinity = torch.bmm(feature_target_down.permute(0, 2, 1), feature_target_down)

            feature_pred_down = feature_pred_down.reshape(B, C, -1)
            rgb_affinity = torch.bmm(feature_pred_down.permute(0, 2, 1), feature_pred_down)

            feature_ditill_loss = feature_ditill_loss + F.l1_loss(rgb_affinity, depth_affinity, reduction='mean') / B

    else:
        raise NotImplementedError

    return feature_ditill_loss

def compute_backbone_local_affinity_loss(features_preds, features_targets):
    feature_ditill_loss = 0.0
    local_shape = features_preds[-1].shape[-2:]
    if isinstance(features_preds, list):
        for i in range(len(features_preds)):  # 1/8   1/16   1/32
            feature_target = features_targets[i].detach()
            feature_pred = features_preds[i]

            B, _, H, W = feature_pred.shape
            feature_pred_q = rearrange(feature_pred, 'b c (h p1) (w p2) -> (b h w) (p1 p2) c', p1=local_shape[0], p2=local_shape[1])
            feature_pred_k = rearrange(feature_pred, 'b c (h p1) (w p2) -> (b h w) (p1 p2) c', p1=local_shape[0], p2=local_shape[1])

            rgb_affinity = einsum('b i d, b j d -> b i j', feature_pred_q, feature_pred_k)

            feature_target_q = rearrange(feature_target, 'b c (h p1) (w p2) -> (b h w) (p1 p2) c', p1=local_shape[0], p2=local_shape[1])
            feature_target_k = rearrange(feature_target, 'b c (h p1) (w p2) -> (b h w) (p1 p2) c', p1=local_shape[0], p2=local_shape[1])

            depth_affinity = einsum('b i d, b j d -> b i j', feature_target_q, feature_target_k)

            feature_ditill_loss = feature_ditill_loss + F.l1_loss(rgb_affinity, depth_affinity, reduction='mean') / B

    else:
        raise NotImplementedError

    return feature_ditill_loss

def calculate_box_mask(features_preds, target, downsample_ratio):
    B, C, H, W = features_preds.shape
    gt_mask = torch.zeros((B, H, W))

    for i in range(B):
        for j in range(target['obj_num'][i]):
            bbox2d_gt = target['box2d_gt'][i, j] / downsample_ratio

            left_top = bbox2d_gt[:2]
            right_bottom = bbox2d_gt[2:]

            left_top_x = int(left_top[0].item())
            left_top_y = int(left_top[1].item())

            right_bottom_x = int(right_bottom[0].item())
            right_bottom_y = int(right_bottom[1].item())

            gt_mask[i, left_top_y:right_bottom_y, left_top_x:right_bottom_x] = 1
    return gt_mask


"""DenseNet as encoder backbone.

Reference: https://arxiv.org/pdf/1608.06993.pdf
"""

import torch
from torch import nn
import numpy as np
import math

from training import CONFIGS_DIR, load_config

class DenseNet(nn.Module):

    @classmethod
    def from_config(cls, architecture_name, phase):
        """
        Args:
            phase (str): 'training' or 'deployment'
        """
        densenet_config = load_config(architecture_name+'.yaml')

        config = load_config('training.yaml') if phase=='training' else load_config('deployment.yaml')

        densenet_config.update(config)

        densenet_parameters = {**densenet_config}
        return DenseNet(**densenet_parameters)

    def __init__(self,
                 initial_conv_output_channels,
                 num_conv_blocks_per_stage,
                 output_channels_per_stage,
                 growth_rate_per_stage,
                 do_downsampling_per_stage,
                 provide_as_output_per_stage,
                 dropout_rate,
                 **extra_arguments):
        super().__init__()

        module_list = []
        block_input_channels = initial_conv_output_channels

        self.is_output_module = []

        for (num_conv_blocks,
             output_channels,
             growth_rate,
             do_downsampling,
             provide_as_output,) in zip(num_conv_blocks_per_stage,
                                        output_channels_per_stage,
                                        growth_rate_per_stage,
                                        do_downsampling_per_stage,
                                        provide_as_output_per_stage):

            # debug output
            # print('densenet stage in, out', block_input_channels, output_channels)

            dense_block = DenseBlock(input_channels=block_input_channels,
                                     num_conv_blocks=num_conv_blocks,
                                     growth_rate=growth_rate,
                                     activation='leaky_relu',
                                     dropout_rate=dropout_rate)

            module_list.append(dense_block)
            self.is_output_module.append(False)

            # debug output
            # print('denseblock out', dense_block.get_output_channels())

            transition_block = DenseTransitionBlock(input_channels=dense_block.get_output_channels(),
                                                    output_channels=output_channels)

            module_list.append(transition_block)
            self.is_output_module.append(True if provide_as_output else False)

            # downsampling

            if do_downsampling:
                downsampling = DenseDownsamplingBlock(input_channels=output_channels,
                                                      output_channels=output_channels)

                module_list.append(downsampling)
                self.is_output_module.append(False)

            block_input_channels = output_channels

        self.module_list = nn.ModuleList(module_list)

    def forward(self, x):
        outputs = []
        for module, provide_as_ouput in zip(self.module_list, self.is_output_module):
            x = module(x)

            if provide_as_ouput:
                outputs.append(x)

        # debug output
        # print('densenet all out:')
        # for output in outputs:
            # print('    * '+str(output.shape))

        return outputs

class DenseBlock(nn.Module):

    def __init__(self,
                 input_channels,
                 num_conv_blocks,
                 growth_rate,
                 activation,
                 dropout_rate):
        super().__init__()

        conv_blocks = []

        for conv_block_index in range(num_conv_blocks):
            conv_block = DenseConvBlockWithBottleneck(input_channels+conv_block_index*growth_rate,
                                                      growth_rate=growth_rate,
                                                      activation=activation,
                                                      dropout_rate=dropout_rate)
            conv_blocks.append(conv_block)

        self.conv_blocks = nn.ModuleList(conv_blocks)
        self.output_channels = input_channels+num_conv_blocks*growth_rate

    def get_output_channels(self):
        return self.output_channels

    def forward(self, x):
        block_outputs = [x]

        for conv_block_index, conv_block in enumerate(self.conv_blocks):
            x = torch.cat(block_outputs, dim=1)
            block_outputs.append(conv_block(x))

        # print('dense block all outputs so far:')
        # for output in block_outputs:
            # print('    * '+str(output.shape))

        final_output = torch.cat(block_outputs, dim=1)

        # print('final dense block out', final_output.shape)

        return final_output

class DenseConvBlockWithBottleneck(nn.Sequential):
    """
    A 1x1 and a 3x3 convolution combined. Denoted as DenseNet-B in the reference.
    """
    def __init__(self,
                 input_channels,
                 growth_rate,
                 activation,
                 dropout_rate):
        super().__init__()

        self.add_module('batch_norm_1', nn.BatchNorm2d(input_channels))

        if activation=='relu':
            self.add_module('relu_1', nn.ReLU())
        elif activation=='leaky_relu':
            self.add_module('leaky_relu_1', nn.LeakyReLU())
        elif activation is None or activation=='none':
            pass
        else:
            warnings.warn("Convolutional block with not-supported activation '{}'.".format(activation))

        self.add_module('conv_1', nn.Conv2d(input_channels,
                                            out_channels=4*growth_rate,
                                            kernel_size=1,
                                            stride=1,
                                            padding=0,
                                            bias=False))

        self.add_module('batch_norm_2', nn.BatchNorm2d(4*growth_rate))

        if activation=='relu':
            self.add_module('relu_2', nn.ReLU())
        elif activation=='leaky_relu':
            self.add_module('leaky_relu_2', nn.LeakyReLU())
        elif activation is None or activation=='none':
            pass
        else:
            warnings.warn("Convolutional block with not-supported activation '{}'.".format(activation))

        self.add_module('conv_2', nn.Conv2d(4*growth_rate,
                                            out_channels=growth_rate,
                                            kernel_size=3,
                                            stride=1,
                                            padding=1,
                                            bias=False))

        if dropout_rate is not None and dropout_rate>0.0:
            self.add_module('dropout', nn.Dropout2d(dropout_rate))

class DenseTransitionBlock(nn.Sequential):
    def __init__(self,
                 input_channels,
                 output_channels):
        super().__init__()

        self.add_module('batch_norm', nn.BatchNorm2d(input_channels))

        self.add_module('conv', nn.Conv2d(input_channels,
                                          out_channels=output_channels,
                                          kernel_size=1,
                                          stride=1,
                                          padding=0,
                                          bias=False))

class DenseDownsamplingBlock(nn.Sequential):
    """
    Note we use batch norm and a 3x3 convolution with stride 2 here instead
    of average pooling as in the reference.
    """
    def __init__(self,
                 input_channels,
                 output_channels):
        super().__init__()

        self.add_module('batch_norm', nn.BatchNorm2d(input_channels))

        self.add_module('conv', nn.Conv2d(input_channels,
                                          out_channels=output_channels,
                                          kernel_size=3,
                                          stride=2,
                                          padding=1,
                                          bias=False))


from game import Game
import pygame
from player import Player
import sys
from os import environ
from utility import black
from config import Config
from datetime import datetime

if __name__ == "__main__":

    num_games = 1
    games = []
    for i in range(num_games):
        games.append(Game())
    active_game = 0
    draw_all = False

    environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (30, 30)
    pygame.init()
    screen = pygame.display.set_mode((Config.field_width, Config.field_height))
    pygame.font.init()
    myfont = pygame.font.SysFont(Game.game_over_text_font, Game.game_over_text_size)
    screen.fill(0)
    frameend = datetime.now()
    frametimes = [0.001] * 101
    last_framerate_update = datetime.now()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    games[active_game].player_left.speed_y = - Config.player_speed
                elif event.key == pygame.K_s:
                    games[active_game].player_left.speed_y = Config.player_speed
                if event.key == pygame.K_UP:
                    games[active_game].player_right.speed_y = - Config.player_speed
                elif event.key == pygame.K_DOWN:
                    games[active_game].player_right.speed_y = Config.player_speed

                if event.key == pygame.K_RIGHT:
                    active_game += 1
                    active_game %= num_games
                elif event.key == pygame.K_LEFT:
                    active_game -= 1
                    active_game %= num_games

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    games[active_game].player_left.speed_y = 0
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    games[active_game].player_right.speed_y = 0

        screen.fill(black)
        for game in games:
            game.update_all()
            if draw_all:
                game.draw_all(screen)
        if not draw_all:
            games[active_game].draw_all(screen)

        pygame.display.update()
        if len(frametimes) > 100:
            frametimes = frametimes[-100:-1]

        frametimes.append((datetime.now() - frameend).total_seconds())
        frameend = datetime.now()
        if (datetime.now() - last_framerate_update).total_seconds() > 0.5:
            pygame.display.set_caption("Active game: %d/%d Player 1: %d Player 2: %d Framerate: %f" % (active_game+1,
                                                                                num_games,
                                                                         games[active_game].player_left.score,
                                                                         games[active_game].player_right.score,
                                                                         1/(sum(frametimes)/len(frametimes))))
            last_framerate_update = datetime.now()


import discord
import asyncio
import aiohttp
import os
import re
import random
import json

def parseReplys(reply):
    regex = r"\$\{([\w\ ]+)\}"
    parsed = reply
    matches = re.finditer(regex, reply, re.MULTILINE)
    if not matches:
        return parsed

    for i in matches:
        com = i.group(1).split()
        if com[0] == "rand":
            if len(com) >= 3:
                result = random.randint(int(com[1]), int(com[2]))
                parsed = parsed.replace(i.group(), str(result), 1)
        else:
            parsed = parsed.replace(i.group(), "\"ERROR\"")

    return parsed

async def asyncDereInfoSend(message, userID):
    async with aiohttp.ClientSession() as session:
        async with session.get("https://deresute.me/{}/json".format(userID)) as resp:
            userData = await resp.json()
            if "api_error" in userData:
                await message.channel.send("api error : " + str(userData["api_error"]))
            elif "name" in userData:
                await message.channel.send(userData["name"] + " " + str(userData["level"]) + " " + userData["comment"])
            else:
                await message.channel.send("Wrong response. Contact developer.")

class discordClient(discord.Client):
    async def on_ready(self):
        print("Bot logged on as", self.user)

    async def on_message(self, message):
        # We don't need to respond to ourselves
        if message.author == self.user:
            return

        splitedMessage = message.content.split(' ')
        # All commands start with mirei
        if (splitedMessage[0] == "mirei") & (len(splitedMessage) > 1):
            # For test ping
            if splitedMessage[1] == "test":
                await message.channel.send("test pong")
            # CGSS user info
            elif splitedMessage[1] == "info":
                # Process game info asyncronously to prevent programme from hogging
                async with message.channel.typing():
                    await asyncDereInfoSend(message, splitedMessage[2])
            else:
                if splitedMessage[1] in staticReplys:
                    if "image" in staticReplys[splitedMessage[1]]:
                        await message.channel.send(content = parseReplys(staticReplys[splitedMessage[1]]["reply"]),
                                                   file = discord.File(staticReplys[splitedMessage[1]]["image"]))
                    else:
                        await message.channel.send(parseReplys(staticReplys[splitedMessage[1]]["reply"]))
                else:
                    await message.channel.send("그런 거 없다")

try:
    with open("./staticReplys.json", 'r') as file:
        staticReplys = json.load(file)
        file.close()
except FileNotFoundError:
    print("Need to make staticReplys.json")
    raise SystemExit()

bot = discordClient()
bot.run(os.environ["DISCORDBOT_TOKEN"])


import requests

# Калсс содержит вызовы методов api сервиса, серилезовнные в методы класса
class Doge:
    base_url = "https://dog.ceo/api"

    def all_breeds(self):
        response = requests.get(f"{self.base_url}/breeds/list/all").json()
        print(response)
        if response.ok:
            return response
        else:
            return None

    def random_images(self, num):
        response = requests.get(f"{self.base_url}/breeds/image/random/{num}").json()
        print(response)
        if response.ok:
            return response
        else:
            return None

    def get_random(self):
        response = requests.get(f"{self.base_url}/breeds/image/random")
        print(response)
        if response.ok:
            return response
        else:
            return None

    def sub_breeds(self, name):
        response = requests.get(f"{self.base_url}/breed/{name}/list").json()
        print(response)
        if response.ok:
            return response
        else:
            return None