import pygame

from item import items
from states.state import State

class ItemMenu(State):
    def __init__(self, game, cb):
        super().__init__(game)
        self.cb = cb
        self.rectangle = pygame.Surface((self.game.width, self.game.height))
        self.rectangle.set_alpha(128)
        self.rectangle.fill((0, 0, 0))
        self.options = list(self.game.player.items.items())
        self.OPTION_SIZE = (self.game.width, self.game.height / 8)
        self.option_images = self.get_item_images(self.options)
        self.index = 0
        for i, option in enumerate(self.options):
            if option[0].can_be_used(self.game.player):
                self.index = i
                break

    def get_item_images(self, items):
        result = []
        for item, count in items:
            padding_x = 10
            padding_y = 10

            new_rect = pygame.Surface(self.OPTION_SIZE)
            new_rect.set_alpha(128)
            new_rect.fill((0, 0, 0))
            new_rect.blit(item.icon, (padding_x, padding_y))

            text_surface = self.game.font.render(f'{item.name}', True, (255, 255, 255))
            name_text_rect = text_surface.get_rect()
            name_text_rect.topleft = (64 + padding_x + 10, padding_y)
            new_rect.blit(text_surface, name_text_rect)

            text_surface = self.game.font.render(f'{item.description}', True, (255, 255, 255))
            text_rect = text_surface.get_rect()
            text_rect.topleft = (64 + padding_x + 10, 24 + padding_y)
            new_rect.blit(text_surface, text_rect)

            text_surface = self.game.font.render(f'{item.count}', True, (255, 128, 0))
            text_rect = text_surface.get_rect()
            text_rect.topright = new_rect.get_rect().topright
            new_rect.blit(text_surface, text_rect)

            result.append(new_rect)
        return result

    def update(self, key_state):
        self.handle_keys(key_state)
        self.prev_state.update(key_state)

    def render(self, display):
        self.prev_state.render(display)
        for i, image in enumerate(self.option_images):
            if i // 8 < self.index // 8 or i // 8 > self.index // 8:
                continue
            if i == self.index:
                image.set_alpha(255)
            else:
                image.set_alpha(128)
            display.blit(image, (0, i * self.OPTION_SIZE[1]))
        display.blit(self.rectangle, (0, 0))
        if len(self.game.state_stack) == 4:
            display.blit(self.prev_state.confirm_buttons, (
                self.game.width - self.prev_state.confirm_buttons_rect[2],
                self.game.height - self.prev_state.confirm_buttons_rect[3]))

    def handle_keys(self, key_state):
        if key_state['down']:
            self.index = (self.index + 1) % len(self.options)
            while not self.options[self.index][0].can_be_used(self.game.player):
                self.index = (self.index + 1) % len(self.options)
        elif key_state['up']:
            self.index = (self.index - 1) % len(self.options)
            while not self.options[self.index][0].can_be_used(self.game.player):
                self.index = (self.index - 1) % len(self.options)
        elif key_state['confirm']:
            self.cb(self.options[self.index][0])
            self.exit_state()
        elif key_state['cancel']:
            self.cb(-1)
            self.exit_state()
        self.game.reset_keys()


# -*- coding: utf-8 -*-
"""
:code:`python readStateFilesAndComputeModes.py stateFilename tol modesFilename addRigidBodyModesBOOL`
"""

import os
import math
import numpy as np
import platform

from sys import argv

slash = '/'
if "Windows" in platform.platform():
    slash = "\\"

def readStateFilesAndComputeModes(stateFilePath, tol, modesFileName, addRigidBodyModes=None, verbose=False):
    print("###################################################")
    print("Executing readStateFilesAndComputeModes.py\n")
    print("Arguments :\n")
    print("     INPUT  :")
    print("     in stateFilePath         :", stateFilePath)
    print("     with arguments           :")
    print("         -tolerance               :", tol, "\n")
    print("     OUTPUT :")
    print("         -modesFileName           :", modesFileName, "\n")
    print("###################################################")
    x0Found = False

    f = open(stateFilePath, 'r')
    nbSnap = 0
    nbLine = 0
    snapshot = []
    snapshotV = []

    if verbose: print("Reading file %r:" % stateFilePath)
    for line in f:
        nbLine = nbLine + 1
        lineSplit = line.split();
        if not x0Found and lineSplit[0] == "X0=":
            lineFloat = list(map(float, lineSplit[1:]))
            restPos = []
            restPos.append(lineFloat)
            restPos = np.transpose(restPos)
            x0Found = True
        if (lineSplit[0] == "X="):
            lineFloat = list(map(float, lineSplit[1:]))
            snapshot.append(lineFloat);
        if (lineSplit[0] == "V="):
            lineFloat = list(map(float, lineSplit[1:]))
            snapshotV.append(lineFloat);

    if x0Found:
        snapshot = np.transpose(snapshot)
        if np.isnan(np.sum(np.sum(snapshot))):
            print("NAN PRESENT IN THE POSITIONS! THE SIMULATION WENT WRONG DURING THE SHAKING! MAKE SURE YOUR "
                  "SIMULATION IS STABLE!")
            return -1

        nbDOFs, nbSnap = np.shape(snapshot)
        snapshotDiff = np.zeros((nbDOFs, nbSnap))
        translationModes = np.zeros((nbDOFs, 3))

        if verbose:
            print("    Read", nbLine, "line and found", nbSnap, "snapshot with", nbDOFs, "of DOF")
            print("Done reading file %r:" % stateFilePath, '\n')

        for i in range(0, nbSnap):
            snapshotDiff[:, i] = snapshot[:, i] - restPos[:, 0]

        for i in range(0, int(nbDOFs / 3)):
            translationModes[3 * i][0] = 1 / math.sqrt(nbDOFs / 3)
            translationModes[3 * i + 1][1] = 1 / math.sqrt(nbDOFs / 3)
            translationModes[3 * i + 2][2] = 1 / math.sqrt(nbDOFs / 3)

        tmp = []
        if (addRigidBodyModes):
            if (addRigidBodyModes[0] == 1):
                for j in range(nbSnap - 1):
                    snapshotDiff[:, [j]] = snapshotDiff[:, [j]] - (
                        np.matmul(np.transpose(snapshotDiff[:, [j]]), translationModes[:, [0]])) * translationModes[:,
                                                                                [0]]
                tmp.append(0)
            if (addRigidBodyModes[1] == 1):
                for j in range(nbSnap - 1):
                    snapshotDiff[:, [j]] = snapshotDiff[:, [j]] - (
                        np.matmul(np.transpose(snapshotDiff[:, [j]]), translationModes[:, [1]])) * translationModes[:,
                                                                                [1]]
                tmp.append(1)
            if (addRigidBodyModes[2] == 1):
                for j in range(nbSnap - 1):
                    snapshotDiff[:, [j]] = snapshotDiff[:, [j]] - (
                        np.matmul(np.transpose(snapshotDiff[:, [j]]), translationModes[:, [2]])) * translationModes[:,
                                                                                [2]]
                tmp.append(2)

        U, s, V = np.linalg.svd(snapshotDiff, full_matrices=False)  # 99% time execution
        sSquare = [i ** 2 for i in s]
        sumSVD = np.sum(sSquare)

        stateFilePath = os.path.normpath(stateFilePath)
        outputDir = slash.join(stateFilePath.split(slash)[:-1]) + slash
        np.savetxt(outputDir + "Sdata.txt", s)

        i = 0
        if verbose:
            print("Determining number of Modes with a Tolerance of", tol)

        while (np.sqrt(np.sum(sSquare[i:]) / sumSVD) > tol or i == 0):
            i = i + 1

        nbModes = i
        if (addRigidBodyModes and addRigidBodyModes != [0] * 3):
            print("Concatenating translation modes")
            nbModes += 3
            modesTot = np.concatenate((translationModes[:, tmp], U[:, 0:nbModes]), axis=1)
            np.savetxt(modesFileName, modesTot, header=str(nbDOFs) + ' ' + str(nbModes), comments='', fmt='%10.5f')
        else:
            np.savetxt(modesFileName, U[:, 0:nbModes], header=str(nbDOFs) + ' ' + str(nbModes), comments='',
                       fmt='%10.5f')
        if verbose:
            print("===> Success readStateFilesAndComputeModes.py\n")

        f.close()

        print(str(nbModes) + " possible modes with a tolerance of " + str(tol))
        return nbModes

    else:
        print("XO NOT FOUND")
        return -1

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

if __name__ == '__main__':  # if we're running file directly and not importing it
    if len(argv) < 4:
        print("Function need at least 3 arguments")
    else:
        readStateFilesAndComputeModes(*argv[1:])


# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

from scrapy.pipelines.images import ImagesPipeline
from scrapy.exceptions import DropItem
from scrapy import Request

class ImagePipeLine(ImagesPipeline):
    default_headers = {
        "Referer": "http://www.meizitu.com/a/5013.html",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/77.0.3833.0 Safari/537.36 "
    }

    def get_media_requests(self, item, info):
        print("process_item")
        # url = item['img_urls']
        # self.default_headers['Referer'] = url
        # yield Request(item['img_urls'], headers=self.default_headers)
        for image_url in item['img_urls']:
            self.default_headers['referer'] = image_url
            yield Request(image_url, headers=self.default_headers)

    def item_completed(self, results, item, info):
        print("process_item_done")
        image_paths = [x['path'] for ok, x in results if ok]
        if not image_paths:
            raise DropItem("Item contains no images")
        item['image_paths'] = image_paths
        return item


def lcs(x,y,m,n): # Time complexity = O(2^n)
    if m==0 or n==0:
        return 0
    elif x[m-1]==y[n-1]:
        return 1+lcs(x,y,m-1,n-1)

    else:
        return max(lcs(x,y,m,n-1),lcs(x,y,m-1,n))

def lcs2(x,y,m,n): # Time complexity = O(m*n)
    table=[[0]*(n+1) for j in range(m+1)]
    for i in range(m+1):
        for j in range(n+1):
            if i==0 or j==0:
                table[i][j]=0

            elif x[m-1]==y[n-1]:
                table[i][j]=1+table[i-1][j-1]

            else:
                table[i][j]=max(table[i][j-1],table[i-1][j])

    return table[m][n]

print(lcs('abcd','bd',len('abcd'),len('bd')))
print(lcs2('abcd','bd',len('abcd'),len('bd')))


"""Welcome handler."""
import injector
import telebot
import telebot.types

from bot.actions.abc import BaseHandler
from bot.services import UserService, VotingManager

class StartVoting(BaseHandler):
    """Initial handler."""

    @injector.inject
    def __init__(self, users: UserService, manager: VotingManager):
        """Primary constructor."""
        self._users = users
        self._manager = manager

    def can_handle(self, message: telebot.types.Message) -> bool:
        """Return true if it's uknown user."""
        return message.text and message.text.startswith('/startvoting')

    def handle(self, bot: telebot.TeleBot, message: telebot.types.Message):
        """Parse and validate payload, start voting if everything is ok."""
        if self._manager.current():
            text = 'Остановите текущее голосование прежде чем начать новое.'
            bot.send_message(message.chat.id, text)
            return

        raw_payload = message.text.replace('/startvoting', '').strip()
        payload_chunks = raw_payload.split()

        max_stocks, max_steaks = None, None

        for chunk in filter(lambda chunk: '=' in chunk, payload_chunks):
            name, value = chunk.rsplit('=')

            if value.isdigit():
                if name == 'stocks':
                    max_stocks = int(value)
                elif name == 'steaks':
                    max_steaks = int(value)

        if max_steaks is None or max_stocks is None:
            text = 'Не могу распарсить параметы голосования.'
            bot.send_message(message.chat.id, text)
            return

        self._manager.start(max_stocks, max_steaks)

        text = 'Управляющий портфелем запустил новое голосование.'
        num = self._users.send_to_all(text)

        text = f'Голосования запущено. Оповещено пользователей: {num}'
        bot.send_message(message.chat.id, text)


valors= [1,4,1,4,1,4]
ordenat=valors.copy()
#for i in valors:
#    ordenat.append(i)
ordenat.sort()
maxim=ordenat[-1]
minim=ordenat[1]
variat=0
baixat = True
for i in valors:
    print(i)

    if baixat == True and i > 3:
        print("puja")
        variat +=1
        baixat = False

    if i < 3:
        print("baix")
        baixat = True

print("Màxim: " +str(maxim))
print("Mínim: " + str(minim))
print("Variat: " + str(variat))


import sys
import math
import interval
from enum import Flag, auto

# Some auxilary functions

def comp_conv_slope(a, b, c, va, vb, vc, slp):
    """
    Computes the slope for a convex function
    :param a: left bound of the interval
    :param b: right bound of the interval
    :param c: point in the interval
    :param va: value at the left end
    :param vb: value at the right end
    :param vc: value at the point c
    :param slp: slope at the point c
    :return: the computed slope
    """
    sp = [0, 0]
    if a == c:
        sp[0] = slp[0]
    else:
        sp[0] = (va - vc) / (a - c)
    if b == c:
        sp[1] = slp[1]
    else:
        sp[1] = (vb - vc) / (b - c)
    return interval.Interval(sp)

def comp_conc_slope(a, b, c, va, vb, vc, slp):
    """
    Computes the slope for a concave function
    :param a: left bound of the interval
    :param b: right bound of the interval
    :param c: point in the interval
    :param va: value at the left end
    :param vb: value at the right end
    :param vc: value at point c
    :param slp: derivative at point c
    :return: the computed slope
    """
    sp = [0, 0]
    if a == c:
        sp[1] = slp[1]
    else:
        sp[1] = (va - vc) / (a - c)
    if b == c:
        sp[0] = slp[0]
    else:
        sp[0] = (vb - vc) / (b - c)
    return interval.Interval(sp)

# Generic class for expressions
class Slope:
    """
    A class for slopes
    """
    # If true then reeval range at every step
    flagRecompRange = False

    # If true then account convexity/concavity
    flagEvalConv = False

    def __init__(self, x, val = None):
        """
        The constructor
        :param x: the source interval for x
        :param val: the point in the interval to compute slope (if different from the center
        """
        if val == None:
            self.value = 0.5 * (x[0] + x[1])
        else:
            self.value = val
        # The Slope
        self.S = interval.Interval([1,1])
        # The Source Interval
        self.x = interval.Interval([x[0], x[1]])
        # The resulting range
        self.range = interval.Interval([x[0], x[1]])
        if Slope.flagEvalConv:
            # The convexity flag
            self.conv = True
            # The concavity flag
            self.conc = True
            # Value at the left end
            self.va = x[0]
            # Value at the right end
            self.vb = x[1]
            # The point within the interval
            self.c = self.value

    def comp_slopes_bound(self):
        """
        Evaluates the slopes bound
        :return:
        the computed slopes bound
        """
        c = self.x.mid()
        xc = self.x - interval.Interval([c, c])
        fc = interval.Interval([self.value, self.value])
        bnd = fc + self.S * xc
        self.range.intersec(bnd)
        return bnd

    def comp_conv_slopes(self):
        """
        For convex/concave functions return
        :return:
        """
        if self.conv:
            s = comp_conv_slope(self.x[0], self.x[1], self.c, self.va, self.vb, self.value, self.S)
        elif self.conc:
            s = comp_conc_slope(self.x[0], self.x[1], self.c, self.va, self.vb, self.value, self.S)
        print("s = ", s, "self.S = ", self.S)
        self.S.intersec(s)

    def __repr__(self):
        if Slope.flagEvalConv:
            return "value = " + str(self.value) + ", slope = " + str(self.S) + ", range = " + str(self.range) \
                   + ", x = " + str(self.x) + ", conv = " + str(self.conv) + ", conc = " + str(self.conc) \
                   + ", va = " + str(self.va) + ", vb = " + str(self.vb) + ", c = " + str(self.c)
        else:
            return "value = " + str(self.value) + ", slope = " + str(self.S) + ", range = " + str(self.range) \
                   + ", x = " + str(self.x)

    def __neg__(self):
        nexpr = Slope(self.x)
        nexpr.value = - self.value
        nexpr.S = - self.S
        nexpr.x = self.x
        nexpr.range = - self.range
        if Slope.flagEvalConv:
            nexpr.va = - self.va
            nexpr.vb = - self.vb
            nexpr.c = self.c
            if not (self.conc and self.conv):
                if self.conv:
                    nexpr.conc = True
                    nexpr.conv = False
                elif self.conc:
                    nexpr.conv = True
                    nexpr.conc = False
                else:
                    nexpr.conv = False
                    nexpr.conc = False
        # if Slope.flagRecompRange:
        #     nexpr.comp_slopes_bound()
        return nexpr

    def __add__(self, eother):
        nexpr = Slope(self.x)
        etmp = valueToSlope(eother, self.x)
        nexpr.value = self.value + etmp.value
        nexpr.S = self.S + etmp.S
        nexpr.x = self.x
        nexpr.range = self.range + etmp.range
        if Slope.flagEvalConv:
            nexpr.va = self.va + eother.va
            nexpr.vb = self.vb + eother.vb
            nexpr.c = self.c
            if self.conv and etmp.conv:
                nexpr.conv = True
            elif self.conc and etmp.conc:
                nexpr.conc = True
            else:
                nexpr.conv = False
                nexpr.conc = False
            nexpr.comp_conv_slopes()
        if Slope.flagRecompRange:
            nexpr.comp_slopes_bound()
        return nexpr

    def __radd__(self, eother):
        return self.__add__(eother)

    def __sub__(self, eother):
        nexpr = Slope(self.x)
        etmp = valueToSlope(eother, self.x)
        nexpr.value = self.value - etmp.value
        nexpr.S = self.S - etmp.S
        nexpr.x = self.x
        nexpr.range = self.range - etmp.range
        if Slope.flagEvalConv:
            nexpr.conv = False
            nexpr.conc = False
        if Slope.flagRecompRange:
            nexpr.comp_slopes_bound()
        return nexpr

    def __rsub__(self, eother):
        etmp = valueToSlope(eother, self.x)
        return etmp.__sub__(self)

    def __mul__(self, eother):
        nexpr = Slope(self.x)
        etmp = valueToSlope(eother, self.x)
        nexpr.value = self.value * etmp.value
        nexpr.S = self.range * etmp.S + self.S * etmp.range
        nexpr.x = self.x
        nexpr.range = self.range * etmp.range
        if Slope.flagEvalConv:
            nexpr.conv = False
            nexpr.conc = False
        if Slope.flagRecompRange:
            nexpr.comp_slopes_bound()
        return nexpr

    def __rmul__(self, eother):
        return self.__mul__(eother)

    def __pow__(self, k):
        nexpr = Slope(self.x)
        nexpr.value = self.value ** k
        nexpr.range = self.range ** k
        if k == 2:
            sp = self.range + interval.Interval([self.value, self.value])
        elif k % 2:
            sp = comp_conv_slope(self.range[0], self.range[1], self.value,
                                 self.range[0] ** k, self.range[1] ** k, nexpr.value, k * self.value ** (k - 1))
        else:
            if self.range[0] >= 0:
                sp = comp_conv_slope(self.range[0], self.range[1], self.value,
                                     self.range[0] ** k, self.range[1] ** k, nexpr.value, k * self.value ** (k - 1))
            elif self.range[1] <= 0:
                sp = comp_conc_slope(self.range[0], self.range[1], self.value,
                                     self.range[0] ** k, self.range[1] ** k, nexpr.value, k * self.value ** (k - 1))
            else:
                sp = interval.Interval([k, k]) * (self.range ** (k - 1))
        nexpr.S = self.S * sp
        if Slope.flagEvalConv:
            nexpr.conv = False
            nexpr.conc = False
            nexpr.va = self.va ** k
            nexpr.vb = self.vb ** k
            nexpr.c = self.c
            if k % 2 == 1:
                if self.range[0] >= 0:
                    nexpr.conv = self.conv
                elif self.range[1] <= 0:
                    nexpr.conc = self.conc
            else:
                if self.range[0] >= 0:
                    nexpr.conv = self.conv
                elif self.range[1] <= 0:
                    nexpr.conc = self.conc
        if Slope.flagRecompRange:
            nexpr.comp_slopes_bound()
        return nexpr

def valueToSlope(expr, x):
    if isinstance(expr, int):
        etmp = const(expr, x)
    elif isinstance(expr, float):
        etmp = const(expr, x)
    else:
        etmp = expr
    return etmp

    # def __call__(self, eother):
    #     nexpr = Expr()
    #     return nexpr

# Constant expression
class const(Slope):
    def __init__(self, value, x):
        self.value = value
        self.S = interval.Interval([0,0])
        self.x = interval.Interval([x[0], x[1]])
        self.range = interval.Interval([value, value])
        if Slope.flagEvalConv:
            self.conc = True
            self.conv = True
            self.a = x[0]
            self.b = x[1]
            self.c = value

# Literal
# class ident(Slope):
#     def __init__(self, x):
#         self.value = 0.5 * (x[0] + x[1])
#         self.S = interval.Interval([1,1])
#         self.x = interval.Interval([x[0], x[1]])
#         self.range = interval.Interval([x[0], x[1]])

class sin(Slope):
    def __init__(self, eother):
        self.x = eother.x
        self.value = math.sin(eother.value)
        self.range = interval.sin(eother.range)
        if Slope.flagEvalConv:
            self.conv = False
            self.conc = False
        sp = interval.Interval([0, 0])
        if eother.value == eother.range[0] or eother.value == eother.range[1]:
            sp = interval.cos(eother.range)
        else:
            pil = math.floor(math.floor(eother.range[0] / math.pi))
            piu = math.ceil(math.ceil(eother.range[1] / math.pi))
            if piu == pil + 1:
                if piu % 2 == 0:
                    sp = comp_conc_slope(eother.range[0], eother.range[1], eother.value,
                                         math.sin(eother.range[0]), math.sin(eother.range[1]), self.value, math.cos(self.value))
                else:
                    sp = comp_conv_slope(eother.range[0], eother.range[1], eother.value,
                                         math.sin(eother.range[0]), math.sin(eother.range[1]), self.value, math.cos(eother.value))
            else:
                sp = interval.cos(eother.range)
        self.S = eother.S * sp
        if Slope.flagRecompRange:
            self.comp_slopes_bound()

class cos(Slope):
    def __init__(self, eother):
        self.x = eother.x
        self.value = math.cos(eother.value)
        self.range = interval.cos(eother.range)
        if Slope.flagEvalConv:
            self.conv = False
            self.conc = False
        sp = interval.Interval([0, 0])
        if eother.value == eother.range[0] or eother.value == eother.range[1]:
            sp = - interval.sin(eother.range)
        else:
            pi05 = 0.5 * math.pi
            pil = math.floor(math.floor(eother.range[0] + pi05/ math.pi))
            piu = math.ceil(math.ceil(eother.range[1]  + pi05 / math.pi))
            if piu == pil + 1:
                if piu % 2 == 0:
                    sp = comp_conc_slope(eother.range[0], eother.range[1], eother.value,
                                         math.cos(eother.range[0]), math.cos(eother.range[1]), self.value,
                                         interval.Interval([-math.sin(eother.value), -math.sin(eother.value)]))
                else:
                    sp = comp_conv_slope(eother.range[0], eother.range[1], eother.value,
                                         math.cos(eother.range[0]), math.cos(eother.range[1]), self.value,
                                         interval.Interval([-math.sin(eother.value), -math.sin(eother.value)]))
            else:
                sp = - interval.sin(eother.range)
        self.S = eother.S * sp
        if Slope.flagRecompRange:
            self.comp_slopes_bound()

class exp(Slope):
    def __init__(self, eother):
        self.x = eother.x
        self.value = math.exp(eother.value)
        self.range = interval.exp(eother.range)
        if Slope.flagEvalConv:
            self.conv = eother.conv
            self.conc = False
            self.va = math.exp(eother.va)
            self.vb = math.exp(eother.vb)
            self.c = eother.c
        sp = interval.Interval([0, 0])
        sp = comp_conv_slope(eother.range[0], eother.range[1], eother.value,
                             math.exp(eother.range[0]), math.exp(eother.range[1]),
                             self.value, interval.Interval([self.value, self.value]))
        self.S = eother.S * sp
        if Slope.flagEvalConv:
            self.comp_conv_slopes()
        if Slope.flagRecompRange:
            self.comp_slopes_bound()

class log(Slope):
    def __init__(self, eother):
        self.x = eother.x
        self.value = math.log(eother.value)
        self.range = interval.log(eother.range)
        if Slope.flagEvalConv:
            self.conv = False
            self.conc = eother.conc
            self.va = math.log(eother.va)
            self.vb = math.log(eother.vb)
            self.c = eother.c
        sp = comp_conc_slope(eother.range[0], eother.range[1], eother.value,
                             math.log(eother.range[0]), math.log(eother.range[1]),
                             self.value, interval.Interval([1/eother.value, 1/eother.value]))
        self.S = eother.S * sp
        if Slope.flagEvalConv:
            self.comp_conv_slopes()
        if Slope.flagRecompRange:
            self.comp_slopes_bound()

# class log(Expr):
#     def __init__(self, eother, base = math.e):
#         self.x = eother.x
#         self.value = math.log(eother.value, base)
#         self.range = interval.log(eother.range, base)
#         sp = interval.Interval([0, 0])
#         if eother.value == eother.range[0] or eother.value == eother.range[1]:
#             sp = self.range
#         else:
#             sp = compConvSlope(self.range, self.value, eother.range, eother.value)
#         self.S = eother.S * sp
#         self.compSlopesBound()

# Check code
if (__name__ == '__main__'):

    # help(Slope)
    def f(x):
        # return x ** 3
        # return x**2 - 4 * x + 2
        # return  (x + sin(x)) * exp(-(x**2))
        # return x**4 - 10 * x**3 + 35 * x**2 - 50 * x + 24
        # return (log(x + 1.25) - 0.84 * x)**2
        # return  0.02 * x**2 - 0.03 * exp(- (20 * (x - 0.875))**2)
        return log(x**4 + x**2 + x)
        # return x**4 - 12 * x**3 + 47 * x**2 - 60 * x - 20 * exp(-x)
        # return x**6 - 15 * x**4 + 27 * x**2 + 250

        # return  (ident(x) + cos(ident(x) - const(0.5 * math.pi, x))) * exp(- (ident(x)**2))
        # return exp(sin(ident(x)) * (ident(x)**2 - const(4, x) * ident(x) + const(2, x)))
        # return const(4, x) * ident(x)
        # return sin(x) + sin(10 / 3 * x)
    # x = [1,7]
    x = [0.75,1.75]

    Slope.flagRecompRange = False
    s = Slope(x)
    ex1 = f(s)
    print("Slope = ", ex1)
    print("bnd = ", ex1.comp_slopes_bound())

    Slope.flagRecompRange = True
    ex2 = f(Slope(x))
    print("Improved slope = ", ex2)
    print("bnd = ", ex2.comp_slopes_bound())

    Slope.flagEvalConv = True
    ex3 = f(Slope(x))
    print("Improved slope + covexity check = ", ex3)
    print("bnd = ", ex3.comp_slopes_bound())


# pip install sinchsms
import time
from time import sleep
from sinchsms import SinchSMS

#   Function for sending SMS
def sendSMS():
    #   Enter all the details , get app_key and app_secret by registering, A app on sinchSMS
    number = 'your_mobile_number'
    app_key = 'your_app_key'
    app_secret = 'your_app_secret'

    # Enter the message to be sent
    message = 'This is Message send from python :)'

    client = SinchSMS(app_key, app_secret)
    print("Send '%s' to %s" % (message, number))

    response = client.send_message(number, message)
    message_id = response['messageId']
    response = client.check_status(message_id)

    # Keep trying unless the status returned is Successful
    while response['status'] != 'Successful':
        print(response['status'])
        time.sleep(1)
        response = client.check_status(message_id)

    print(response['status'])

if __name__ == "__main__":
    sendSMS()

'''
Note
You will need a Sinch account for getting your application key and secret. Visit www.sinch.com to get started

Using as command line script:
./sinchsms.py
usage: sinchsms.py <application key> <application secret> send <number> <message> <from_number>
       sinchsms.py <application key> <application secret> status <message_id>
'''


import os
import os.path as osp
import random

class CommonFolderScanner(object):
    """CommonFolderScanner

        Arguments:
            root_folder {string} -- which folder to scan

        Keyword Arguments:
            max_depth {int} -- the max_depth to scan (default: {1})
            classification_depth {int} -- classifcate by folder name in what depth (default: {1})
            file_type {list} -- default filter function used to filter file type (default: {['jpg']})
                                if file_filter is not none this para will be ignored
            file_filter{function} -- you can impl a filter function instead the default one,recieve a fullpath filename and return a bool (default: None)
            combine_same_dir_as_one_class {bool} -- whether combine the same folder of different father folder (default: {True})
    """

    def __init__(self, root_folder, max_depth=1, classification_depth=1, file_type=['jpg'], file_filter=None, combine_same_dir_as_one_class=True):

        self.root_folder = os.path.normpath(root_folder)
        self.max_depth = max_depth
        self.classification_depth = classification_depth
        self.file_type = file_type
        self.filter = file_filter
        self.combine = combine_same_dir_as_one_class

    def scan_folder(self):
        """Scan the root folder and find out needed files
           and labeled it with folders' names

        Returns:
            [dict] -- [{'classname':file list}]
        """
        assert self.max_depth >= self.classification_depth, 'max_depth should be larger than classification_depth'
        assert osp.exists(
            self.root_folder), '%s is not a directory' % self.root_folder
        g = os.walk(self.root_folder, topdown=True)
        res_for_imglist = []
        res_for_classification = {}
        for _, (path, _, files) in enumerate(g):
            new_path = path[len(self.root_folder):]
            depth = new_path.count(os.path.sep)
            if depth > self.max_depth:
                continue
            if self.classification_depth <= depth:
                if self.combine:
                    classname = new_path.split(os.path.sep)[
                        self.classification_depth]
                else:
                    classname = new_path.rsplit(
                        osp.sep, depth-self.classification_depth)[0]
                    classname = classname.replace(osp.sep, '_')
            else:
                continue
            for f in files:
                fullpath_f = osp.join(new_path, f)
                if self.filter_file(fullpath_f):
                    res_for_imglist.append(fullpath_f)
            if classname in res_for_classification:
                res_for_classification[classname] += res_for_imglist
            else:
                res_for_classification[classname] = res_for_imglist
            res_for_imglist = []
        return res_for_classification

    def create_trainvaltest(self, dst_path=None, rate=(3, 1, 1)):
        """Create train val test txt files using result returned by scan_folder

        Keyword Arguments:
            dst_path {string} -- where the txt files to save (default: {None})
            rate {tuple} -- train:val:test (default: {(3, 1, 1)})
        """
        if dst_path is None:
            save_root = '.'
        else:
            save_root = dst_path
        assert osp.exists(save_root), '%s does\'nt exist' % save_root
        res = self.scan_folder()
        val_rate = rate[1] / sum(rate)
        test_rate = rate[2] / sum(rate)
        for i, classname in enumerate(res):
            class_i_imgs = res[classname]
            random.shuffle(class_i_imgs)
            total = len(class_i_imgs)
            val_count = int(total*val_rate)
            test_count = int(total*test_rate)
            class_i_imgs_for_val = class_i_imgs[0:val_count]
            class_i_imgs_for_test = class_i_imgs[val_count:val_count+test_count]
            class_i_imgs_for_train = class_i_imgs[val_count+test_count:]
            label = i
            with open(osp.join(save_root, 'train.txt'), 'a') as f:
                f.writelines(['%s %d\n' % (x, label)
                              for x in class_i_imgs_for_train])
            with open(osp.join(save_root, 'val.txt'), 'a') as f:
                f.writelines(['%s %d\n' % (x, label)
                              for x in class_i_imgs_for_val])
            with open(osp.join(save_root, 'test.txt'), 'a') as f:
                f.writelines(['%s %d\n' % (x, label)
                              for x in class_i_imgs_for_test])
            with open(osp.join(save_root, 'classnames.txt'), 'a') as f:
                f.write('%d\t%-s\n' % (label, classname))
            with open(osp.join(save_root, 'trainvaltest_all.txt'), 'a') as f:
                f.writelines(['%s %d\n' % (x, label) for x in class_i_imgs])

    def filter_file(self, filename):
        '''To filter the file, eg. filetype or check the file validation

        Arguments:
            filename {string} -- a filename full path string

        Returns:
            bool -- whether this file is OK or not
        '''
        if self.filter is not None:
            assert hasattr(self.filter,'__call__'),'filter need to be a function'
            res = self.filter(filename)
            assert isinstance(res,bool),'filter must return a bool'
            return res
        for _type in self.file_type:
            if filename.endswith(_type):
                return True
        return False

def main():
    scanner = CommonFolderScanner(
        './', max_depth=5, classification_depth=1, combine_same_dir_as_one_class=True)
    # res = scanner.scan_folder(combine_same_dir_as_one_class=True)
    scanner.create_trainvaltest()

if __name__ == '__main__':
    main()


from .chicago_encyclopedia_extractor import ChicagoEncyclopediaExtractor
from .data_extraction_paths import DataExtractionPaths
from .entitiesextractor import EntitiesExtractor

class DataExtractorUtils:

    @staticmethod
    def get_chicago_crime_data(embedding_model_path, embedding_model_name):
        print("Extracting entities from chicago encyclopedia...")
        extractor = ChicagoEncyclopediaExtractor(output_target_file=
            DataExtractionPaths.CHICAGO_ENCYCLOPEDIA_TEXT_DATA_PATH)
        chicago_encyclopedia_phrases = extractor.load_entities(
            input_source_file=DataExtractionPaths.CHICAGO_ENCYCLOPEDIA_ENTITIES_PATH)
        print("Completed entities phrases from chicago encyclopedia...[" + str(len(chicago_encyclopedia_phrases)) + "]")

        print("Extracting entities from knowledgebase...")
        entity_lookup = EntitiesExtractor(
            embedding_model_path=embedding_model_path, embedding_model_name=embedding_model_name)
        entity_lookup.extract_from_knowledgebase(DataExtractionPaths.CHICAGO_CRIME_KNOWLEDGEBASE_PATH)

        named_entities = []
        for term in entity_lookup.get_all_terms():
            entity_name = entity_lookup.get_name(term.lower())
            entity_value = term.lower()
            named_entities.append((entity_name, entity_value))
        print("Completed extracting entities from knowledgebase...[" + str(len(named_entities)) + "]")

        print("Starting extracting regular expressions from knowledgebase...")
        regular_expressions = [regular_expression_entity.get_value() for regular_expression_entity \
                               in entity_lookup.get_all_regular_expression_entities() if \
                               regular_expression_entity.get_data_attribute() is not None]
        print("Completed extracting regular expressions from knowledgebase...[" + str(len(regular_expressions)) + "]")

        print("Merging all of the entities...")
        for term in chicago_encyclopedia_phrases:
            entity_name = 'unknown'
            entity_value = term
            named_entities.append((entity_name, entity_value))
        print("Completed merging all of the entities...[" + str(len(named_entities)) + "]")

        return entity_lookup, named_entities, regular_expressions


import random

high_score = 0

def roll_dice():
        global high_score
        roll_a = random.randint(1, 6)
        roll_a2 = random.randint(1, 6)
        total = roll_a + roll_a2

        print("You roll a...", str(roll_a))
        print("You roll a...", str(roll_a2))
        print()

        print("You have rolled a total of: ",str(total))
        print()

        if total > high_score:
            print("New high score!")
            print()
            high_score = total

def dice_game():
        while True:
            print("Current High Score: ",str(high_score))

            choice = input("1) Roll Dice\n2) Leave Game\nEnter Your choice: ")
            print()

            if choice == "1":
                roll_dice()
            elif choice == "2":
                  print("Goodbye!")
                  break
            else:
                  continue

dice_game()


from django import forms
from pods.models import Pod, Discussion, Comment

class PodEnrollForm(forms.Form):
    pod = forms.ModelChoiceField(queryset=Pod.objects.all(),widget=forms.HiddenInput)

class DiscussionForm(forms.ModelForm):
    class Meta:
        model = Discussion
        fields = ('title', 'body')

        Widgets = {
            'Title': forms.TextInput(),
            'Body': forms.Textarea(),
        }

class CommentForm (forms.ModelForm):
    body = forms.CharField(widget=forms.Textarea(attrs={
        'class': 'md-textarea form-control',
        'placeholder': 'comment here...',
        'rows': '4',
    }))

    class Meta:
        model = Comment
        fields = ('body',)


import json
import os
import mimetypes
import uuid

from flask import request, flash, redirect, url_for, Blueprint, make_response, Response
from werkzeug.utils import secure_filename

from modul_app.database.api_key_repository import check_api_key
from modul_app.models.ResponseModel import ErrorResponseModel
from modul_app.models.my_file import MyFile
from modul_app.xlsx_analyzer import XlsxAnalyzer
from modul_app.main import app

from modul_app.database.process_repository import (
    get_process_by_id,
    put_file,
    get_file,
    delete_file
)

from modul_app.database.file_repository import (insert_my_file, save_result_file_in_db, delete_template_file)

xlsx = Blueprint('xlsx', __name__)

ALLOWED_EXTENSIONS = {'xlsx', 'json'}

def allowed_file(filename):
    """ Функция проверки расширения файла """
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# Генерация документа сиюминутным способом со стороны стороннего сервиса через api
@xlsx.route("/api/generate/now/file-xlsx/", methods=['POST'])
async def api_now_file_xlsx():
    api_key = request.headers.environ.get('HTTP_AUTHORIZATION')
    if api_key is None or not await check_api_key(api_key):
        return ErrorResponseModel("Error api-key", 400, "Invalid api-key")
    if not request.files.get('file', None):
        return ErrorResponseModel("Error data", 400, "Files not Found")
    list_filenames = await create_filenames_for_xlsx()
    files = request.files.getlist("file")
    if len(files) != 2:
        return ErrorResponseModel('Error count Files', 400, 'The number of files must be equal to 2')
    have_xlsx = False
    have_json = False
    for file in files:
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            if filename.endswith('.xlsx') and not have_xlsx:
                have_xlsx = True
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], list_filenames[0]))
            elif filename.endswith('.json') and not have_json:
                have_json = True
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], list_filenames[1]))
            else:
                return ErrorResponseModel('Error data', 400, 'One of the file types was not detected')
        else:
            return ErrorResponseModel('Error data', 400, 'Invalid file type')
    await xlsx_worker(list_filenames[0], list_filenames[1], list_filenames[2])
    # Открытие сохранённого готового файла
    save_file = open(os.path.join(app.config['UPLOAD_FOLDER'], list_filenames[2]), 'rb')
    file = save_file.read()
    save_file.close()
    await delete_template_file(list_filenames[0], list_filenames[1], list_filenames[2])
    # Подготавливаем ответ
    response = make_response(file)
    _type = mimetypes.guess_type(list_filenames[2])
    response.mimetype = _type[0]
    return response

@xlsx.route("/api/generate/now/file-xlsx/<process_id>", methods=['POST'])
async def api_now_file_xlsx_with_process(process_id):
    api_key = request.headers.environ.get('HTTP_AUTHORIZATION')
    if api_key is None or not await check_api_key(api_key):
        return ErrorResponseModel("Error api-key", 400, "Invalid api-key")
    process = get_process_by_id(process_id)
    if process is None:
        return ErrorResponseModel("Error process", 400, "Process not Found")
    if process["file_type"] != "xlsx":
        return ErrorResponseModel("Error process", 400, "The template file type does not match the api request")
    if request.files.get('file', None):
        json_file = request.files['file']
        if not json_file.filename.endswith('.json'):
            return ErrorResponseModel("Error data", 400, "Invalid file type")
        list_filenames = await create_filenames_for_xlsx()
        await start_create_xlsx_with_process(process_id, json_file, list_filenames, True)
        # Открытие сохранённого готового файла
        save_file = open(os.path.join(app.config['UPLOAD_FOLDER'], list_filenames[2]), 'rb')
        file = save_file.read()
        save_file.close()
        await delete_template_file(list_filenames[0], list_filenames[1], list_filenames[2])
        # Подготавливаем ответ
        response = make_response(file)
        _type = mimetypes.guess_type(list_filenames[2])
        response.mimetype = _type[0]
        return response
    return ErrorResponseModel("Error data", 400, "File not Found")

@xlsx.route("/api/generate/file-xlsx/<process_id>", methods=['POST'])
async def api_file_xlsx_with_process(process_id):
    api_key = request.headers.environ.get('HTTP_AUTHORIZATION')
    if api_key is None or not await check_api_key(api_key):
        return ErrorResponseModel("Error api-key", 400, "Invalid api-key")
    process = get_process_by_id(process_id)
    if process is None:
        return ErrorResponseModel("Error process", 400, "Process not Found")
    if process["file_type"] != "xlsx":
        return ErrorResponseModel("Error process", 400, "The template file type does not match the api request")
    if request.files.get('file', None):
        json_file = request.files['file']
        if not json_file.filename.endswith('.json'):
            return ErrorResponseModel("Error data", 400, "Invalid file type")
        list_filenames = await create_filenames_for_xlsx()
        file_id = await start_create_xlsx_with_process(process_id, json_file, list_filenames)
        # Подготавливаем ответ
        response = Response()
        response.status_code = 202
        response.location = request.host_url + url_for('process.download_xlsx_result_file_api', file_id=file_id)
        return response
    return ErrorResponseModel("Error data", 400, "File not Found")

@xlsx.route("/generate/file-xlsx/<process_id>", methods=['POST'])
async def file_xlsx(process_id):
    if request.files.get('file', None):
        json_file = request.files['file']
        if not json_file.filename.endswith('.json'):
            flash('Файл должен быть типа json!')
            return redirect(url_for('process.open_process', id=process_id))
        list_filenames = await create_filenames_for_xlsx()
        await start_create_xlsx_with_process(process_id, json_file, list_filenames)
    else:
        flash('Файл не выбран!')
    return redirect(url_for('process.open_process', id=process_id))

async def start_create_xlsx_with_process(process_id, json_file, list_filenames: list, is_now=False):
    process = get_process_by_id(process_id)
    template_file_id = process['file_id']
    template_file_byte = get_file(template_file_id)
    # Временная загрузка шаблонного файла на пк
    output = open(os.path.join(app.config['UPLOAD_FOLDER'], list_filenames[0]), 'wb')
    output.write(template_file_byte)
    output.close()
    # Временная загрузка json данных на пк
    json_file.save(os.path.join(app.config['UPLOAD_FOLDER'], list_filenames[1]))
    # Запуск генерации документа
    await xlsx_worker(list_filenames[0], list_filenames[1], list_filenames[2])
    if not is_now:
        file_id = await save_result_file_in_db(list_filenames[2], process_id)
        # Удаление ранее созданных файлов
        await delete_template_file(list_filenames[0], list_filenames[1], list_filenames[2])
        return file_id

# Создание документа из xlsx
async def xlsx_worker(template_filename: str, json_filename: str, result_filename: str):
    # Чтение json файла из временного хранилища
    with open(os.path.join(app.config['UPLOAD_FOLDER'], json_filename), encoding="utf8") as read_file:
        data = json.load(read_file)
        read_file.close()
    # Создание объекта класса обработки docx файлов
    document = XlsxAnalyzer()
    # Инициализация шаблона как документа
    document.open_document(os.path.join(app.config['UPLOAD_FOLDER'], template_filename))
    # Инициализация данных из json
    document.init_data(data)
    # Поиск токенов
    document.start_search()
    # Замена токенов
    document.start_replace()
    # Сохранение готового файла
    document.save_document(os.path.join(app.config['UPLOAD_FOLDER'], result_filename))

# Создание временных имён для файлов
async def create_filenames_for_xlsx() -> list:
    # Генерация временного имени шаблонного файла
    template_filename = str(uuid.uuid4()) + '.xlsx'
    # Генерация временного имена готового файла
    result_filename = str(uuid.uuid4()) + '.xlsx'
    # Генерация временног имени для файла с данными
    json_data_filename = str(uuid.uuid4()) + '.json'
    return [template_filename, json_data_filename, result_filename]


"""
REPLACE THIS LINE WITH YOUR NAME
"""

from abc import ABCMeta, abstractmethod

# There are two families of related products
# AbstractProductA
class Pizza(metaclass=ABCMeta):
    @abstractmethod
    def cook(self):
        pass

# ConcreteProductA1
class HawaiianPizza(Pizza):
    def cook(self):
        print("HawaiianPizza - ham & pineapple")

# ConcreteProductA2
class CheesePizza(Pizza):
    def cook(self):
        print("DeluxPizza - Cheddar & Mozzarella")

# AbstractProductB
class Chinese(metaclass=ABCMeta):
    @abstractmethod
    def cook(self):
        pass

# ConcreteProductB1
class Dumplings(Chinese):
    def cook(self):
        print("Dumplings - ham & pineapple")

# ConcreteProductB2
class MoonCake(Chinese):
    def cook(self):
        print("MoonCake - sesame seeds, ground lotus seeds and duck eggs")

"""
The CLIENT code below currently has to make too many decisions
and know all about the food choices

Change things by applying the ABSTRACT FACTORY pattern
so the client only has to decide the type of feast
and does not need to know the details of feast preparation.

To make things simpler can you please ..
get rid of the constants (too much to remember)
get rid of the case statements (too difficult to maintain)

"""
CHINESE = 1
PIZZA = 2

def feast(type):
    print("Main")
    main = None
    desert = None
    if type == PIZZA:
        main = CheesePizza()
    elif type == CHINESE:
        main = Dumplings()
    main.cook()
    print("Desert")
    if type == PIZZA:
        desert = HawaiianPizza()
    elif type == CHINESE:
        desert = MoonCake()
    desert.cook()

if __name__ == "__main__":
    print("***A Chinese feast***")
    feast(CHINESE)
    print("***A Pizza feast***")
    feast(PIZZA)


"""
macro parsing

this module parses C code with some custom extensions, and upon binding with a code-generator,
it emits valid backend-specific code instead. this serves to paper over the differences
that exist in the backends, and allows the extension of plain C with some preprocessing functionality
that integrate nicely with the rest of fruityloop

the full list of features supported:
    nd-array awareness:
        nd-array indexing (array_id(idx0, idx1...)); round-bracketed to avoid conflict with POC array indexing
        shape attributes on nd-arrays

    stencil support:
        unrolled loops over stencils: ( for (s in stencil) {s.weight;} )
        access to stencil attributes ( stencil.size; )

    fully qualified numpy style typenames (uint32, float64, andsoforth)
    templated type arguments (<type_id>)

    atomic substitution: (openCL syntax is used)

    integer looping ( for (id in start:stop){} )

many more features could easily be added, as long as they are fully backwards compatible with POC

"""

from parsing import *

def replace_atomics(cg, source):
    """
    replace openCL-style atomics with backend specific atomic operations
    """
    replacement = cg.atomic_op

    op = oneOf('add sub inc dec min max')
    atomic_grammar = Literal('atomic_') + op('op')

    def replace(s,l,t):
        return replacement(t.op)
    atomic_grammar.setParseAction(replace)
    return atomic_grammar.transformString(source)

def replace_type_templates(cg, source):
    """
    replace numpy types with c-types. this could be more efficient and intelligent...
    we do not do any semantic analysis here; simple find and replace
    but that should suffice, no?
    """
    type_grammar = angleBracketedExpr(identifier('template'))
    def replace(s,l,t):
        return cg.declaration.templates[t.template]
    type_grammar.setParseAction(replace )
    return type_grammar.transformString(source)

def replace_typing(cg, source):
    """
    replace numpy types with c-types. this could be more efficient and intelligent...
    we do not do any semantic analysis here; simple find and replace
    but that should suffice, no?
    """
    replacement = cg.type_specifier
    type_grammar = dtype_term.copy()
    type_grammar.setParseAction(lambda s,l,t: replacement(t[0]))
    return type_grammar.transformString(source)

def replace_shape_syntax(cg, source):
    """
    replace arrayidentifier.shape[ndim] syntax with C named variables
    silently fails to replace some wrong syntax, like misspelled shape;
    dont worry, the cuda compiler is sure to complain about it :)
    would it be sufficient and currect to catch all instances of 'arrayidentifier.'+whatever,
    that fail to match the whole syntax?
    """
    declaration = cg.declaration

    arrayidentifier = (Word(alphanums+'_')).setResultsName('identifier') # + Optional( Word(alphanums))
    positive_integer = Word(nums)
    shape_expr = arrayidentifier + Suppress( Literal('.shape')) + nestedExpr('[',']', positive_integer).setResultsName('dimension')

    def replace(s,l,t):
        """if match is correct, replace numpy syntax with c-compatible syntax"""
        identifier = t.identifier
        dimensions = t.dimension[0]
        if not len(dimensions)==1: raise Exception('only simple shape indexing allows')
        dimension = dimensions[0]
        try:
            arg = declaration.arguments[identifier]
        except KeyError:
            raise ParseFatalException("array '{identifier}' is not defined".format(identifier=identifier))
        try:
            size = arg.shape[int(dimension)]
        except Exception:
            raise ParseFatalException('{identifier}.shape[{dimension}] is invalid'.format(identifier=identifier, dimension=dimension))

        return '{identifier}_shape_{dimension}'.format(identifier=identifier, dimension=dimension)
    shape_expr.setParseAction(replace)

    return shape_expr.transformString(source)

def replace_array_syntax(cg, source):
    """
    replace weave.blitz style array indexing with inner product over strides
    we could optionally insert bounds checking code here as well, as a debugging aid
    should we allow for partial indexing? not sure; disallowed atm

    we could do compile-time bounds checking, for cases where the shapes are know at compile time
    and the presumably predictable reserved indexing symbols i{n} are used
    """
    declaration = cg.declaration
    replacement = cg.indexing_expression

    arrayidentifier = oneOf(' '.join(declaration.array_identifiers))('arrayidentifier')
##    index = Or([identifier, positive_integer])
##    index = Word( printables.replace('()',''))
    #note; updated parsing expression allows for braced expressions within the indexing statement
    index_expr = arrayidentifier + originalTextFor( nestedExpr())('indices')

    def replace(s,l,t):
        """if match is correct, replace numpy syntax with c-compatible syntax"""
        identifier = str( t.arrayidentifier)
        indices = tuple(t.indices.strip('()').split(','))

        try:
            arg = declaration.arguments[identifier]
        except KeyError:
            raise ParseFatalException("array '{identifier}' is not defined".format(identifier=identifier))

        if not len(indices)==arg.ndim:
            raise Exception("indexing '{identifier}' requires {ndim} arguments".format(identifier=identifier, ndim=arg.ndim))

        return replacement(arg=arg, indices=indices)

    index_expr.setParseAction(replace)
    return index_expr.transformString(source)

def replace_for_syntax(cg, source):
    """
    replace: 'for (id in start:stop:step)'
    with:    'for (int id=start; start<stop; id+=step)'
    rather trivial syntactic sugar indeed
    we could implement an unrolling mechanism here too,
    in case all params are known at compile time, and loop is small?
    """
    replacement = cg.for_statement

    index = Or([sign_wrap(identifier), integer])
    colon = Suppress(Literal(':'))
    range = index.setResultsName('start') + colon + index.setResultsName('stop') + Optional(Combine(colon + index), '1').setResultsName('step')
    loop_expr = Literal('for') + '(' + identifier.setResultsName('index') + Literal('in') + range + ')'

    loop_expr.setParseAction(lambda s,l,t: replacement(**dict(t)))
    return loop_expr.transformString(source)

def replace_for_stencil_body(dummy, body):
    """
    expand stencil_dummy_id.property syntax
    to C-compatible underscore names
    """
    grammar = Literal(dummy) + Literal('.').setParseAction(replaceWith('_'))
    return grammar.transformString(body)

def replace_stencil_properties(cg, body):
    """
    expand stencil_dummy_id.property syntax
    to C-compatible underscore names
    """
    declaration = cg.declaration

    stencil_identifier = oneOf(' '.join(declaration.stencil_templates))
    attribute = Literal('size')('attribute')
    grammar = stencil_identifier('identifier') + '.' + attribute
    def replace(s,l,t):
        if t.attribute=='size':
            return declaration.get_stencil(t.identifier).size
    grammar.setParseAction(replace)
    return grammar.transformString(body)

def replace_for_stencil_syntax(cg, source):
    """
    replace: 'for (id in stencilid)'
    with:    iteration over the body
    expand dummy accessors as well, like s.weight, and s.kernel_axis
    this parsing operation needs to be nested
    first we must parse the declaration to obtain the dummy identifier
    only then can we cleanly parse the body

    only do unrolled loop for now
    giver each term in loop its own scope, so we can redeclare const vars within?

    need to do some thinking; what does the stencil loop over? an array or the kernel?
    we do padding per array; this argues for stenceling per array as well
    that is, we need to decide on a set of axes to apply the stencil over
    or should we simply generate a tuple of nameless offsets, and let
    the end user handle the indexing?
    could use array indexing syntax to get offsets
    or, explicitly declare the axes to broadcast the stencil over
    as in, for (s in stencil(i,j,k)) { array(s.i), andsoforth}
    nah; just broadcast stencil to match array dimension
    then bind to the array, copying the axis names of the array bound
    """

    declaration = cg.declaration

    unroll = True #deduce from syntax? or stencil object?

    array = oneOf(' '.join(declaration.array_identifiers))
    for_range = identifier('dummy') + 'in' + identifier('stencil') + roundBracketedExpr(array('array'))
    scoped_body = Combine( nestedExpr('{','}', Word(anything.translate(None, '{}'))))
    scoped_body.setParseAction(keepOriginalText)
    line_body = Combine( SkipTo(';', include=True))
    body = Or([scoped_body, line_body])('body')
    stencil_expr = (Literal('for') + roundBracketedExpr(for_range) + body)

    def replace(s,l,t):
        body = t.body
        dummy = t.dummy

        array = declaration.arguments[t.array]

        replaced_body = replace_for_stencil_body(dummy, body)

        def voxel(v):
            #get all stencil props here; list of tuples of offsets?
            #ideally, pull such constructs from codegen

            index   = 'const int {d_id}_{axis_id} = (int){axis_id} + {offset};'
            indexes = cg.statements(
                [index.format(offset=o, axis_id=a.identifier, d_id = dummy)
                    for o, a in zip(v.offset, array.shape)], newline=False)

            weight = 'const float32 {d_id}_weight = {weight};'.format(weight=v.weight, d_id=dummy)

            scope = cg.scope(
                cg.statements([
                    indexes,
                    weight,
                    replaced_body]))
            return scope

        #grab stencil from the template dict
        #if not implied by a padding keyword, explicitly add stencil decl to signature?
        stencil = declaration.get_stencil(t.stencil)

        return ''.join(voxel(v) for v in stencil.voxels())

    stencil_expr.setParseAction(replace)
    return stencil_expr.transformString(source)

def replace_output_reference_syntax(source):
    """
    scalar output args are passed by reference; they are actually shape=(1,) arrays
    we might need them by reference for atomic operations
    perhaps just add a & in those cases; treat it as a value type by placing a * everywhere
    in the body of code. does cuda C handle &*ptr==ptr correctly?
    """

def parse_body(body):
    """
    lazily parse body code
    that is, we return a function that will perform the parsing upon recieving a matching code generator
    """

    def inner(code_generator):
        b = dedent( body)

        b = replace_stencil_properties  (code_generator, b)
        b = replace_for_syntax          (code_generator, b)
        b = replace_for_stencil_syntax  (code_generator, b)
        b = replace_type_templates      (code_generator, b)
        b = replace_typing              (code_generator, b)
        b = replace_array_syntax        (code_generator, b)
        b = replace_atomics             (code_generator, b)
        return b

    return inner


'''
  Problem: Flexible Spaces
'''

width, partition  = [int(x) for x in input().split()]
locations         = [int(x) for x in input().split()]
output            = []

locations = [0] + locations + [width]

for i in range(len(locations) - 1, -1, -1):
  for j in range(i):
    if(locations[i] - locations[j] not in output):
      output.append(locations[i] - locations[j])

print(' '.join(str(x) for x in sorted(output)))


from implementation.agents.VillageAgent import VillageAgent
from implementation.places.FiniteFood import FiniteFood
from implementation.places.Tile import Tile
from implementation.pops.TestPop import TestPop
from implementation.settlements.Village import Village
from structure.Grid import Grid
from structure.places.Place import Place

class GridFactory:

    @classmethod
    def generate_places(cls, world, world_type, height, width):
        grid = Grid(world, height, width)
        if world_type == 'empty':
            for x in range(width):
                for y in range(height):
                    grid.places[x].append(Place(grid, x, y))

        elif world_type == 'test_food':
            for x in range(width):
                for y in range(height):
                    plc = FiniteFood(grid, x, y)
                    grid.places[x].append(plc)
                    plc.nomads.append(TestPop(plc))

        elif world_type == 'test_agriculture':
            # World config data
            num_settlements_per_tile = 1
            num_pops_per_settlement = 10
            # world generation
            for x in range(width):
                for y in range(height):
                    plc = Tile(grid, x, y)
                    grid.places[x].append(plc)
                    for i in range(num_settlements_per_tile):
                        vlg = Village(plc, num_pops_per_settlement)
                        vlg_ag = VillageAgent(vlg)
                        vlg.agents.append(vlg_ag)
                        plc.settlements.append(vlg)

        else:
            raise ValueError('no valid world type')

        return grid


from rdkit import Chem
from rdkit.Chem import Draw

import matplotlib.pyplot as plt
import numpy as np

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="")
    parser.add_argument(
        "--smiles", default="CCC1=[O+][Cu-3]2([O+]=C(CC)C1)[O+]=C(CC)CC(CC)=[O+]2"
    )
    parser.add_argument("--out_path", default="../data/mol.png")

    args = parser.parse_args()

    mol = Chem.MolFromSmiles(args.smiles)

    img = Draw.MolToImage(mol)

    img.save(open(args.out_path, "wb"))

    imgplot = plt.imshow(img)
    plt.show()


# 2739	 구구단

N = int(input())

for n in range(1,10):
    print(N, '*', n, '=', N * n)

# 10950	 A+B - 3

T = int(input())

for t in range(T):
    A, B = map(int, input().split())
    print(A + B)

# 8393	 합

n = int(input())
t = 0

for N in range(n + 1):
    t += N
print(t)

# 15552	 빠른 A+B

import sys

T = int(sys.stdin.readline())

for t in range(T):
    A, B = map(int, sys.stdin.readline().split())
    print(A + B)

# 2741	 N 찍기

N = int(input())

for n in range(1, (N + 1)):
    print(n)

# 2742	 기찍 N

N = int(input())

for n in range(N):
    print(N - n)

# 11021	 A+B - 7

T = int(input())

for x in range(1, (T + 1)):
    A, B = map(int, input().split())
    print(f'Case #{x}: {A} + {B} = {A + B}')

# 11022	 A+B - 8

T = int(input())

for x in range(1, (T + 1)):
    A, B = map(int, input().split())
    print('Case #{0}: {1}'.format(x, A + B))

# 2438	 별 찍기 - 1

N = int(input())

for n in range(1, (N + 1)):
    print('*' * n)

# 2439	 별 찍기 - 2

N = int(input())

for n in range(1, (N + 1)):
    print(' ' * (N - n) + '*' * n)

# 10871	 X보다 작은 수

N, X = map(int, input().split())
A = list(map(int, input().split()))

for i in range(N):
    if A[i] < X:
        print(A[i], end=" ")


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='home'),
    path('home', views.index, name='home'),
    path('reservation-form', views.registration_form, name='reservation-form'),
    path('new-customer', views.new_customer_form, name='new-customer'),
    path('find-room', views.find_room, name='find-room'),
    path('select-room', views.select_room, name='reservation-form'),
    path(
        'todays-reservations',
        views.todays_reservations,
        name='todays-reservations'),
    path(
        'reservations',
        views.reservations,
        name='reservations'),
    path('checkout', views.checkout, name='checkout'),
    path('parking-spaces', views.parking_space, name='parking-spaces')
]


import argparse

from transformers import AutoTokenizer, Trainer, TrainingArguments, AutoModelForCausalLM
from transformers import DataCollatorForLanguageModeling

from datasets import load_dataset
from catalan_dataset import CatalanDataset

def defineArgumentParser():
    """Define the Argument Parser to read the input from the CLI.
    """
    ap = argparse.ArgumentParser()

    ap.add_argument("-m", "--model", type=str, required=True,
        help="Base model name to be trained.")
    ap.add_argument("-t", "--tokenizer", type=str, required=True,
        help="Tokenizer name to be used.")

    ap.add_argument("-i", "--train_path", type=str, required=True,
        help="Path to the training .CSV")
    ap.add_argument("-l", "--test_path", type=str, required=True,
        help="Path to the training .CSV")

    ap.add_argument("-o", "--output", type=str, required=True,
        help="Name of the trained model.")

    ap.add_argument("-e", "--n_epochs", type=int, default=3,
        help="Number of training epochs")
    ap.add_argument("-b", "--train_batch_size", type=int, default=32,
        help="Train batch size.")
    ap.add_argument("-c", "--eval_batch_size", type=int, default=64,
        help="Evaluation batch size.")
    ap.add_argument("-d", "--eval_steps", type=int, default=500,
        help="Evaluation steps.")
    ap.add_argument("-f", "--save_steps", type=int, default=1000,
        help="Save steps.")
    ap.add_argument("-w", "--warmup_steps", type=int, default=500,
        help="Warmup steps.")

    return(ap)

def loadDatasets(train_path: str,
                 test_path: str,
                 tokenizer: AutoTokenizer,
                 use_huggingface_datasets_library: bool = False):
    """Load the specified datasets for training and evaluation.

    Args:
        train_path (str): Training dataset path.
        test_path (str): Test dataset path.
        tokenizer (AutoTokenizer): Tokenizer to be used.
        use_huggingface_datasets_library (bool, optional): Whether to use the datasets library Huggingface provides. Defaults to False.
    """
    # Using Huggingface library is currently (Jan 2022) giving errors.
    # https://github.com/huggingface/datasets/issues/2988
    # https://huggingface.co/docs/datasets/loading_datasets.html

    data_coll = DataCollatorForLanguageModeling(tokenizer=tokenizer,
                                                mlm=False)
    if(use_huggingface_datasets_library):
        dataset = load_dataset("csv",
                            data_files = {'train': train_path,
                                            'test': test_path},
                            sep=';')

        dataset = dataset.remove_columns(['id', 'title'])
    else:
        # Use our own Dataset Class.
        train_dataset = CatalanDataset(train_path, tokenizer)
        test_dataset = CatalanDataset(test_path, tokenizer)

        dataset = {'train': train_dataset,
                   'test': test_dataset}
    return(dataset, data_coll)

def main(model_name: str = "DeepESP/gpt2-spanish",
         tokenizer_name: str = "DeepESP/gpt2-spanish",
         train_path: str = '../data/catalan_corpus_train.csv',
         test_path: str = '../data/catalan_corpus_test.csv',
         output_name: str= "./gpt2-catalan",
         n_epochs: int = 3,
         train_batch_size: int = 32,
         eval_batch_size: int = 64,
         eval_steps: int = 500,
         save_steps: int = 1000,
         warmup_steps: int = 500,
         ):

    print("[INFO] Loading model '{}'...".format(model_name))
    print("[INFO] Loading tokenizer '{}'...".format(tokenizer_name))
    model = AutoModelForCausalLM.from_pretrained(model_name)
    tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
    print("[OK] Done.")

    print("[INFO] Loading datasets...")
    print("     [+] Training: {}".format(train_path))
    print("     [+] Testing: {}".format(test_path))
    dataset, data_collator = loadDatasets(train_path, test_path, tokenizer)
    print("[OK] Done.")

    print("[INFO] Going to fine-tune model {}".format(model_name))

    training_args = TrainingArguments(
        output_dir = output_name,
        overwrite_output_dir = True,
        num_train_epochs = n_epochs,
        per_device_train_batch_size = train_batch_size,
        per_device_eval_batch_size = eval_batch_size,
        eval_steps = eval_steps,
        save_steps = save_steps,
        warmup_steps = warmup_steps,
        prediction_loss_only = True,
    )

    print("[INFO] Training arguments:\n{}".format(training_args))
    print("[INFO] Creating trainer...")
    # Trainer defaults to using AdamW as the optimizer
    trainer = Trainer(
        model = model,
        args = training_args,
        data_collator = data_collator,
        train_dataset = dataset['train'],
        eval_dataset = dataset['test']
    )

    # Throws   File "[PATH]\venv\lib\site-packages\datasets\formatting\formatting.py", line 428, in _check_valid_index_key
    #     raise IndexError(f"Invalid key: {key} is out of bounds for size {size}")
    # IndexError: Invalid key: 89 is out of bounds for size 0 ?
    # https://github.com/huggingface/datasets/issues/2988
    print("[INFO] Starting training...")
    trainer.train()
    print("[OK] Done.")

    trainer.save_model()
    print("Saved model.")
    return

if(__name__ == '__main__'):

    ap = defineArgumentParser()
    args = vars(ap.parse_args())

    # Parse CLI arguments
    model_name = args['model']
    tokenizer_name = args['tokenizer']
    train_path = args['train_path']
    test_path = args['test_path']
    output_name = args['output']
    n_epochs = args['n_epochs']
    train_batch_size = args['train_batch_size']
    eval_batch_size = args['eval_batch_size']
    eval_steps = args['eval_steps']
    save_steps = args['save_steps']
    warmup_steps = args['warmup_steps']

    main(model_name = model_name,
         tokenizer_name = tokenizer_name,
         train_path = train_path,
         test_path = test_path,
         output_name = output_name,
         n_epochs = n_epochs,
         train_batch_size = train_batch_size,
         eval_batch_size = eval_batch_size,
         eval_steps = eval_steps,
         save_steps = save_steps,
         warmup_steps = warmup_steps
         )


#!/usr/bin/env python3

import re
import sys

# for benchmarking python regex
val = "2020-06-30"
for i in range(1000000):
    if not re.search("[0-9]{4}-[0-9]{2}-[0-9]{2}", val):
        print("doesnt work")
        sys.exit(1)


import os
import requests

from flask import Flask, jsonify, request
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)
app.config['DEBUG'] = True

@app.route("/")
def hello():
    return jsonify({"message": "Go to /comments/ or /comments/search/"}), 200

@app.route("/comments/")
def get_comments():
    youtube_api = os.getenv('YLYTIC_API')
    response = requests.get(youtube_api)
    return jsonify(response.json()), 200

def get_date(input_date):  # Sat, 1 Jan 2023 01:55:35 GMT
    input_format = "%a, %d %b %Y %H:%M:%S %Z"
    output_format = "%d-%m-%Y"
    date_obj = datetime.strptime(input_date, input_format)

    return date_obj.strftime(output_format)  # Output: 01-01-2023

# /search?search_author=Fredrick
@app.route("/comments/search/")
def get_filtered_comments():

    # *extracting the params from the url
    search_author = request.args.get('search_author')
    at_from = request.args.get('at_from')
    at_to = request.args.get('at_to')
    like_from = request.args.get('like_from')
    like_to = request.args.get('like_to')
    reply_from = request.args.get('reply_from')
    reply_to = request.args.get('reply_to')
    search_text = request.args.get('search_text')

    youtube_api = os.getenv('YLYTIC_API')
    response = requests.get(youtube_api)
    # handling error
    if response.status_code != 200:
        return {"error": "Something went wrong"}, response.status_code

    # get all the comments
    filtered_comments = response.json()['comments']

    if search_author:
        filtered_comments = [
            comment for comment in filtered_comments if comment['author'].lower() == search_author.lower()]

    if at_from:
        at_from = datetime.strptime(request.args.get('at_from'), '%d-%m-%Y')
        filtered_comments = [
            comment for comment in filtered_comments if datetime.strptime(get_date(comment['at']), '%d-%m-%Y') >= at_from]

    if at_to:
        at_to = datetime.strptime(request.args.get('at_to'), '%d-%m-%Y')
        filtered_comments = [
            comment for comment in filtered_comments if datetime.strptime(get_date(comment['at']),  '%d-%m-%Y') <= at_to]

    if like_from:
        filtered_comments = [
            comment for comment in filtered_comments if comment['like'] >= int(like_from)]
    if like_to:
        filtered_comments = [
            comment for comment in filtered_comments if comment['like'] <= int(like_to)]

    if reply_from:
        filtered_comments = [
            comment for comment in filtered_comments if comment['reply'] >= int(reply_from)]

    if reply_to:
        filtered_comments = [
            comment for comment in filtered_comments if comment['reply'] <= int(reply_to)]

    if search_text:
        filtered_comments = [
            comment for comment in filtered_comments if search_text.lower() in comment['text'].lower()]

    return {"comments": filtered_comments}, 200

if __name__ == '__main__':
    app.run(debug=True)


def pop(self, input) -> str or None:
    """Removes the last item and returns it."""
    node = self.begin
    popped_node = None
    if node is None:
        return None
    elif node.next is None:
        removed_value = self.begin.value
        self.begin = None
        node = self.begin
    else:
        node = self.begin
        while node.next.next:
            node = node.next

    return removed_value

pop('Alireza')


# from sklearn.learning_curve import validation_curve
import numpy as np
from sklearn.model_selection import validation_curve
import matplotlib.pyplot as plt

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

def PolynomialRegression(degree=2, **kwargs):
    return make_pipeline(PolynomialFeatures(degree),
                         LinearRegression(**kwargs))

def make_data(N, err=1.0, rseed=1):
    # randomly sample the data
    rng = np.random.RandomState(rseed)
    X = rng.rand(N, 1) ** 2
    y = 10 - 1. / (X.ravel() + 0.1)
    if err > 0:
        y += err * rng.randn(N)
        return X, y

X, y = make_data(40)

degree = np.arange(0, 21)
train_score, val_score = validation_curve(PolynomialRegression(), X, y,
                                          'polynomialfeatures__degree',
                                          degree, cv=7)
plt.plot(degree, np.median(train_score, 1), color='blue', label='training score')
plt.plot(degree, np.median(val_score, 1), color='red', label='validation score')
plt.legend(loc='best')
plt.ylim(0, 1)
plt.xlabel('degree')
plt.ylabel('score')


from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name='home'),
    path('student_form/',views.student_form,name='student_form'),
    path('students/<int:pk>/',views.Student_Information,name='students'),
    path('student/<int:pk>/edit/',views.Student_Edit,name='s_edit'),
    path('delete/<int:pk>/delete/',views.Student_Delete,name='delete')
    # path('student/<int:pk>/',views.Student_Edit,name='s_edit')

]
# <int:pk>/edit/


from rest_framework import serializers

from account.serializers.profile import UserProfileSerializer
from sympathy.models import Sympathy

class SympathySerializer(serializers.ModelSerializer):
    #user2 = UserProfileSerializer(read_only=True)

    class Meta:
        model = Sympathy
        fields = [
            'user1',
            'user2',
            'room',
            'id'
        ]


from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html

from interview.models import (
    ContractType,
    Candidate,
    Document,
    Process,
    Interview,
    SourcesCategory,
    Sources,
    Offer,
    InterviewKind,
)

@admin.register(ContractType)
class ContractTypeAdmin(admin.ModelAdmin):
    list_display = ("id", "name", "has_duration")
    list_filter = ("has_duration",)
    search_fields = ("name",)

@admin.register(Candidate)
class CandidateAdmin(admin.ModelAdmin):
    list_display = ("id", "name", "email", "phone")
    search_fields = ("name",)

@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
    list_display = ("id", "created_date", "candidate", "document_type", "content", "still_valid")
    list_filter = ("created_date", "still_valid", "document_type")
    search_fields = ("candidate__name",)

@admin.register(Process)
class ProcessAdmin(admin.ModelAdmin):
    list_display = (
        "id",
        "candidate",
        "subsidiary",
        "sources",
        "start_date",
        "end_date",
        "contract_type",
        "salary_expectation",
        "contract_duration",
        "state",
    )
    list_filter = ("subsidiary", "start_date", "end_date", "contract_type", "state", "sources")
    search_fields = ("candidate__name",)

@admin.register(Interview)
class InterviewAdmin(admin.ModelAdmin):
    list_display = ("id", "process", "state", "rank", "planned_date")
    list_filter = ("process__subsidiary", "planned_date", "state")
    search_fields = ("process__candidate__name",)

@admin.register(SourcesCategory)
class SourcesCategoryAdmin(admin.ModelAdmin):
    list_display = ("id", "name")
    search_fields = ("name",)

@admin.register(Sources)
class SourcesAdmin(admin.ModelAdmin):
    list_display = ("id", "name", "category", "archived", "processes_list_url")
    list_filter = ("category", "archived")
    search_fields = ("name",)

    def processes_list_url(self, obj):
        return format_html("ðŸ”—", url=reverse("process-list-source", args=[str(obj.id)]))

    processes_list_url.short_description = "URL"

@admin.register(Offer)
class OfferAdmin(admin.ModelAdmin):
    list_display = ("id", "name", "subsidiary", "archived", "processes_list_url")
    list_filter = ("subsidiary", "archived")
    search_fields = ("name",)

    def processes_list_url(self, obj):
        return format_html("ðŸ”—", url=reverse("process-list-offer", args=[str(obj.id)]))

    processes_list_url.short_description = "URL"

@admin.register(InterviewKind)
class InterviewKindAdmin(admin.ModelAdmin):
    list_display = ("id", "name")
    search_fields = ("name",)


score = [[80, 70], [70, 80], [30, 50], [90, 100], [100, 90], [100, 100], [10, 30]]
dict, average = {}, [sum(i)/len(i) for i in score]

for index, avg in enumerate(sorted(average, reverse = True), start = 1):
	if avg not in dict:
		dict[avg] = index
print([dict[i] for i in average])

'''solution
딕셔너리와 enumerate index를 활용한 정렬방식 사용
'''


from dbt.version import installed as installed_version
from dbt.adapters.factory import adapter_management, register_adapter
from dbt.flags import set_flags, get_flag_dict
from dbt.cli.flags import Flags
from dbt.config import RuntimeConfig
from dbt.config.runtime import load_project, load_profile, UnsetProfile
from dbt.events.functions import setup_event_logger, fire_event, LOG_VERSION
from dbt.events.types import MainReportVersion, MainReportArgs, MainTrackingUserState
from dbt.exceptions import DbtProjectError
from dbt.parser.manifest import ManifestLoader, write_manifest
from dbt.profiler import profiler
from dbt.tracking import active_user, initialize_from_flags, track_run
from dbt.utils import cast_dict_to_dict_of_strings

from click import Context
from functools import update_wrapper

def preflight(func):
    def wrapper(*args, **kwargs):
        ctx = args[0]
        assert isinstance(ctx, Context)
        ctx.obj = ctx.obj or {}

        # Flags
        flags = Flags(ctx)
        ctx.obj["flags"] = flags
        set_flags(flags)

        # Tracking
        initialize_from_flags(flags.SEND_ANONYMOUS_USAGE_STATS, flags.PROFILES_DIR)
        ctx.with_resource(track_run(run_command=flags.WHICH))

        # Logging
        # N.B. Legacy logger is not supported
        setup_event_logger(flags)

        # Now that we have our logger, fire away!
        fire_event(MainReportVersion(version=str(installed_version), log_version=LOG_VERSION))
        flags_dict_str = cast_dict_to_dict_of_strings(get_flag_dict())
        fire_event(MainReportArgs(args=flags_dict_str))

        if active_user is not None:  # mypy appeasement, always true
            fire_event(MainTrackingUserState(user_state=active_user.state()))

        # Profiling
        if flags.RECORD_TIMING_INFO:
            ctx.with_resource(profiler(enable=True, outfile=flags.RECORD_TIMING_INFO))

        # Adapter management
        ctx.with_resource(adapter_management())

        return func(*args, **kwargs)

    return update_wrapper(wrapper, func)

# TODO: UnsetProfile is necessary for deps and clean to load a project.
# This decorator and its usage can be removed once https://github.com/dbt-labs/dbt-core/issues/6257 is closed.
def unset_profile(func):
    def wrapper(*args, **kwargs):
        ctx = args[0]
        assert isinstance(ctx, Context)

        if ctx.obj.get("profile") is None:
            profile = UnsetProfile()
            ctx.obj["profile"] = profile

        return func(*args, **kwargs)

    return update_wrapper(wrapper, func)

def profile(func):
    def wrapper(*args, **kwargs):
        ctx = args[0]
        assert isinstance(ctx, Context)

        if ctx.obj.get("profile") is None:
            flags = ctx.obj["flags"]
            # TODO: Generalize safe access to flags.THREADS:
            # https://github.com/dbt-labs/dbt-core/issues/6259
            threads = getattr(flags, "THREADS", None)
            profile = load_profile(
                flags.PROJECT_DIR, flags.VARS, flags.PROFILE, flags.TARGET, threads
            )
            ctx.obj["profile"] = profile

        return func(*args, **kwargs)

    return update_wrapper(wrapper, func)

def project(func):
    def wrapper(*args, **kwargs):
        ctx = args[0]
        assert isinstance(ctx, Context)

        if ctx.obj.get("project") is None:
            # TODO: Decouple target from profile, and remove the need for profile here:
            # https://github.com/dbt-labs/dbt-core/issues/6257
            if not ctx.obj.get("profile"):
                raise DbtProjectError("profile required for project")

            flags = ctx.obj["flags"]
            project = load_project(
                flags.PROJECT_DIR, flags.VERSION_CHECK, ctx.obj["profile"], flags.VARS
            )
            ctx.obj["project"] = project

        return func(*args, **kwargs)

    return update_wrapper(wrapper, func)

def runtime_config(func):
    """A decorator used by click command functions for generating a runtime
    config given a profile and project.
    """

    def wrapper(*args, **kwargs):
        ctx = args[0]
        assert isinstance(ctx, Context)

        req_strs = ["profile", "project"]
        reqs = [ctx.obj.get(req_str) for req_str in req_strs]

        if None in reqs:
            raise DbtProjectError("profile and project required for runtime_config")

        ctx.obj["runtime_config"] = RuntimeConfig.from_parts(
            ctx.obj["project"],
            ctx.obj["profile"],
            ctx.obj["flags"],
        )

        return func(*args, **kwargs)

    return update_wrapper(wrapper, func)

def manifest(*args0, write=True, write_perf_info=False):
    """A decorator used by click command functions for generating a manifest
    given a profile, project, and runtime config. This also registers the adaper
    from the runtime config and conditionally writes the manifest to disc.
    """

    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            ctx = args[0]
            assert isinstance(ctx, Context)

            req_strs = ["profile", "project", "runtime_config"]
            reqs = [ctx.obj.get(dep) for dep in req_strs]

            if None in reqs:
                raise DbtProjectError("profile, project, and runtime_config required for manifest")

            runtime_config = ctx.obj["runtime_config"]
            register_adapter(runtime_config)

            # a manifest has already been set on the context, so don't overwrite it
            if ctx.obj.get("manifest") is None:
                manifest = ManifestLoader.get_full_manifest(
                    runtime_config, write_perf_info=write_perf_info
                )

                ctx.obj["manifest"] = manifest
                if write and ctx.obj["flags"].write_json:
                    write_manifest(manifest, ctx.obj["runtime_config"].target_path)

            return func(*args, **kwargs)

        return update_wrapper(wrapper, func)

    # if there are no args, the decorator was used without params @decorator
    # otherwise, the decorator was called with params @decorator(arg)
    if len(args0) == 0:
        return outer_wrapper
    return outer_wrapper(args0[0])