# The Traveling Salesman Problem consists of finding the shortest and longest paths along a set number of points (cities)
# The text file used consists of 1000 2D points seperated by a comma and space
# A random search, random mutation hill climber, and genetic algorithm were performed to find the results using the data

import numpy as np
import random as r
import matplotlib.pyplot as plt
import plotly.express as px

############# Defining the Random Search Function ####################
def random_search():
    pointsX = []          # initialising all our variables
    pointsY = []
    X = []
    Y = []
    iterations = []
    count = 0
    dist = 0
    ndist = 700
    tdist = []
    alldist = []

    file = open(r'C:\Users\Karol\Documents\Fall 2021 Semester\Evolutionary Algorithms & Automation\HW1\tsp.txt')   # reading file tsp.txt

    for i in file:
        row = i.split(', ')
        xcoord = float(row[0])
        ycoord = float(row[1])
        pointsX.append(xcoord)
        pointsY.append(ycoord)

    coord = list(zip(pointsX,pointsY))
    r.shuffle(coord)                   # random shuffling of the order of coordinates
    pointsX, pointsY = list(zip(*coord))
    length = len(coord)

    for i in range(0,50000):                  # setting number of iterations to 50000
        for i in range(0, length-1):

            xtemp1 = pointsX[i]
            ytemp1 = pointsY[i]

            if ((i+1)>(len(pointsX))):     # for closing the loop from last coordinates to first coordinates
                xtemp2 = pointsX[0]
                ytemp2 = pointsY[0]

            xtemp2 = pointsX[i+1]
            ytemp2 = pointsY[i+1]

            tempdist = np.sqrt((xtemp2-xtemp1)**2 +(ytemp2-ytemp1)**2) # calculating the distance between two consecutive points
            dist +=  tempdist

        iterations.append(count)
        count += 1

        if dist < ndist:
            ndist = dist
            tdist.append(dist)                  # collecting all the values of the distances calculated
            X, Y = pointsX, pointsY
            #print(dist)
        else:
            tdist.append(ndist)              # append shortest distance for plotting

        r.shuffle(coord)
        pointsX, pointsY = list(zip(*coord))

        dist = 0

    return X,Y,iterations,tdist,count

##################### Defining the Hill Climber Function ############################
def hill_climber():
    pointsX = []          # initialising all our variables
    pointsY = []
    iter = 50000
    X = []
    Y = []
    searches =  10
    iterations = []
    count = 0
    dist = 0
    ndist = 700
    tdist = []
    alldist = []
    new_distance = 0

    file = open(r'C:\Users\Karol\Documents\Fall 2021 Semester\Evolutionary Algorithms & Automation\HW1\tsp.txt')   # reading file tsp.txt

    for i in file:
        row = i.split(', ')
        xcoord = float(row[0])
        ycoord = float(row[1])
        pointsX.append(xcoord)
        pointsY.append(ycoord)

    coord = list(zip(pointsX,pointsY))
    r.shuffle(coord)                   # random shuffling of the order of coordinates
    pointsX, pointsY = list(zip(*coord))
    length = len(coord)

    pointsX = list(pointsX)
    pointsY = list(pointsY)

                 # setting number of iterations to 50000
    for i in range(0, length-1):

        xtemp1 = pointsX[i]
        ytemp1 = pointsY[i]

        if ((i+1)>(len(pointsX))):     # for closing the loop from last coordinates to first coordinates
            xtemp2 = pointsX[0]
            ytemp2 = pointsY[0]

        xtemp2 = pointsX[i+1]
        ytemp2 = pointsY[i+1]

        tempdist = np.sqrt((xtemp2-xtemp1)**2 +(ytemp2-ytemp1)**2) # calculating the distance between two consecutive points
        dist +=  tempdist

    print('Current distance: ', dist)
    #print(xpoints)
    distance_saved = dist

    while (count < iter):

        j = r.randrange(length)
        #print(x)
        swap1x = pointsX[j]
        swap1y = pointsY[j]

        if ((j+1) >= length):                        # If final point selected, use first point
            swap2x = pointsX[0]
            swap2y = pointsY[0]

            pointsX[j] = swap2x                         # swap 2 points
            pointsY[j] = swap2y

            pointsX[0] = swap1x
            pointsY[0] = swap1y
        else:
            swap2x = pointsX[j+1]
            swap2y = pointsY[j+1]

            pointsX[j] = swap2x                         # swap 2 points
            pointsY[j] = swap2y

            pointsX[j+1] = swap1x
            pointsY[j+1] = swap1y

        for i in range(0, length-1):                  # iterate through swapped path

            x1 = pointsX[i]
            y1 = pointsY[i]

            if ((i+1) >= length):                  # i is the last element
                x2 = pointsX[0]
                y2 = pointsY[0]
            else:
                x2 = pointsX[i+1]
                y2 = pointsY[i+1]

            new_path = np.sqrt((x2-x1)**2+(y2-y1)**2)            # take distance between points
            new_distance +=  new_path

        if distance_saved  < new_distance:                          # original path is shorter
            pointsX[j] = swap1x                              # undo the swap
            pointsY[j] = swap1y

            if ((j+1) >= length):                  # i is the last element
                pointsX[0] = swap2x
                pointsY[0] = swap2y
            else:
                pointsX[j+1] = swap2x
                pointsY[j+1] = swap2y

            X, Y = pointsX, pointsY
            tdist.append(distance_saved)

        else:
            distance_saved = new_distance
            tdist.append(distance_saved)
            X, Y = pointsX, pointsY

            #print(distance_saved)

        iterations.append(count)
        count += 1
        new_distance = 0

    return X,Y,iterations,tdist,count

################# Defining GA Function #####################
def genetic_algorithm():
    pointsX, pointsY = [], []          # initialising all our variables
    weightsparallel = []                        # population list of weights (list of lists)
    weightvalues = []
    keyvaluex, keyvaluey, keyvalue = [], [], []
    weightpopx, weightpopy, weightpop = [], [], []                      # list of dictionaries, having list of xvalues: weight for each individual
    weightedx, weightedy, weightedxpop, weightedypop = [], [], [], []
    population, indpop, childlist = [], [], []
    sortedx, sortedy, sortedxy = [], [], []
    indsortedx, indsortedy, indsortedxy, sortedxypop = [], [], [], []
    child, childpointsX, childpointsY, childpoints = [], [], [], []
    childrenX, childrenY = [], []
    even_numbers = []                       # counter for breeding
    xpop, ypop = [], []                     # x and y points of population
    X, Y = [], []                           # saved x,y lists for plotting
    even_numbers = []
    popcount = 10
    weightsum = 0

    iterations = []
    crossovercount = 1                   # number of crossovers (every 100 swaps)
    crossnum = 0
    iter = 50000
    count = 0
    dist = 0
    ndist = 700
    tdist = []
    alldist = []
    new_distance = 0

    file = open(r'C:\Users\Karol\Documents\Fall 2021 Semester\Evolutionary Algorithms & Automation\HW1\tsp.txt')   # reading file tsp.txt

    def distance(population, xpop, ypop, length):
        popdistances = []
        new_dist = 0
        indcount = 0
        count = 0
        for i in population:
            pointsX = xpop[indcount]
            pointsY = ypop[indcount]
            for x in range(0,length-1):

                xp1 = pointsX[x]
                yp1 = pointsY[x]

                xp1, yp1 = float(xp1), float(yp1)

                if (x+1) >= length:
                    xp2 = pointsX[0]
                    yp2 = pointsY[0]

                    xp2, yp2 = float(xp2), float(yp2)
                else:
                    xp2 = pointsX[x+1]
                    yp2 = pointsY[x+1]

                    xp2, yp2 = float(xp2), float(yp2)

                new_path = np.sqrt((xp2-xp1)**2+(yp2-yp1)**2)            # take distance between points
                new_dist +=  new_path

            popdistances.append(new_dist)
            count += 1
            new_dist = 0

            indcount += 1

        return popdistances

    def crossover(population, length):
        popcount = len(population)
        childpoints, childpointsX, childpointsY = [], [], []
        for i in range(0,popcount-1):                     # start at second solution, to allow breeding
            if i%2 == 1:
                continue
            #print(i)
            for x in range(int(length/4)):
                childpointsX.append(weightedxpop[i][x])  # starting at first parent, go back to first parent solution
                childpointsY.append(weightedypop[i][x])
                childpoint = str(weightedxpop[i][x]) + ' ' + str(weightedypop[i][x])
                childpoints.append(childpoint)

            for x in range(int(length*3/4),length):           # go from point 750 to 1000 in parent 1
                childpointsX.append(weightedxpop[i][x])
                childpointsY.append(weightedypop[i][x])
                childpoint = str(weightedxpop[i][x]) + ' ' + str(weightedypop[i][x])
                childpoints.append(childpoint)

            for x in sortedxypop[i+1]:                      # take points from parent 2 which aren't in child
                if x in childpoints:
                    continue
                else:
                    childpoints.append(x)
                    xp1, yp1 = x.split()
                    childpointsX.append(xp1)
                    childpointsY.append(yp1)

            population.append(childpoints)

            weightedxpop.append(childpointsX)
            weightedypop.append(childpointsY)

            childpointsX = []
            childpointsY = []
            childpoints = []
        return population

    for i in file:
        row = i.split(', ')
        xcoord = float(row[0])
        ycoord = float(row[1])
        pointsX.append(xcoord)
        pointsY.append(ycoord)

    length = len(pointsX)
    RSorder = list(zip(pointsX,pointsY))        # save original random search for order of points

    for x in range(length):
        keyvaluex.append(pointsX[x])
        keyvaluey.append(pointsY[x])
        coord = str(pointsX[x]) + ' ' + str(pointsY[x])
        keyvalue.append(coord)

    for i in range(popcount):
        coord = list(zip(pointsX,pointsY))     # pointsX,Y are never appended, dont have to reset
        r.shuffle(coord)                        # random shuffling of the order of coordinates
        pointsX, pointsY = list(zip(*coord))

        pointsX = list(pointsX)
        pointsY = list(pointsY)

        xpop.append(pointsX)                  # population x coordinates
        ypop.append(pointsY)

        coord = str(pointsX) + ' ' + str(pointsY)

        for i in range(0, length-1):
            xtemp1 = pointsX[i]
            ytemp1 = pointsY[i]

            coord = str(pointsX) + ' ' + str(pointsY)
            indpop.append(coord)

            weight = float("%.5f" % r.random())
            weightvalues.append(weight)

            if ((i+1)>(len(pointsX))):     # for closing the loop from last coordinates to first coordinates
                xtemp2 = pointsX[0]
                ytemp2 = pointsY[0]

            xtemp2 = pointsX[i+1]
            ytemp2 = pointsY[i+1]

            tempdist = np.sqrt((xtemp2-xtemp1)**2 +(ytemp2-ytemp1)**2) # calculating the distance between two consecutive points
            dist +=  tempdist

        coord = str(xtemp2) + ' ' + str(ytemp2)
        indpop.append(coord)

        population.append(indpop)

        indpop = []
        weight = float("%.5f" % r.random())     # add point for index 999
        weightvalues.append(weight)

        weightx = dict()
        weighty = dict()
        weights = dict()
        for i in range(length):
            weightx[keyvaluex[i]] = weightvalues[i]
            weighty[keyvaluey[i]] = weightvalues[i]
            weights[keyvalue[i]] = weightvalues[i]

        weightpopx.append(weightx)
        weightpopy.append(weighty)
        weightpop.append(weights)

    w = 0
    for x in weightpopx:
        weightpopx[w] = sorted(x.items(), key=lambda x: x[1])
        w += 1

    w = 0
    for x in weightpopy:
        weightpopy[w] = sorted(x.items(), key=lambda x: x[1])
        w += 1

    w = 0
    for x in weightpop:
        weightpop[w] = sorted(x.items(), key=lambda x: x[1])
        sortedxy.append(x.keys())
        w += 1

    # sort population by ascending weight

    for i in sortedxy:                          # extract key values (x,y coordinates) from population dictionary
        for e in i:
            indsortedxy.append(e)
            x,y = e.split()
            weightedx.append(x)
            weightedy.append(y)
            indsortedx.append(x)
            indsortedy.append(y)

        weightedxpop.append(weightedx)          # population x values in order of ascending weight
        weightedypop.append(weightedy)          # population y values in order of ascending weight
        sortedx.append(indsortedx)
        sortedy.append(indsortedy)
        sortedxypop.append(indsortedxy)

        weightedx = []
        weightedy = []
        indsortedx = []
        indsortedy = []
        indsortedxy = []

    for i in range(0,popcount-1):                     # start at second solution, to allow breeding
        if i%2 == 1:
            continue
        for x in range(int(length/4)):
            childpointsX.append(weightedxpop[i][x])  # starting at first parent, go back to first parent solution
            childpointsY.append(weightedypop[i][x])
            childpoint = str(weightedxpop[i][x]) + ' ' + str(weightedypop[i][x])
            childpoints.append(childpoint)

        for x in range(int(length*3/4),length):           # go from point 750 to 1000 in parent 1
            childpointsX.append(weightedxpop[i][x])
            childpointsY.append(weightedypop[i][x])
            childpoint = str(weightedxpop[i][x]) + ' ' + str(weightedypop[i][x])
            childpoints.append(childpoint)

        for x in sortedxypop[i+1]:                      # zip x and y points, compare child x and y points to parent x and y points
            if x in childpoints:
                continue
            else:
                childpoints.append(x)
                xp1, yp1 = x.split()
                childpointsX.append(xp1)
                childpointsY.append(yp1)

        childlist.append(childpoints)

        weightedxpop.append(childpointsX)
        weightedypop.append(childpointsY)

        childrenX.append(childpointsX)
        childrenY.append(childpointsY)
        child = list(zip(childpointsX, childpointsY))

        childpointsX = []
        childpointsY = []
        childpoints = []

    distance_saved = dist

    for i in range(0,len(childlist)):
        population.append(childlist[i])

    while crossnum < crossovercount:
        indcount = 0

        for i in population:
            while (count < iter):

                pointsX = xpop[indcount]
                pointsY = ypop[indcount]

                x = r.randrange(length)
                swap1x = pointsX[x]
                swap1y = pointsY[x]

                if ((x+1) >= length):                        # If final point selected, use first point
                    swap2x = pointsX[0]
                    swap2y = pointsY[0]

                    pointsX[x] = swap2x                         # swap 2 points
                    pointsY[x] = swap2y

                    pointsX[0] = swap1x
                    pointsY[0] = swap1y
                else:
                    swap2x = pointsX[x+1]
                    swap2y = pointsY[x+1]

                    pointsX[x] = swap2x                         # swap 2 points
                    pointsY[x] = swap2y

                    pointsX[x+1] = swap1x
                    pointsY[x+1] = swap1y

                for i in range(0, length-1):                  # iterate through swapped path

                    x1 = pointsX[i]
                    y1 = pointsY[i]

                    if ((i+1) >= length):                  # i is the last element
                        x2 = pointsX[0]
                        y2 = pointsY[0]
                    else:
                        x2 = pointsX[i+1]
                        y2 = pointsY[i+1]

                    new_path = np.sqrt((x2-x1)**2+(y2-y1)**2)            # take distance between points
                    new_distance +=  new_path

                if distance_saved  < new_distance:                          # original path is shorter
                    pointsX[x] = swap1x                              # undo the swap
                    pointsY[x] = swap1y

                    if ((x+1) >= length):                           # i is the last element
                        pointsX[0] = swap2x
                        pointsY[0] = swap2y
                    else:
                        pointsX[x+1] = swap2x
                        pointsY[x+1] = swap2y

                        X, Y = pointsX, pointsY
                        tdist.append(distance_saved)

                else:
                    distance_saved = new_distance
                    tdist.append(distance_saved)
                    X, Y = pointsX, pointsY

                # Change individual solution in population list
                newpoints = []
                for e in range(0,length):
                    xp = X[e]
                    yp = Y[e]
                    point = str(xp) + ' ' + str(yp)
                    newpoints.append(point)

                population[indcount] = newpoints[:]

                iterations.append(count)
                count += 1
                new_distance = 0
                dist = 0

                sorteddistances = []
                distorder = []
                indcounter = 0

                if count % 100 == 0:
                    popdistances = distance(population, weightedxpop, weightedypop, length)
                    sorteddistances = sorted(range(len(popdistances)), key=lambda k: popdistances[k])

                    for i in range(0, 5):
                        del population[int(sorteddistances[i])]

                    newpopulation = crossover(population, length)

            indcount += 1

        newdistances = []
        crossnum += 1

    print(distance_saved)

    missing = len(iterations) - len(tdist)

    for i in range(0,missing):
        tdist.append(distance_saved)

    return X,Y,iterations,tdist

####### Calling the Functions ##########
RS_X, RS_Y, RS_iterations, RS_tdist, count = random_search()
HC_X, HC_Y, HC_iterations, HC_tdist, count = hill_climber()
GA_X, GA_Y, GA_iterations, GA_tdist = genetic_algorithm()

#print(RS_iterations)
#print(HC_iterations)
print(count)

RS_yval = []
HC_yval = []
RS_stdss = []
HC_stdss = []
GA_yval = []
GA_stdss = []

############ Calculating the errors for each method ##############
for i in range(0,int(count/10)-1):
    RS_stdss.append(RS_tdist[i])

RS_std = np.std(RS_stdss)
print(RS_std)
RS_error = 50*(RS_std/(np.sqrt(count)))
print(RS_error)

xval = np.arange(0.1,count,count/10)
for i in range(count):
    if i % (count/10) == 0:
        RS_yval.append(RS_tdist[i])

HC_std = np.std(HC_tdist)
print(HC_std)
HC_error = 20*(HC_std/(np.sqrt(count)))
print(HC_error)
for i in range(count):
    if i % (count/10) == 0:
        HC_yval.append(HC_tdist[i])

for i in range(0,int(count/10)-1):
    GA_stdss.append(GA_tdist[i])

GA_std = np.std(GA_stdss)
print(GA_std)
GA_error = 20*(GA_std/(np.sqrt(count)))
print(GA_error)

for i in range(count):
    if i % (count/10) == 0:
        GA_yval.append(GA_tdist[i])

########### Plotting Graphs ################
plt.figure(1)             # plotting the graph of No. of Iterations vs The Values of calculated distances
plt.plot(RS_iterations,RS_tdist,label="RS")
plt.errorbar(xval,RS_yval,yerr=RS_error,linestyle='')
plt.plot(HC_iterations,HC_tdist,label="RMHC")
plt.errorbar(xval,HC_yval,yerr=HC_error,linestyle='')
plt.plot(GA_iterations,GA_tdist,label="GA")
plt.errorbar(xval,GA_yval,yerr=GA_error,linestyle='')
plt.title('No. of Iterations vs Distance Values')
plt.xlabel('Iterations')
plt.ylabel('Distance')
plt.legend()
plt.show()

RS_dot = px.scatter(x=RS_iterations,y=RS_tdist)   # random search dot plot
#RS_dot.show()

HC_dot = px.scatter(x=HC_iterations,y=HC_tdist)   # hill climber dot plot
#HC_dot.show()

GA_dot = px.scatter(x=GA_iterations,y=GA_tdist)
GA_dot.show()

###### plotting bar graph #######
RS_shortestdist = RS_tdist[-1]
HC_shortestdist = HC_tdist[-1]
GA_shortestdist = GA_tdist[-1]
x_bar = ["RS","HC","GA"]
y_bar = [RS_shortestdist,HC_shortestdist,GA_shortestdist]
bar_fig = plt.figure(figsize = (5,6))
plt.bar(x_bar,y_bar,width = 0.4)
plt.xlabel("Algorithms")
plt.ylabel("Shortest Distance Values")
plt.title("Shortest Distance Comparison")
plt.show()


# 템플릿과 데이터를 이용해 HTML 파일을 생성하는 render 포함
from django.shortcuts import render
from django.views import generic

# Create your views here.
# 뷰는 HTTP 요청을 처리하고, 데이터베이스에서 데이터를 가져오고,
# HTML 템플릿으로 데이터를 랜더링하고 생성된 HTML을 HTTP응답으로 반환하여 사용자들에게 보여주는 함수이다.
# (index 뷰는 이 구조(모델)을 따라간다
# index는 데이터베이스 안의 모델들의 레코드 개수 및 정보를 가져오고 그 정보를 템플릿으로 전달한다

from catalog.models import Book, Author, BookInstance, Genre
# 우리의 모든 뷰들 안에서 데이터에 접근하는데 필요한 모델 클래스 import

def index(request) :
    """사이트 홈페이지 보기 기능"""

    # 일부 주요 개체의 개수 생성
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()
    # 모델 클래스들에서 레코드들의 개수를 가져옴

    # 사용 가능한 책(상태)
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()
    # 상태 필드에서 'a'값을 가지는 BookInstance 객체들 목록도 가져옴

    # 'all()'은 기본적으로 내포되어 있다
    num_authors = Author.objects.count()

    context = {
        'num_books' : num_books,
        'num_instances' : num_instances,
        'num_instances_available' : num_instances_available,
        'num_authors' : num_authors,
    }

    # 컨텍스터 변수의 데이터를 사용하여 HTML 템플릿 index.html을 렌더링한다.
    return render(request, 'index.html', context=context)
    # render() : HTML 페이지 생성 및 페이지를 응답으로 반환하는 함수
    # render()의 매개변수들
    # request : HttpRequest인 원본 객체
    # 데이터에 대한 플레이스홀더들을 갖고 있는 HTML 템플릿
    # context

# books/ 링크로 들어오면 실행되는 모델
class BookListView(generic.ListView) :
    model = Book

    def get_queryset(self): # 정쟁이 포함된 책 5권 얻기
        return Book.objects.filter(title__icontains='war')[:5]

    def get_context_data(self, **kwargs):
        # 컨텍스트를 얻으려 기본 구현을 호출
        context = super(BookListView, self).get_context_data(**kwargs)
        # 데이터를 생성하고 컨텍스트에 추가
        context['some_data'] = 'This is just some data'
        return context


import cmd
import shlex
import inspect
import readline
import pynames
from pynames import GENDER, LANGUAGE

class Name_cmd(cmd.Cmd):
    prompt = '> '
    lang = 'native'

    def get_args(self, arg):  # распаковка аргументов и нужные параметры примерно одинаковые
        args = shlex.split(arg)
        if len(args) < 1 or len(args) > 3:
            print("From 1 to 3 arguments is required")
            return
        race = args[0]
        allowed_races = inspect.getmembers(pynames.generators)[1][1]  # просто нашел, что это-нужное место
        if not (race in allowed_races):
            print("Names for this race can not be generated")
            return
        gen_name, info, subrace = '', '', ''  # передача и пола и language в info одновременно не имеют смысла. Пусть будет одна переменная
        if len(args) > 1:
            if args[1] == 'male' or args[1] == 'female' or args[1] == 'language':
                info = args[1]
            else:
                subrace = args[1]
            if len(args) == 3:
                info = args[2]
        start_line = 'pynames.generators.' + race
        base = eval(start_line)
        members_list = inspect.getmembers(base)
        generator_name = [elem[0] for elem in members_list if
                          elem[0].endswith("Generator") and elem[0].startswith(subrace)
                          and elem[0] != 'FromListGenerator'][0]  # генератор из списка, которого у нас нет
        start_line += '.' + generator_name + '()'
        return eval(start_line), info

    def do_generate(self, arg):
        generator_object, gender = Name_cmd.get_args(self, arg)
        if not gender:  # по умолчанию
            gender = 'male'
        config_str = 'GENDER.' + gender.upper()
        if self.lang in generator_object.languages:
            config_str += ', LANGUAGE.' + self.lang.upper()
        print(generator_object.get_name_simple(*eval(config_str)))

    def do_info(self, arg):
        generator_object, parameter = Name_cmd.get_args(self, arg)
        if parameter == 'language':
            print(*(lang for lang in generator_object.languages), sep=', ')
        else:
            if parameter:
                gender_str = 'GENDER.' + parameter.upper()
                print(generator_object.get_names_number(eval(gender_str)))
            else:
                print(generator_object.get_names_number())

    def do_language(self, arg):
        if len(shlex.split(arg)) > 1:
            print("Impossible to set few languages")
        else:
            self.lang = arg.lower()  # проверка будет при вызове генераторов, а не здесь

    def do_exit(self, arg):
        return True

    def complete_language(self, prefix, allcomand, beg, end):
        return [s for s in ('RU', 'EN', 'NATIVE') if s.startswith(prefix.upper())]

    def complete_info(self, prefix, allcomand, beg, end):
        args = shlex.split(allcomand)
        if len(args) == 2:  # info и начало префикса:
            allowed_races = inspect.getmembers(pynames.generators)[1][1]
            return [s for s in allowed_races if s.startswith(prefix)]
        else:
            return [s for s in ('language', 'male', 'female') if s.startswith(prefix)]

    def complete_generate(self, prefix, allcomand, beg, end):
        args = shlex.split(allcomand)
        if len(args) == 2:  # generate и начало префикса:
            allowed_races = inspect.getmembers(pynames.generators)[1][1]
            return [s for s in allowed_races if s.startswith(prefix)]
        elif len(args) == 3:
            race = args[1]
            start_line = 'pynames.generators.' + race
            base = eval(start_line)
            members_list = [elem[0] for elem in inspect.getmembers(base) if
                            elem[0].endswith("Generator")
                            and elem[0] != 'FromListGenerator']
            suggestions_list = ['male', 'female'] + members_list
            return [elem for elem in suggestions_list if elem.startswith(prefix)]
        elif len(args) == 4:
            return [elem for elem in ('male', 'female') if elem.startswith(prefix)]

Name_cmd().cmdloop()


N, K = map(int,input().split())
grade = [0] * 7
gl = []
arr = [list(map(int,input().split())) for _ in range(N)]

Fe = []
Ma = []
Fer = [0] * 7
Mar = [0] * 7
for i in range(len(arr)):
    if arr[i][0] == 0:
        Fe.append(arr[i][1])

    else:
        Ma.append(arr[i][1])

for n in Fe:
    Fer[n] += 1
for m in Ma:
    Mar[m] += 1

cnt = 0
for _ in range(1001):
    for f in range(1,7):
        if Fer[f] > K:
            Fer[f] -= K
            cnt += 1
    for l in range(1,7):
        if Mar[l] > K:
            Mar[l] -= K
            cnt += 1

for s in range(1,7):
    if Fer[s] <= K and Fer[s] != 0:
        cnt += 1
    if Mar[s] <= K and Mar[s] != 0:
        cnt += 1

print(cnt)


import cv2

# OPENING WEBCAM
video = cv2.VideoCapture(0)
# OPENING FACE CASCADE XML FILE
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

while True:
    # CAPTURING VIDEO
    success, img = video.read()
    # CONVERTING ORIGINAL IMAGE TO GRAYSCALE
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # DETECTING FACES
    faces = face_cascade.detectMultiScale(img_gray, 1.1, 4)
    # CREATING A BOUNDING BOX AROUND DETECTED FACES
    for x, y, width, height in faces:
        cv2.rectangle(img, (x, y), (x+width, y+height), (0, 255, 0), 2)
    # DISPLAYING OUTPUT
    cv2.imshow('Video', img)
    cv2.waitKey(1)


from unittest import TestCase
from unittest.mock import patch
from unittest.mock import Mock, PropertyMock, MagicMock;

import sys

__author__ = 'Monster'

class TestContext(TestCase):

    def test_getController(self):
        bge = Mock()

        bge.logic.getCurrentController = Mock(return_value="controller")
        with patch.dict('sys.modules', {'bge': bge}):
            from mbge import context
            self.assertEqual(context.controller, "controller")

    def test_getOwner(self):
        bge = Mock()

        bge.logic.getCurrentController().owner = "owner"
        with patch.dict('sys.modules', {'bge': bge}):
            from mbge import context
            self.assertEqual(context.owner, "owner")

    def test_getScene(self):
        bge = Mock()

        bge.logic.getCurrentScene = Mock(return_value="scene")
        with patch.dict('sys.modules', {'bge': bge}):
            from mbge import context
            self.assertEqual(context.scene, "scene")

    def test_getScenes(self):
        bge = Mock()

        bge.logic.getSceneList = Mock(return_value="[scene]")
        with patch.dict('sys.modules', {'bge': bge}):
            from mbge import context
            self.assertEqual(context.scenes, "[scene]")

    def test_doc(self):
        bge = Mock()

        bge.logic.getSceneList = Mock(return_value="[scene]")
        with patch.dict('sys.modules', {'bge': bge}):
            from mbge import context
            print(dir(context))
            print(help(context))


#!/usr/bin/env python3

import dbxref.resolver
import requests
import logging
import json
import argparse

logger = logging.getLogger(__name__)

def main():
    """main()method for script usage"""
    # AVAILABLE for implementation:
    # 'go_terms', 'member_databases', 'integrated', 'entry_annotations', ''
    #
    # USED:
    # basics: 'accession', 'type', 'description', 'counters', 'entry_id', 'source_database', 'name'
    # hierarchy
    # wikipedia
    # literature
    # cross_references
    # overlaps_with

    parser = argparse.ArgumentParser(description="Retrieve InterPro documents and convert them into json")
    parser.add_argument("--basics", "-b", action="store_true", help="Include basic information such as accession, "
                                                                    "type, name, description, counters, entry_id and "
                                                                    "source_database")
    parser.add_argument("--hierarchy", "-hi", action="store_true", help="")
    parser.add_argument("--wikipedia", "-w", action="store_true", help="")
    parser.add_argument("--literature", "-l", action="store_true", help="")
    parser.add_argument("--cross_references", "-cr", action="store_true", help="")
    parser.add_argument("--overlaps", "-o", action="store_true", help="")
    parser.add_argument("dbxrefs", nargs=argparse.REMAINDER)
    args = parser.parse_args()

    # if nothing specified, output all available information for the entry
    if None not in (args.basics, args.hierarchy, args.wikipedia, args.literature, args.cross_references, args.overlaps):
        args.basics = True
        args.hierarchy = True
        args.wikipedia = True
        args.literature = True
        args.cross_references = True
        args.overlaps = True

    dbxrefs = dbxref.resolver.convert_to_dbxrefs(args.dbxrefs)

    documents = retrieve(dbxrefs, basics=args.basics, hierarchy=args.hierarchy, wikipedia=args.wikipedia,
                         literature=args.literature, cross_references=args.cross_references, overlaps=args.overlaps)
    print(json.dumps(documents, sort_keys=True, indent=4))

def retrieve(dbxrefs, basics=True, hierarchy=True, wikipedia=True, literature=True, cross_references=True, overlaps=True):
    """Retrieve json document from InterPro REST api, filter information by selected Options and parse into new json"""
    resolved = dbxref.resolver.resolve(dbxrefs, check_existence=False)
    documents = []
    for entry in resolved:
        # Construct URL for retrieve
        json_url = entry['locations']['json'][0]
        logger.debug('URL: %s', json_url)
        r = requests.get(json_url)
        logger.debug('Content: %s', r.text)
        ipro = json.loads(r.text)

        # Parse retrieved json file by selected Options
        output = {"id": entry["dbxref"]}
        if basics:
            try:
                output.update(accession=ipro["metadata"]["accession"], entry_type=ipro["metadata"]["type"],
                              description=ipro["metadata"]["description"], counters=ipro["metadata"]["counters"],
                              entry_id=ipro["metadata"]["entry_id"], name=ipro["metadata"]["name"],
                              source_database=ipro["metadata"]["source_database"])
            except KeyError:
                logger.warning("One or more basic information were not available for the given entry. Please check your output.")
        if hierarchy:
            try:
                output.update(hierarchy=ipro["metadata"]["hierarchy"])
            except KeyError:
                logger.warning("Hierarchy information was not available for the given entry.")
        if wikipedia:
            try:
                output.update(wikipedia=ipro["metadata"]["wikipedia"])
            except KeyError:
                logger.warning("Wikipedia articles were not available for the given entry.")
        if literature:
            try:
                output.update(literature=ipro["metadata"]["literature"])
            except KeyError:
                logger.warning("Literature was not available for the given entry.")
        if cross_references:
            try:
                output.update(cross_references=ipro["metadata"]["cross_references"])
            except KeyError:
                logger.warning("Cross_references were not available for the given entry.")
        if overlaps:
            try:
                output.update(overlaps=ipro["metadata"]["overlaps_with"])
            except KeyError:
                logger.warning("Overlap information was not available for the given entry.")
        documents.append(output)
    return documents

if __name__ == "__main__":
    main()


import json
import os
import shutil
from sentinel_dataset._utils import parse_eodata_folder_name
from sentinel_data_preparation.data_preparation import DataPreparation

#Input data are level-1
config = {
    "sensor": "sentinel-2",
    "eocloud_path_list": "example_eodata_l1.txt",
    "rad_cor": "toa",
    "resolution": "10m",
    "bands": ["b02", "b03", "b04", "b08",  # 10m
              "b05", "b06", "b07", "b8a", "b11", "b12",  # 20m
              "b01", "b09","b10"],  # 60m
    "process_clouds": "yes",
    "process_target_data": "no",
    "outdir": 'data/',
    'tile_ids':["T29SQB","T29SQC","T30STJ","T29TPE","T30SUJ","T32TMP","T32TNS","T32TNP","T32TPR","T32TML","T32TMK","T32TNT","T32UPU","T32TPT","T32UQU","T32UNU","T32TMN","T32TMM"]
}

s2_dp = DataPreparation(config)
s2_dp.run_all()

#For atmospheric coreection we wil use Level-2 data as labels
config = {
    "sensor": "sentinel-2",
    "eocloud_path_list": "example_eodata_l2.txt",
    "rad_cor": "toa",
    "resolution": "10m",
    "bands": ["b02", "b03", "b04", "b08",  # 10m
              "b05", "b06", "b07", "b8a", "b11", "b12",  # 20m
              "b01", "b09"],  # 60m
    "process_clouds": "no",
    "process_target_data": "no",
    "outdir": 'data_atm_corr/',
    'tile_ids':["T32TMP","T32TNS","T32TNP","T32TPR","T32TML","T32TMK","T32TNT","T32UPU","T32TPT","T32UQU","T32UNU","T32TMN","T32TMM"]
}

s2_dp = DataPreparation(config)
s2_dp.run_all()

#Move amtospheric corrected data into the data-folder to act as labels
def use_atm_corr_data_as_labels(atm_corr_dir, out_dir, delete_atm_corr_dir = False):

    for dir, dirnames, filenames in os.walk(atm_corr_dir):
        for filename in filenames:
            if 'data_b' in filename:
                src = os.path.join(dir, filename)

                atm_corr_properties = parse_eodata_folder_name(dir.split('/')[-1])
                date_atm_corr = str(atm_corr_properties['datetime']).replace('-','').replace(':','')

                #find corresponding output-folder
                for outdir, _, _ in os.walk(out_dir):
                    if date_atm_corr in outdir:
                        out_properties = parse_eodata_folder_name(outdir.split('/')[-1])
                        if atm_corr_properties['tile_id']==out_properties['tile_id']:
                            dest = os.path.join(outdir, filename.replace(atm_corr_dir, '')).replace('/data_b', '/lbl_b')  # Rename data as labels
                            print('Moving', src, 'to', dest)
                            shutil.move(src,dest)

        if delete_atm_corr_dir:
            shutil.rmtree(atm_corr_dir)

use_atm_corr_data_as_labels('data_atm_corr/','data/')

##


"""
The below program get/input data from a excel sheet and will write/print the unique data on text document.
"""
import openpyxl as op
import os

drive = "" #! Please enter the drive path.
geo_input_file = "" #! Please enter the input file name.
geo_output_file = "" #! Please enter the output file name.

geo_input_path = drive + geo_input_file
geo_output_path = drive + geo_output_file

# * Loading all the district from geolocation excelsheet.

geolocation_city = []
wb1 = op.load_workbook(geo_input_path)
ws1 = wb1.get_sheet_by_name("Sheet1")
rm1 = ws1.max_row
for loc in range(2, (rm1 + 1)):
    geo_cit = ws1.cell(row = loc, column = 1).value
    if geo_cit not in geolocation_city:
        geolocation_city.append(geo_cit)
        output = open(geo_output_path, 'a')
        output.write(geo_cit + "\n")
        output.close()
print("All Done")

excelWork/geolocation city import and export.py


import sys
sys.setrecursionlimit(10**6)
class Solution():
    """_summary_

        1. You are given a number n, representing the count of elements.
        2. You are given n numbers.
        3. You are given a number "tar".
        4. Complete the body of printTargetSumSubsets function - without changing signature - to calculate and print all subsets of given elements, the contents of which sum to "tar". Use sample input and output to get more idea.
        Note -> The online judge can't force you to write the function recursively but that is what the spirit of question is. Write recursive and not iterative logic. The purpose of the question is to aid learning recursion and not test you.
    """

    def targetSum(self, arr, idx , target , sos,ans:list):
        if idx==len(arr):
            if sos==target:
                print(ans+".")
            return

        self.targetSum(arr,idx+1,target ,sos+arr[idx] , ans+str(arr[idx])+",")
        self.targetSum(arr,idx+1,target,sos,ans)

arr = [int(input()) for _ in range(int(input()))]
target = int(input())

Solution().targetSum(arr, 0, target ,0 , "")


import csv

responseFromClient = "20158511"

with open('data.csv', 'r') as csvFile:
    reader = csv.reader(csvFile)
    rows = []
    flag = 0
    for row in reader:
         # print(row)
         rows.append(row)
        # print(col[0]
    # print(rows)
    for i in range (len(rows)):
        # k = i
        for j in range(0,3):
            m = j
            print(rows[i][j])
    #         if(rows[i][j] == responseFromClient):
    #             print(rows[i][m + 1])
    #             flag = 1
    # if(flag == 0):
    #     print("arey pp roll number chusko sarigga")
csvFile.close()


from io import BytesIO
from PIL import Image as Img
import cv2 as cv

import matplotlib.image as mpimg

if __name__ == '__main__':

    imagefile = mpimg.imread(
        'C:\\Users\\alyona\\Documents\\cloud\\cloud_app\\FV000046.jpg')

    gray = cv.cvtColor(imagefile, cv.COLOR_BGR2GRAY)

    cascade_path = r'' + cv.data.haarcascades + "haarcascade_frontalface_default.xml"

    face_cascade = cv.CascadeClassifier(cascade_path)
    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor=1.3,
        minNeighbors=3,
        minSize=(30, 30)
    )

    print("[INFO] Found {0} Faces.".format(len(faces)))

    for (x, y, w, h) in faces:
        cv.rectangle(imagefile, (x, y), (x + w, y + h), (0, 255, 0), 2)
        roi_color = imagefile[y:y + h, x:x + w]
        print("[INFO] Object found. Saving locally.")
        roi_to_save = cv.cvtColor(roi_color, cv.COLOR_BGR2RGB)
        cv.imwrite(str(w) + '_' + str(h) + '_faces.jpg', roi_to_save)

        image = cv.cvtColor(roi_color, cv.COLOR_BGR2RGB)
        img_crop_pil = Img.fromarray(image)
        byte_io = BytesIO()
        img_crop_pil.save(byte_io, 'jpeg')
        jpg_buffer = byte_io.getvalue()
        byte_io.seek(0)

    imagefile_to_save = cv.cvtColor(imagefile, cv.COLOR_BGR2RGB)
    status = cv.imwrite('faces_detected.jpg', imagefile_to_save)
    print("[INFO] Image faces_detected.jpg written to filesystem: ", status)


import pytest

from autovirt.domain.shopboard import ShopBoard, ShopBoardItem

shopboard_data = [
    (0, 100, 100, 100, 123),
    (1, 150, 200, 350, 123),
    (2, 200, 2000, 10000, 123),
]

@pytest.fixture
def products():
    return [
        ShopBoardItem(
            unit_id=item[0],
            sales_volume=item[1],
            purchased_amount=item[2],
            quantity=item[3],
            goods_category_id=item[4],
        )
        for item in shopboard_data
    ]

def test_empty_shopboard_returns_no_excess_products():
    sb = ShopBoard()
    assert not sb.get_excess_products()

def test_init_with_products_list(products):
    sb = ShopBoard(products)
    assert len(sb) == len(products)

def test_get_excess_products(products):
    sb = ShopBoard(products)
    excess_products = sb.get_excess_products(multiplier=2)
    assert products[1] in excess_products
    assert products[2] in excess_products
    assert sb.get_excess_products(multiplier=3) == [products[2]]


"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
Return false.
"""
class Solution:
    def isBalanced(self, root: 'TreeNode') -> 'bool':
        self.maxHeightDiff = 0
        self.getHeight(root)
        if self.maxHeightDiff > 1:
            return False
        else:
            return True
    def getHeight(self, root):
        if not root:
            return 0
        leftHeight = self.getHeight(root.left)
        rightHeight = self.getHeight(root.right)
        curHeightDiff = abs(leftHeight - rightHeight)
        if curHeightDiff > self.maxHeightDiff:
            self.maxHeightDiff = curHeightDiff
        return max(leftHeight, rightHeight) + 1

Python/easy/110. Balanced Binary Tree.py


import os

def data_calc_size(size):
    """
    Return a friendly data size unit and float tuple
    e.g.
        12345   -> 12.345 KB
        1234567 -> 1.235 MB
    """
    base = 1024
    progression = ["B", "KB", "MB", "GB", "TB", "PB"]  # ...
    unit = 0
    base_exponent = 0
    while True:
        calced = size / (base ** base_exponent)
        if calced < base:
            return (round(calced, 3), progression[unit], )
        else:
            base_exponent += 1
            unit += 1

def data_size_format(size):
    return "{} {}".format(*data_calc_size(size))

jinja_filters = dict(id=id,
                     repr=repr,
                     len=len,
                     pathjoin=lambda x: os.path.join(*x),
                     commafy=lambda x: format(x, ',d'),
                     data=data_size_format)


verif = True

matriz_alumnos = []
matriz_aux = []
while verif:
    print("Ingrese el número de la operación que desea ejecutar:")
    print("1 - Ver la lista de alumnos.")
    print("2 - Añadir un alumno a la lista.")
    print("3 - Salir.")
    try:
        selection = int(input(""))
    except ValueError:
        selection = 4

    if selection == 1:
        for alumnos in matriz_alumnos:
            print(f"{alumnos[0].title()} - {alumnos[1]} cursos")

    elif selection == 2:
        matriz_aux = []
        alumno = input("Ingrese el nombre del alumno: ")
        curso = input("Ingrese la cantidad de cursos: ")
        if alumno == "" or curso == "":
            print("Error el nombre o curso invalido")
        else:
            matriz_aux.append(alumno)
            matriz_aux.append(curso)
            matriz_alumnos.append(matriz_aux)

    elif selection == 3:
        print("¡Gracias por utilizar el programa!")
        verif = False
    else:
        print("La opción ingresada no es correcta, vuelva a intentarlo.")


"""
Irj programot, mely beker egy egesz szamot: n. Feltetelezhetjuk, hogy ez pozitiv.

Ezt kovetoen kerjen be egesz szamokat addig, amig n db nemnegativ szamot nem kapott.
A program a futasa vegen irja ki egy listaban ezeket a szamokat.

Pelda bemenet:
3
1
2
3
Pelda kimenet:
[1, 2, 3]

Pelda bemenet:
3
-1
0
-44
35
-19
-35
1
Pelda kimenet:
[0, 35, 1]

"""

n = int(input())
poz = 0
t = []
while poz < n:
    a = int(input())
    if a >= 0:
        poz +=1
        t.append(a)

print(t)


"""
Given a string s, find the length of the longest substring without repeating characters.
"""
from collections import defaultdict

class Solution:
    # O(n^2)
    def lengthOfLongestSubstring(self, s: str) -> int:
        maximum = 0
        for i in range(0, len(s)):
            chars = set()
            for j in range(i, len(s)):
                if s[j] in chars:
                    break
                else:
                    maximum = max(maximum, j-i+1)
                    chars.add(s[j])
        return maximum

    # O(n)
    def lengthOfLongestSubstring(self, s: str) -> int:
        d  = defaultdict(lambda:-1)
        i = 0 # Index of last char that is repeated now
        result = 0 # Max Length os Substring
        for index in range(len(s)):
            i = max(i, d[s[index]]+1)
            result = max(result, index-i+1)
            d[s[index]] = index
        return result


from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QPushButton, QLabel, QComboBox, QCheckBox, QTableWidget, QTableWidgetItem
from PyQt5.QtWidgets import QLineEdit, QDateEdit, QTimeEdit
from PyQt5.QtCore import QDate, QTime, QSize
from PyQt5.QtGui import QIcon, QFont
from gui_atividades import *
import sys

class WindowAudiencias(QWidget):

    def __init__(self, db, parent=None):
        super(WindowAudiencias, self).__init__(parent)
        self.db = db
        self.setWindowIcon(QIcon("static/logo.ico"))
        self.setWindowTitle("Audiências do Tribunal de Justiça")
        self.resize(800, 600)
        self.filtered_date = False
        self.filtered_vara = False

        # buttons
        x_btn = 600
        y_btn_gap = 20
        y_btn_step = 50

        self.btn_font = QFont()
        self.btn_font.setBold(True)
        self.btn_font.setPixelSize(12)

        def create_button(window, on_click, text, tip, pos):
            button = QPushButton(text, window)
            button.setToolTip(tip)
            button.move(x_btn, y_btn_gap + y_btn_step * pos)
            button.clicked.connect(on_click)
            button.resize(150, 40)
            button.setFont(self.btn_font)
            return button

        self.btn_insert_audiencia = create_button(self, self.on_click_insert_audiencia,
            'Inserir Audiência', 'Criar uma nova Audiência no banco de dados.', 0)
        self.btn_update_audiencia = create_button(self, self.on_click_update_audiencia,
            'Atualizar Audiência', 'Atualizar uma Audiência do banco de dados.', 1)
        self.btn_delete_audiencia = create_button(self, self.on_click_delete_audiencia,
            'Remover Audiência', 'Remover uma Audiência do banco de dados.', 2)
        self.btn_atividades = create_button(self, self.on_click_open_atividades,
            'Atividades Audiência', 'Abrir a janela de atividades da Audiência.', 3)

        # filter buttons
        def create_filter_button(window, on_click, icon, tip, x):
            filter_button = create_button(window, on_click, '', tip, 3.5)
            filter_button.setIcon(QIcon('./static/{}'.format(icon)))
            filter_button.resize(40, 40)
            filter_button.move(x, y_btn_gap + y_btn_step * 3.5)
            filter_button.setIconSize(QSize(30, 30) )
            return filter_button

        self.btn_filter_vara = create_filter_button(self, self.on_click_filter_vara,
            'filter_vara.png', 'Filtrar Audiências pela Vara.', 300)
        self.btn_filter_date = create_filter_button(self, self.on_click_filter_date,
            'filter_data.png', 'Filtrar Audiências por data da Audiência.', 350)
        self.btn_remove_filter_date = create_filter_button(self, self.on_click_remove_filters,
            'rm_filter.png', 'Remover filtros das Audiências.', 400)

        # labels
        def create_label(window, text, x, pos):
            label = QLabel(window)
            label.setText(text)
            y_gap = 20
            y_step = 50
            label.move(x, y_gap + pos * y_step)
            return label

        x_in_1 = 50
        x_in_2 = 220

        create_label(self, 'Vara', x_in_1, 0)
        create_label(self, 'Processo', x_in_1, 1)
        create_label(self, 'Tipo', x_in_1, 2)
        create_label(self, 'Audiências', x_in_1, 4)

        create_label(self, 'Horário', x_in_2, 0)
        create_label(self, 'Data Audiência', x_in_2, 1)
        create_label(self, 'Data Despacho', x_in_2, 2)

        # line edit
        y_gap = 37
        y_step = 50

        def create_line_edit(window, x, pos):
            line_edit = QLineEdit(window)
            line_edit.move(x, y_gap + pos * y_step)
            line_edit.resize(150, 24)
            return line_edit

        self.line_processo = create_line_edit(self, x_in_1, 1)

        # date edit
        def create_date_edit(window, x, pos):
            date_edit = QDateEdit(self)
            date_edit.move(x, y_gap + pos * y_step)
            date_edit.resize(150, 24)
            return date_edit

        self.date_data_audiencia = create_date_edit(self, x_in_2, 1)
        self.date_data_despacho = create_date_edit(self, x_in_2, 2)

        # time edit
        self.time_horario = QTimeEdit(self)
        self.time_horario.move(x_in_2, y_gap + 0 * y_step)
        self.time_horario.resize(150, 24)

        # combo-box
        def create_cb(window, list_items, x, pos):
            combo_box = QComboBox(window)
            combo_box.addItems(list_items)
            combo_box.move(x, y_gap + pos * y_step)
            combo_box.resize(150, 24)
            return combo_box

        self.cb_vara = create_cb(self, ["1", "2"], x_in_1, 0)
        self.cb_tipo = create_cb(self, ["Instrução e Julgamento", "Oitiva", "Interrogatório", "Depoimento Especial", "UNA", "Continuação", "Carta Precatória"], x_in_1, 2)

        # check-box
        self.ck_urgente = QCheckBox("Urgente", self)
        self.ck_urgente.move(x_in_1, y_gap-17 + 3 * y_step)

        # table
        self.table_audiencias = QTableWidget(self)
        self.table_audiencias.move(50, 240)
        self.table_audiencias.resize(700, 300)
        self.table_audiencias.itemSelectionChanged.connect(self.table_audiencias_select)
        self.set_table_audiencias_content(self.filtered_date, self.filtered_vara)

    # table functions
    def set_table_audiencias_content(self, filtered_date, filtered_vara):
        audiencias = self.db.get_audiencias()
        self.table_audiencias.clear()

        headers = list(self.db.get_audiencia_columns())
        n_rows = len(audiencias)
        self.table_audiencias.setRowCount(n_rows)
        if (n_rows <= 0):
            return

        self.table_audiencias.setColumnCount(len(audiencias[0]))
        self.table_audiencias.setHorizontalHeaderLabels(headers)

        ignored_rows = []
        for row, record in enumerate(audiencias):
            ignore_row = False
            for column, content in enumerate(record):
                self.table_audiencias.setItem(row, column, QTableWidgetItem(content))

                if (filtered_date):
                    if (headers[column] == 'data_audiencia' and content != self.get_date_data_audiencia()):
                        if (row not in ignored_rows):
                            ignored_rows.append(row)

                if (filtered_vara):
                    if (headers[column] == 'vara' and content != self.get_cb_vara()):
                        if (row not in ignored_rows):
                            ignored_rows.append(row)

        for i, row in enumerate(ignored_rows):
            self.table_audiencias.removeRow(row-i)

    def table_audiencias_select(self):
        currentRow = self.table_audiencias.currentRow()
        self.table_audiencias.selectRow(currentRow)

        vara_index = self.cb_vara.findText(self.table_audiencias.item(currentRow, 0).text())
        self.cb_vara.setCurrentIndex(vara_index)

        tipo_index = self.cb_tipo.findText(self.table_audiencias.item(currentRow, 2).text())
        self.cb_tipo.setCurrentIndex(tipo_index)

        status_urgente = self.table_audiencias.item(currentRow, 3).text()
        status_urgente = 2 if status_urgente == 'Sim' else 0
        self.ck_urgente.setCheckState(status_urgente)

        txt_horario = self.table_audiencias.item(currentRow, 4).text()
        self.time_horario.setTime(self.transform_to_qtime(txt_horario))

        select_processo = self.table_audiencias.item(currentRow, 1)
        select_data_audiencia = self.table_audiencias.item(currentRow, 5)

        if (select_processo and select_data_audiencia):
            select_processo = select_processo.text()
            self.line_processo.setText(select_processo)

            date_to_set = self.transform_to_qdate(select_data_audiencia.text())
            self.date_data_audiencia.setDate(date_to_set)

        select_data_despacho = self.table_audiencias.item(currentRow, 6)
        if (select_data_despacho):
            date_to_set = self.transform_to_qdate(select_data_despacho.text())
            self.date_data_despacho.setDate(date_to_set)

    # get data functions
    def transform_to_qdate(self, date_str):
        date_list = date_str.split('/')
        return QDate(int(date_list[2]), int(date_list[1]), int(date_list[0]))

    def transform_to_qtime(self, time_str):
        time_list = time_str.split(':')
        return QTime(int(time_list[0]), int(time_list[1]))

    def get_ck_urgente(self):
        return self.ck_urgente.checkState()

    def get_cb_vara(self):
        return self.cb_vara.currentText()

    def get_cb_tipo(self):
        return self.cb_tipo.currentText()

    def get_line_processo(self):
        return self.line_processo.text()

    def get_time_horario(self):
        return self.time_horario.text()

    def get_date_data_audiencia(self):
        return self.date_data_audiencia.text()

    def get_date_data_despacho(self):
        return self.date_data_despacho.text()

    # button functions
    def on_click_filter_date(self):
        self.filtered_date = True
        self.set_table_audiencias_content(self.filtered_date, self.filtered_vara)

    def on_click_filter_vara(self):
        self.filtered_vara = True
        self.set_table_audiencias_content(self.filtered_date, self.filtered_vara)

    def on_click_remove_filters(self):
        self.filtered_date = False
        self.filtered_vara = False
        self.set_table_audiencias_content(self.filtered_date, self.filtered_vara)

    def on_click_insert_audiencia(self):
        self.db.insert_audiencia(vara=self.get_cb_vara(),
                                 processo=self.get_line_processo(),
                                 tipo=self.get_cb_tipo(),
                                 urgente=self.get_ck_urgente(),
                                 horario=self.get_time_horario(),
                                 data_audiencia=self.get_date_data_audiencia(),
                                 data_despacho=self.get_date_data_despacho())
        self.set_table_audiencias_content(self.filtered_date, self.filtered_vara)

    def on_click_delete_audiencia(self):
        currentRow = self.table_audiencias.currentRow()
        drop_processo = self.table_audiencias.item(currentRow, 1)
        drop_data_audiencia = self.table_audiencias.item(currentRow, 5)

        if (drop_processo and drop_data_audiencia):
            drop_processo = drop_processo.text()
            drop_data_audiencia = drop_data_audiencia.text()
            self.db.delete_audiencia(drop_processo, drop_data_audiencia)

            print('Audiência removida do banco de dados.')
            self.set_table_audiencias_content(self.filtered_date, self.filtered_vara)

    def on_click_update_audiencia(self):
        currentRow = self.table_audiencias.currentRow()
        update_processo = self.table_audiencias.item(currentRow, 1)
        update_data_audiencia = self.table_audiencias.item(currentRow, 5)

        if (update_processo and update_data_audiencia):
            update_processo = update_processo.text()
            update_data_audiencia = update_data_audiencia.text()
            self.db.update_audiencia(vara=self.get_cb_vara(),
                                     processo=update_processo,
                                     tipo=self.get_cb_tipo(),
                                     urgente=self.get_ck_urgente(),
                                     horario=self.get_time_horario(),
                                     data_audiencia=update_data_audiencia,
                                     data_despacho=self.get_date_data_despacho())
            self.set_table_audiencias_content(self.filtered_date, self.filtered_vara)

    def on_click_open_atividades(self):
        use_processo = self.get_line_processo()
        use_data_audiencia = self.get_date_data_audiencia()

        if (len(use_processo) != 13 or len(use_data_audiencia) != 10):
            print('Audiência selecionada é inválida.')
        else:
            self.windowAtividades = WindowAtividades(self.db, use_processo, use_data_audiencia, self.get_cb_vara())
            self.windowAtividades.show()


from bs4 import BeautifulSoup
import requests
import numpy as np
import csv
from datetime import datetime

print("Welcome to the eBay Price Tracker!")
print("Enter an eBay link to find the average price for the product! ")
LINK = input("Input here: ")

def get_prices_by_link(link):
    r = requests.get(link)
    page_parse = BeautifulSoup(r.text, 'html.parser')
    search_results = page_parse.find("ul", {"class": "srp-results"}).find_all("li", {"class": "s-item"})
    item_prices = []

    for result in search_results:
        price_as_text = result.find("span", {"class": "s-item__price"}).text
        if "to" in price_as_text:
            continue
        price = float(price_as_text[1:].replace(",", ""))
        item_prices.append(price)
    return item_prices

def getProductName(link):
    r = requests.get(link)
    page_parse = BeautifulSoup(r.text, 'html.parser')
    input_tag = page_parse.find("input", {"class": "gh-tb ui-autocomplete-input"})
    product_name = input_tag["value"]
    return product_name

def remove_outliers(prices, m=2):
    data = np.array(prices)
    return data[abs(data - np.mean(data)) < m * np.std(data)]

def get_avg(prices):
    return np.mean(prices)

def save_to_file(prices):
    fields = ["Date: "+datetime.today().strftime("%d-%m-%y"),
              "Product name: "+getProductName(LINK),
              "Average price: "+str(np.around(get_avg(prices), 2))]
    with open('prices.csv', 'a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(fields)

if __name__ == "__main__":
    prices = get_prices_by_link(LINK)
    without_outliers = remove_outliers(prices)
    print("Product name: "+getProductName(LINK))
    print("Average Price: "+str(np.around(get_avg(without_outliers), 2)))
    save_to_file(without_outliers)


import sys
import heapq as hq
sys.stdin = open("C:\\Users\\82103\\pythonprogramming\\baekjoon\\input.txt","rt")

n = int(input())
if n==1:
    print(0)
    sys.exit(0)
L=[]
for i in range(n):
    a=int(input())
    hq.heappush(L,a)
ans =0
while L:
    a=hq.heappop(L)
    b=hq.heappop(L)
    ans+=a+b
    if len(L)==0:
        break
    hq.heappush(L,a+b)

print(ans)


# -*- encoding:utf-8 -*-
# __author__=='Gan'

# Given a linked list, remove the nth node from the end of list and return its head.
#
# For example,
#
#    Given linked list: 1->2->3->4->5, and n = 2.
#
#    After removing the second node from the end, the linked list becomes 1->2->3->5.
# Note:
# Given n will always be valid.
# Try to do this in one pass.
# Definition for singly-linked list.

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy = ListNode(-1)
        dummy.next = head
        counter, incise = dummy, dummy
        for i in range(n):
            counter = counter.next  # if len = 10 and n = 5, from 0 to 5 and from 10 to 5 are the same.
        while counter.next:
            counter, incise = counter.next, incise.next
            # Find the location where need to incise.
        incise.next = incise.next.next
        return dummy.next

if __name__ == '__main__':
    head = ListNode(1)
    head.next = ListNode(2)
    head.next.next = ListNode(3)
    print(Solution().removeNthFromEnd(head, 1))

# 207 / 207 test cases passed.
# Status: Accepted
# Runtime: 45 ms
# Your runtime beats 46.63 % of python submissions.

# Summary:
# If only traverse the list,then there are several operations.
# Then it should be linked to the list several times.
# For this question, find the location and incise the list are two operations.So it should be linked to the list twice.


with open("stocks.csv","r") as f, open("output.csv","w") as out:
    out.write("company Name,PE Ratio, PB Ratio\n")
    next(f)
    for line in f:
        tokens = line.split(",")
        stock = tokens[0]
        price = float(tokens[1])
        eps = float(tokens[2])
        book = float(tokens[3])
        pe = round(price / eps, 2)
        pb = round(price / book,2)
        out.write(f"{stock},{pe},{pb}\n")


import time
import warnings

import numpy as np

from src.learning_loop import LearningLoop
from src.results.all_results import Results
from src.utils import create_folders, initialize_experiment, write_to_file, create_strategies_list
from src.utils.arguments import get_main_args
from src.utils.plotting import plot_initial_points
from src.utils.clustering import introduce_uu
from src.experiments import Synthetic

warnings.filterwarnings('ignore')

def run_experiments(strategies, args):
    results_path = create_folders()
    for experiment_name in args.experiments:
        experiment = initialize_experiment(experiment_name, args.seed, results_path)
        if args.add_uus:
            introduce_uu(experiment, args.add_uus)
        loop = LearningLoop()
        results = Results()

        folds = experiment.split(prop_known=experiment.prop_known, n_splits=args.n_folds, split_seed=args.seed)
        for k, (known_idx, train_idx, test_idx) in enumerate(folds):
            # Remove duplicates
            known_idx, train_idx, test_idx = np.unique(known_idx), np.unique(train_idx), np.unique(test_idx)
            loop.update_data_split(known_idx, train_idx, test_idx)

            if args.plots_on:
                plot_initial_points(known_idx, test_idx, experiment)

            # Run the experiment for every strategy
            for strategy in strategies:
                print(strategy)
                start = time.time()
                running_instance = loop.run(args, experiment, strategy)
                end = time.time()

                write_to_file(loop, args, k, experiment, strategy, str(end - start))
                results.collect(strategy, running_instance)
                results.export(experiment.path)

def main():
    args = get_main_args()
    strategies = create_strategies_list(args)

    np.random.seed(args.seed)
    run_experiments(strategies, args)

if __name__ == '__main__':
    main()


import os
import re
import json
import requests
from file import write_text, create_dir
import argparse

def download(url):
    return requests.get(url).text

class ReactComponentNotFound(RuntimeError):
    pass

class ReactSpider(object):
    @staticmethod
    def extract_react_component(page_source):
        """
        Extract data used to initialize `ReactComponent` from the given page source
        This will only work if the `ReactComponent` is constructed in one line
        """
        regex = re.search('ReactComponent\((.+,\s*"loggedIn".+?})', page_source)
        if not regex:
            raise ReactComponentNotFound(page_source)
        return json.loads(regex.group(1))

    @classmethod
    def crawl(cls, url):
        page_source = download(url)
        react_component = cls.extract_react_component(page_source)
        return cls.filter(react_component)

    @classmethod
    def filter(cls, component):
        """
        filter and return necessary data from react component
        :param component: unfiltered data used to initialize `ReactComponent`
        :return: filtered data
        """
        raise NotImplemented()

class TutorialSpider(ReactSpider):
    @classmethod
    def filter_content_items(cls, content_items):
        result = []
        for ci in content_items:
            # practice nodes do not have videos
            if 'youtubeId' not in ci:
                continue
            result.append({'title': ci['title'], 'video_id': ci['youtubeId']})
        return result

    @classmethod
    def filter(cls, component):
        tutorials = component['componentProps']['curation']['tabs'][0]['modules'][0]['tutorials']
        nodes = []
        for t in tutorials:
            nodes.append({
                'title': t['title'],
                'children': cls.filter_content_items(t['contentItems'])})
        return nodes

class ModuleSpider(ReactSpider):
    @classmethod
    def filter(cls, component):
        modules = component['componentProps']['curation']['tabs'][0]['modules']
        modules = [m for m in modules if m['kind'] == 'TableOfContentsRow']
        return [{'title': m['title'], 'url': m['url']} for m in modules]

def get_url_base(url):
    regex = re.search('(.+://.+?)/.+', url)
    return regex.group(1)

def adjust_module_urls(modules, url):
    """Convert relative paths to full urls"""
    url_base = get_url_base(url)
    for m in modules:
        m['url'] = url_base + m['url']
    return modules

def get_modules(url):
    modules = ModuleSpider.crawl(url)
    return adjust_module_urls(modules, url)

def save(title, modules):
    out_dir = os.path.join('transcripts', 'tutorials')
    create_dir(out_dir)
    fname = os.path.join(out_dir, title + '.json')
    write_text(fname, json.dumps(modules))

def convert_hierarchy(hierarchy):
    """Convert dict hierarchy to directory hierarchy"""
    for c in hierarchy:
        for gc in c['children']:
            yield {'path': os.path.join(c['title'], gc['title']), 'video_id': gc['video_id']}

def commit_hierarchy(hierarchy):
    """
    Commit hierarchy to file system so that they can be cached
    :param hierarchy: hierarchy to commit
    :param dest: directory in file system to commit to
    """
    for node in hierarchy:
        create_dir(os.path.dirname(node['path']))
        write_text(node['path'], node['video_id'])

def resolve_paths(hierarchy, dest):
    """
    Resolve relative paths in hierarchy
    :param hierarchy: hierarchy containing video ids; mutated
    :param dest: Destination in file system to save hierarchy
    :return: hierarchy with resolved paths
    """
    for node in hierarchy:
        node['path'] = os.path.join(dest, node['path'])
    return hierarchy

def resolve_indices(hierarchy):
    """
    Prepend index of array element to title so that the order is
    preserved after saving to the file system
    :param hierarchy: hierarchy containing video ids; mutated
    :return: hierarchy with resolved indices
    """
    for i, h in enumerate(hierarchy):
        h['title'] = '%d %s' % (i, h['title'])
        if 'children' in h:
            resolve_indices(h['children'])
    return hierarchy

def fix_illegal_names(hierarchy):
    """
    Fix illegal names
    :param hierarchy: hierarchy containing video ids; mutated
    :return: hierarchy with resolved indices
    """
    for i, h in enumerate(hierarchy):
        h['title'] = h['title'].replace('/', '_').replace(':', '_')
        if 'children' in h:
            fix_illegal_names(h['children'])
    return hierarchy

def process_modules(url, dest_dir):
    for m_i, m in enumerate(get_modules(url)):
        module_title = '%d %s' % (m_i, m['title'])
        print('\tProcessing ' + module_title)

        module_dir = os.path.join(dest_dir, module_title)

        if os.path.exists(module_dir):
            print('\t\tSkipping ' + module_dir)
            continue

        hierarchy = TutorialSpider.crawl(m['url'])
        hierarchy = resolve_indices(hierarchy)
        hierarchy = fix_illegal_names(hierarchy)
        hierarchy = list(convert_hierarchy(hierarchy))
        hierarchy = resolve_paths(hierarchy, module_dir)
        commit_hierarchy(hierarchy)

        print('\tSaved ' + module_title)

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('module')
    parser.add_argument('url')
    return parser.parse_args()

def main():
    """
    Download tutorials of every content in every module
    eg) Vectors and spaces(module) => Vectors(content) => Vector intro for linear algebra(tutorial)
    """
    args = get_args()

    module_title = args.module

    print('Processing ' + module_title)
    subject_dir = os.path.join('video_ids', module_title)
    process_modules(args.url, subject_dir)

if __name__ == '__main__':
    main()


from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from rest_framework.authtoken.models import Token

from .serializers import RegestrationSerializer
from user_app import models

@api_view(['POST', ])
def logout_view(request):

    if request.method == 'POST':
        request.user.auth_token.delete()
        return Response(status=status.HTTP_200_OK)

@api_view(['POST', ])
def registration_view(request):

    if request.method == 'POST':
        data = request.data
        serializer = RegestrationSerializer(data=data)

        data = {}

        if serializer.is_valid():
            account = serializer.save()       # over-riding save method to add extra field "PASSWORD2"

            # we need to over-ride save method, all the current functionality will be there and we can add some more according to out requirement.

            data['response'] = "Registration Sucessfull."
            data['username'] = account.username
            data['email'] = account.email               # store all this data into data{}

            token = Token.objects.get(user=account).key     # getting token.
            data['token'] = token

        else:
            data = serializer.errors

        return Response(data)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 13 12:20:56 2023

@author: user
"""

n = int(input())

data = [tuple(input().split()) for _ in range(n)]
ant = []
for i in range(n):
    print(*data[i])
    if '5' in data[i] or '4' in data[i]:
        ant.append(data[i])

print()

for i in range(len(ant)):
    print(*ant[i])


import re
from os import PathLike
from typing import Union, Optional

import aiosqlite

from .. import Notebook
from ..NotebookCell import NotebookCell

class SQLiteNotebook(Notebook):
    def __init__(self, notebook: Union[str, PathLike], execute: bool = False):
        super().__init__(notebook, self.__execute_cell, execute)
        self.db: Optional

    async def __aenter__(self) -> "Notebook":
        self.db = aiosqlite.connect(':memory:')

        await self.db.__aenter__()
        await super().__aenter__()

        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await super().__aexit__(exc_type, exc_val, exc_tb)
        await self.db.__aexit__(exc_type, exc_val, exc_tb)

    async def __execute_cell(self, cell: NotebookCell):
        statements = list(filter(lambda x: x, re.split(r';$', cell.source, flags=re.MULTILINE)))
        last_index = len(statements) - 1

        for i, statement in enumerate(statements):
            async with self.db.execute(statement) as cursor:
                if i == last_index:
                    return await cursor.fetchall()


#!/usr/bin/env python

"""
Filename:  transformer_classifier.py
Description:
    This system fine-tunes an Italian BERT model to predict who (out of three subjects) is the
    post-editor of an automatically translated sentence. Predictions are cross-validated on the training set.
"""

import argparse
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold
from simpletransformers.classification import ClassificationArgs, ClassificationModel

def create_arg_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument("-tr", "--train_file", default='./data/IK_NLP_22_PESTYLE/train.tsv',
                        type=str, help="Location of training file.")
    parser.add_argument("-te", "--test_file", default='./data/IK_NLP_22_PESTYLE/test.tsv',
                        type=str, help="Location of test file.")
    parser.add_argument("-o", "--outfile", default='./transformer_predictions.txt',
                        type=str, help="Path to write output to.")
    parser.add_argument("-m", "--model",
                        type=str, help="Specify an already fine-tuned model")
    return parser.parse_args()

def prepare_train(train_file, include_from_scratch=False):
    """
    Extract the relevant features from the data set: MT, PE and subject.
    If include_from_scratch is False, we do not take into account the HT modality.
    """
    pairs = []
    labels = []
    with open(train_file) as train:
        train.readline()  # Skip first line: this is the header
        for line in train:
            if line.split("\t")[1][0] == "t":
                # Get a list of: [MT output, post-edited sentence, subject id]
                if include_from_scratch:
                    pairs.append([line.split("\t")[4], line.split("\t")[5]])
                    labels.append(line.split("\t")[1])
                else:
                    if line.split("\t")[4]:
                        pairs.append([line.split("\t")[4], line.split("\t")[5]])
                        labels.append(line.split("\t")[1])

    # We use only 90% of the data, in order to allow comparison with the other models
    X_train, _, y_train, _ = train_test_split(pairs, labels, test_size=0.1, random_state=42)

    return X_train, y_train

def predict_test(test_data, model, include_from_scratch=False, final=False):
    """
    Given a fine-tuned model, predict the labels (translators) from MT-PE sentence pairs.
    If include_from_scratch is False, we do not take into account the HT modality.
    """
    pairs = []
    predictions = []

    if final:  # Use the 'final' (official) test set
        with open(test_data) as test:
            test.readline()  # Skip first line: this is the header
            for line in test:
                if line.split("\t")[0][0] in "0123456789":
                    if include_from_scratch:
                        pairs.append([line.split("\t")[4], line.split("\t")[5]])
                    else:
                        if line.split("\t")[4]:
                            pairs.append([line.split("\t")[4], line.split("\t")[5]])
    else:  # Use a subset of the data for cross-validation
        pairs = test_data

    for pair in pairs:
        prediction, _ = model.predict(pair)
        predictions.append(prediction[0])

    return predictions

def get_accuracy(gold, pred):
    """
    Retrieve the number of correctly predicted post-editors
    """
    # Map labels to ints, to streamline with model predictions
    gold_ints = []
    for g in gold:
        if g == "t1":
            gold_ints.append(0)
        elif g == "t2":
            gold_ints.append(1)
        elif g == "t3":
            gold_ints.append(2)
        else:
            pass

    # Get number of correct predictions
    correct = 0
    if len(gold_ints) == len(pred):
        for g, p in zip(gold_ints, pred):
            if g == p:
                correct += 1
    else:
        print("ERROR: Gold standard and predictions are not of equal length!")

    return correct / len(gold)

def reformat_test(pairs):
    """
    Retrieve a regular list from the numpy array
    The output is a list that contains lists ([MT,PE]) with each sentence pair.
    """
    data = []
    mt = [t[0] for t in pairs]
    pe = [t[1] for t in pairs]

    for m, p in zip(mt, pe):
        data.append([m, p])

    return data

def reformat_train(pairs, labels):
    """
    Retrieve a regular list from the numpy array
    The output is a list that contains lists ([MT,PE,label]) from each sentence pair.
    """
    data = []
    mt = [t[0] for t in pairs]
    pe = [t[1] for t in pairs]
    labs = np.ndarray.tolist(labels)

    for m, p, l in zip(mt, pe, labs):
        data.append([m, p, l])

    return data

def main():

    args = create_arg_parser()
    all_predictions = []

    if args.model:  # Use an already fine-tuned model, test on the final test set
        model = ClassificationModel("bert", args.model, use_cuda=False)
        predictions = predict_test(args.test_file, model, final=True)
        all_predictions.append(predictions)
        all_predictions.append("\n")

    else:  # Fine-tune a new model, use cross-validation

        # Define model
        model_args = ClassificationArgs()
        model_args.num_train_epochs = 3
        model_args.overwrite_output_dir = True
        model_args.learning_rate = 0.000001
        model_args.do_lower_case = True
        model_args.silence = True
        model = ClassificationModel("bert", "dbmdz/bert-base-italian-uncased", args=model_args, use_cuda=False, num_labels=3)

        # Create the correct splits for cross-validation
        skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
        X, y = prepare_train(args.train_file)
        X = np.array(X)
        y = np.array(y)
        for train_index, test_index in skf.split(X, y):
            X_train, X_test = X[train_index], X[test_index]
            y_train, y_test = y[train_index], y[test_index]

            # Prepare train set
            train_data = reformat_train(X_train, y_train)
            train_df = pd.DataFrame(train_data)
            train_df.columns = ["text_a", "text_b", "labels"]
            train_df["labels"] = train_df["labels"].replace(["t1", "t2", 't3'], [0, 1, 2])
            print(train_df)

            # Train model
            model.train_model(train_df)

            # Predict synsets
            predictions = predict_test(reformat_test(X_test), model)
            all_predictions.append(predictions)
            all_predictions.append("\n")
            print("ACCURACY: ", get_accuracy(y_test, predictions))

    # Write results to pickle file
    with open(args.outfile, 'w') as pred_file:
        for pred_list in all_predictions:
            for pred in pred_list:
                pred_file.write(str(pred))
    print("Predictions have been written to file: " + args.outfile)

if __name__ == "__main__":
    main()


import sys
from collections import deque
import copy
input = sys.stdin.readline
inf = sys.maxsize

n, m = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(n)]

dr = [1, -1, 0, 0]
dc = [0, 0, -1, 1]

virus_cnt = 0   # 처음 바이러스의 개수
virus_loc = []  # 바이러스의 위치
empty_cnt = 0   # 빈칸의 개수
for i in range(n):
    for j in range(n):
        if board[i][j] == 2:
            virus_cnt += 1
            virus_loc.append([i, j, 0])
        elif board[i][j] == 0:
            empty_cnt += 1

pick = deque()
ccc= 0
ans = inf
def bfs(q, visited):
    global ans
    # 비어있는 칸에 몇초 걸려서 감염시키는지
    while q:
        r, c, time = q.popleft()
        # if time == ans:
        #     for i in visited:
        #         print(i)
        #     return
        for i in range(4):
            nr = r + dr[i]
            nc = c + dc[i]
            if 0 <= nr < n and 0 <= nc < n and board[nr][nc] != 1:
                if visited[nr][nc] > time + 1:
                    visited[nr][nc] = time + 1
                    q.append([nr, nc, time + 1])

    spread_cnt = 0 # 몇칸 감염시켰는지
    max_time = 0 # 가장 오래걸린 시간
    # for i in visited:
    #     print(i)
    for i in range(n):
        for j in range(n):
            if visited[i][j] != inf and board[i][j] == 0:
                if visited[i][j] > max_time:
                    max_time = visited[i][j]
                spread_cnt += 1
    # print(max_time)
    # 만약 감염시킨 칸의 개수가 처음 빈칸의 개수와 같을때
    if spread_cnt == empty_cnt:
        if max_time < ans:
            ans = max_time
        return

def combi(cnt, start):
    global virus_cnt, m, ccc
    # 바이러스를 m개 뽑는 조합
    if cnt == m:
        ccc += 1
        visited = [[inf]*n for _ in range(n)]
        for loc in pick:
            visited[loc[0]][loc[1]] = 0
        # print(pick)
        q = copy.deepcopy(pick)
        bfs(q, visited)
        return
    for i in range(start, virus_cnt):
        pick.append(virus_loc[i])
        combi(cnt + 1, i + 1)
        pick.pop()

combi(0, 0)
if ans == inf:
    print(-1)
else:
    print(ans)


# -*- encoding: utf-8 -*-
# ##########################################################################
#    Module Writen to OpenERP, Open Source Management Solution
#
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import xml.etree.cElementTree as ET
from .report_to_file import ReportToFile
from openerp.addons.account_chart_report.report.chart_of_accounts import AccountChar
from datetime import datetime

class AccountChartXml(ReportToFile):
    """
    Class to generate and export the account chart in xml format
    """

    def __init__(
        self, name, table, rml=False, parser=False, header=True, store=False
    ):
        super(AccountChartXml, self).__init__(
            name, table, rml, parser, header, store
        )

    def generate_report(self, parser, data, objects):
        import tempfile
        Etree = ET.ElementTree()

        acc_lst = parser.get_lst_account(
            parser.cr, parser.uid, data["form"]["id_account"],
            parser.actual_context
        )
        period_id = data["form"]["period_id"][0]

        period_obj = self.pool['account.period']
        period = period_obj.browse(
            parser.cr, parser.uid, period_id,
            context=parser.actual_context
        )
        time_period = datetime.strptime(period.date_start, "%Y-%m-%d")

        month = str(time_period.month).rjust(2, '0')
        year = str(time_period.year)

        catalogo = ET.Element('catalogocuentas:Catalogo')
        #namespace
        catalogo.set("xsi:schemaLocation",
                    "www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas/CatalogoCuentas_1_1.xsd")
        catalogo.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
        catalogo.set("xmlns:catalogocuentas", "www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas")

        catalogo.set("Version", "1.1")
        catalogo.set("RFC", parser.company.partner_id.vat_split)
        catalogo.set("Mes", month)
        catalogo.set("Anio", year)

        Etree._setroot(catalogo)

        # Debemos quitar la primer cuenta del listado,
        # ya que es la que engloba a todo el plan contable
        del acc_lst[0]

        for acc in acc_lst:
            # Solo se consideran las cuentas que tengan catálogo agrupador,
            # de esa forma se pueden omitir algunas cuentas del reporte
            if acc.sat_group_id:
                cuenta = ET.SubElement(catalogo, 'catalogocuentas:Ctas')
                # Codigo agrupador poner el Codigo no el Nombre
                cuenta.set("CodAgrup", str(acc.sat_group_id.code))
                cuenta.set("NumCta", acc.code)
                cuenta.set("Desc", acc.name)
                if acc.parent_id and acc.level > 1:
                    cuenta.set("SubCtaDe", acc.parent_id.code)
                cuenta.set("Nivel", str(acc.level))
                cuenta.set("Natur", acc.nature)

        # Write data into temporal file
        with tempfile.NamedTemporaryFile(delete=False) as report:
            Etree.write(report.name, encoding='UTF-8')
            self.fname = report.name

        return

AccountChartXml(
    'report.account.chart.xml', 'account.account',
    parser=AccountChar
)


import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, LSTM, Add, Dropout, Embedding, Reshape, Bidirectional

class BahdanauAttention(Model):

    def __init__(self, units):
        super(BahdanauAttention, self).__init__()
        self.W1 = Dense(units)
        self.W2 = Dense(units)
        self.V = Dense(1)

    def call(self, features, hidden):
        hidden_with_time_axis = tf.expand_dims(hidden, 1)
        attention_hidden_layer = (tf.nn.tanh(self.W1(features) + self.W2(hidden_with_time_axis)))
        score = self.V(attention_hidden_layer)
        attention_weights = tf.nn.softmax(score, axis=1)
        context_vector = attention_weights * features
        context_vector = tf.reduce_sum(context_vector, axis=1)
        return context_vector, attention_weights

class NICAttention(tf.keras.Model):

    def __init__(self, embedding_dim, vocab_size):
        super(NICAttention, self).__init__()
        self.dropout1 = Dropout(0.3)
        self.dense1 = Dense(embedding_dim, activation='relu')

        self.embeddingB = Embedding(vocab_size, embedding_dim, mask_zero=True)
        self.dropoutB = Dropout(0.5)
        self.LSTM = Bidirectional(LSTM(256, return_sequences=True, return_state=True))

        self.attention = BahdanauAttention(256)

        self.dense2 = Dense(256, activation='relu')
        self.dense3 = Dense(vocab_size, activation='softmax')
        self.hidden = tf.zeros((3, 256))

    def call(self, inputs):
        InputA = inputs[0]
        InputB = inputs[1]

        A = self.dropout1(InputA)
        A = self.dense1(A)

        context_vector, attention_weights = self.attention(A, self.hidden)

        B = self.embeddingB(InputB)

        x = tf.concat([tf.expand_dims(context_vector, 1), B], axis=-1)

        output, state = self.LSTM(x)
        self.hidden = state

        x = self.dense2(output)
        x = self.dense3(x)

        return x


import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
INF = 10**30

def make_adj_list(n, E):
    l = [[] for _ in range(n)] # 隣接リスト. 各要素は(コスト、to_node)
    for i in range(E):
        s, t, d = map(int, input().strip().split())
        l[s].append([d, t])
    return l

# 全てのエッジに関してtoの最短距離を更新、それを頂点回数繰り返す
# エッジ1周につき最低1頂点は最短距離が求まるのでそれを伝播させていく
def bellman_ford(n, s, l):
    # s: start node, n: num of node
    # return True: negative cycle
    dist = [INF] * n
    dist[s] = 0
    for i in range(n):
        # 全てのエッジに関してtoの最短距離を更新
        for v in range(n):
            for k in range(len(l[v])):
                cost, to = l[v][k]
                if dist[v] != INF and dist[to] > dist[v] + cost:
                    dist[to] = dist[v] + cost
                    if i == n-1:
                        return (True, dist)
    return (False, dist)

def main():
    v, e, r = map(int, input().strip().split())
    l = make_adj_list(v, e)
    is_negative_cycle, dist = bellman_ford(v, r, l)
    if is_negative_cycle:
        print("NEGATIVE CYCLE")
        return
    for d in dist:
        if d == INF:
            print('INF')
        else:
            print(d)

if __name__ == '__main__':
    main()


from abc import ABCMeta, abstractmethod
import numbers
import warnings

import torch

from ignite.engine import State, Engine
from ignite._six import with_metaclass

class BaseLogger(object):
    """
    Base logger handler. See implementations: TensorboardLogger, VisdomLogger, PolyaxonLogger

    """
    def attach(self, engine, log_handler, event_name):
        """Attach the logger to the engine and execute `log_handler` function at `event_name` events.

        Args:
            engine (Engine): engine object.
            log_handler (callable): a logging handler to execute
            event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine.Events`
                or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.

        """
        if event_name not in State.event_to_attr:
            raise RuntimeError("Unknown event name '{}'".format(event_name))

        engine.add_event_handler(event_name, log_handler, self, event_name)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def close(self):
        pass

class BaseHandler(with_metaclass(ABCMeta, object)):

    @abstractmethod
    def __call__(self, *args, **kwargs):
        pass

class BaseOptimizerParamsHandler(BaseHandler):
    """
    Base handler for logging optimizer parameters
    """

    def __init__(self, optimizer, param_name="lr", tag=None):
        if not isinstance(optimizer, torch.optim.Optimizer):
            raise TypeError("Argument optimizer should be of type torch.optim.Optimizer, "
                            "but given {}".format(type(optimizer)))

        self.optimizer = optimizer
        self.param_name = param_name
        self.tag = tag

class BaseOutputHandler(BaseHandler):
    """
    Helper handler to log engine's output and/or metrics
    """

    def __init__(self, tag, metric_names=None, output_transform=None, another_engine=None, global_step_transform=None):

        if metric_names is not None and not isinstance(metric_names, list):
            raise TypeError("metric_names should be a list, got {} instead.".format(type(metric_names)))

        if output_transform is not None and not callable(output_transform):
            raise TypeError("output_transform should be a function, got {} instead."
                            .format(type(output_transform)))

        if output_transform is None and metric_names is None:
            raise ValueError("Either metric_names or output_transform should be defined")

        if another_engine is not None:
            if not isinstance(another_engine, Engine):
                raise TypeError("Argument another_engine should be of type Engine, "
                                "but given {}".format(type(another_engine)))
            warnings.warn("Use of another_engine is deprecated and will be removed in 0.2.1. "
                          "Please use global_step_transform instead.", DeprecationWarning)

        if global_step_transform is not None and not callable(global_step_transform):
            raise TypeError("global_step_transform should be a function, got {} instead."
                            .format(type(global_step_transform)))

        if global_step_transform is None:
            def global_step_transform(engine, event_name):
                return engine.state.get_event_attrib_value(event_name)

        self.tag = tag
        self.metric_names = metric_names
        self.output_transform = output_transform
        self.another_engine = another_engine
        self.global_step_transform = global_step_transform

    def _setup_output_metrics(self, engine):
        """Helper method to setup metrics to log
        """
        metrics = {}
        if self.metric_names is not None:
            for name in self.metric_names:
                if name not in engine.state.metrics:
                    warnings.warn("Provided metric name '{}' is missing "
                                  "in engine's state metrics: {}".format(name, list(engine.state.metrics.keys())))
                    continue
                metrics[name] = engine.state.metrics[name]

        if self.output_transform is not None:
            output_dict = self.output_transform(engine.state.output)

            if not isinstance(output_dict, dict):
                output_dict = {"output": output_dict}

            metrics.update({name: value for name, value in output_dict.items()})
        return metrics

class BaseWeightsScalarHandler(BaseHandler):
    """
    Helper handler to log model's weights as scalars.
    """

    def __init__(self, model, reduction=torch.norm):
        if not isinstance(model, torch.nn.Module):
            raise TypeError("Argument model should be of type torch.nn.Module, "
                            "but given {}".format(type(model)))

        if not callable(reduction):
            raise TypeError("Argument reduction should be callable, "
                            "but given {}".format(type(reduction)))

        def _is_0D_tensor(t):
            return isinstance(t, torch.Tensor) and t.ndimension() == 0

        # Test reduction function on a random tensor
        o = reduction(torch.rand(4, 2))
        if not (isinstance(o, numbers.Number) or _is_0D_tensor(o)):
            raise ValueError("Output of the reduction function should be a scalar, but got {}".format(type(o)))

        self.model = model
        self.reduction = reduction

class BaseWeightsHistHandler(BaseHandler):
    """
    Helper handler to log model's weights as histograms.
    """

    def __init__(self, model):
        if not isinstance(model, torch.nn.Module):
            raise TypeError("Argument model should be of type torch.nn.Module, "
                            "but given {}".format(type(model)))

        self.model = model


# bot-term.py
# A simple interactive terminal to test the model
# Usage: python3 bot-term.py
# ITL 2020-11-15

import requests

# api_url = "http://3.139.62.97:4000/predict"
api_url = "http://ec2-3-139-62-97.us-east-2.compute.amazonaws.com:4000/predict"

print("\nWelcome to the Accurolab Covid-19 test bot.")
print("Please ask a question, or hit return to exit.\n")

continue_loop = True
while continue_loop:
  q = input("> ")
  if q == "":
    continue_loop = False
  else:
    payload = {"question" : q }
    r = requests.put(api_url, json=payload).json()
    for x in r:
        if x != 'question':
            print(x,": ",r[x])
    print("\n")