from celery import shared_task
from django.utils import timezone
import time
from reddit.models import RedditPost
import os
import datetime

import sys
sys.path.append("../")
from text_classifier import classify_text_inputs

@shared_task
def update_posts():
    start = time.time()
    log_file = 'log.txt'
    error_file = 'error.txt'
    if not os.path.exists(log_file):
        open(log_file, 'w').close()  # Create an empty file
    if not os.path.exists(error_file):
        open(error_file, 'w').close()  # Create an empty file
    posts = RedditPost.objects.all()
    successes = 0
    failures = 0
    total = 0
    for post in posts:
        total += 1
        try:
            lastest_comments = post.get_updated_comments()
            if len(lastest_comments) == post.num_top_level_comments:
                successes += 1
                continue
            post.update()
            sa_results = classify_text_inputs(lastest_comments)
            post.set_num_top_level_comments(len(lastest_comments))
            post.set_sentiment_analysis_results(sa_results)
            post.save()
            successes += 1
        except Exception as e:
            failures += 1
            print(e)
            with open(error_file, 'a') as ef:
                f.write(str(e) + '\n')
            continue

    with open(log_file, 'a') as f:
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        f.write(
            f"Updated {total} posts with {successes}/{total} successes and {failures}/{total} failures at {current_time}. Took {time.time() - start} seconds.\n")


from models.Build import Build
from models.Container import Container
from models.Depends import Dependency
from models.Environment import Environment
from models.Ports import Port
from models.Volume import Volume

endLine = '\n'
indent = '   '

class Generator:
    version = '3.8'

    @staticmethod
    def get_ports(container, left_indent, count):
        container_ports = ''
        for port in container.ports:
            if port:
                if port is container.ports[0]:
                    container_ports += left_indent + port + endLine
                else:
                    container_ports += left_indent + indent * count + port + endLine
        return container_ports

    @staticmethod
    def get_environments(container, left_indent, count):
        container_environment = ''
        for environment in container.environments:
            if environment:
                if environment is container.environments[0]:
                    container_environment += left_indent + environment + endLine
                else:
                    container_environment += left_indent + indent * count + environment + endLine
        return container_environment

    @staticmethod
    def get_dependency(container, left_indent, count):
        container_dependency = ''
        for dependency in container.dependency:
            if dependency:
                if dependency is container.dependency[0]:
                    container_dependency += left_indent + dependency + endLine
                else:
                    container_dependency += left_indent + indent * count + dependency + endLine
        return container_dependency

    @staticmethod
    def get_build(container, left_indent):
        container_build = ''
        if container.build:
            container_build += left_indent + indent * 3 + 'context: ' + container.build.context + endLine
            container_build += left_indent + indent * 3 + 'dockerfile: ' + container.build.dockerfile + endLine
        return container_build

    @staticmethod
    def get_image(container):
        container_image = ''
        if container.image:
            container_image += container.image + endLine
        return container_image

    @staticmethod
    def get_volumes(container, left_indent, count):
        volumes = ''
        for volume in container.volumes:
            if volume:
                if volume is container.volumes[0]:
                    volumes += left_indent + volume + endLine
                else:
                    volumes += left_indent + indent * count + volume + endLine
        return volumes

    @staticmethod
    def SetContainerName(selected_container, containers, container_name):
        for container in containers:
            if container is selected_container:
                selected_container.name = container_name
                break

    @staticmethod
    def SetContainerBuild(selected_container, containers, container_build):
        for container in containers:
            if container is selected_container:
                selected_container.build = container_build
                break

    @staticmethod
    def GenerateYaml(containers, left_indent="   ", count=3):
        docker_compose = f'\n{left_indent}version:  "{Generator.version}"' + endLine * 2 + f'{left_indent}services:' + endLine * 2
        for container in containers:
            if container.active:
                docker_compose += left_indent + indent + container.name + ':' + endLine
                # Image
                if container.image is not None:
                    docker_compose += left_indent + indent * 2 + 'image: ' + Generator.get_image(container)
                # Build
                if container.build is not None:
                    docker_compose += left_indent + indent * 2 + 'build:' + endLine + Generator.get_build(container,
                                                                                left_indent)
                # Ports
                if container.ports is not None and container.portsCount > 0 \
                        and len(container.ports[0]) > 0:
                    docker_compose += left_indent + indent * 2 + 'ports:' + endLine
                    docker_compose += left_indent + indent * 2 + Generator.get_ports(container, left_indent, count)
                # Environments
                if container.environments is not None and container.environmentsCount > 0 \
                        and len(container.environments[0]) > 0:
                    docker_compose += left_indent + indent * 2 + 'environment:' + endLine
                    docker_compose += left_indent + indent * 2 + Generator.get_environments(container, left_indent,
                                                                                count)
                # Dependency
                if container.dependency is not None and container.dependsCount > 0 \
                        and len(container.dependency[0]) > 0:
                    docker_compose += left_indent + indent * 2 + 'depends_on:' + endLine
                    docker_compose += left_indent + indent * 2 + Generator.get_dependency(container, left_indent, count)
                # Volumes
                if container.volumes is not None and container.volumesCount > 0 \
                        and len(container.volumes[0]) > 0:
                    docker_compose += left_indent + indent * 2 + 'volumes:' + endLine
                    docker_compose += left_indent + indent * 2 + Generator.get_volumes(container, left_indent, count)

                docker_compose += endLine
        return docker_compose

    @staticmethod
    def GetYamlFromFile(window, yaml):
        i = 0
        name = ''
        key = f'-container-{i}-'
        image = None
        build = None
        ports = None
        environments = None
        depends = None
        volumes = None
        window['-selected-version-value-'].update(yaml['version'])
        Generator.version = yaml['version']
        containers = Generator.reset_containers()
        for container in yaml['services']:
            data = yaml['services'][container]
            name = container
            if 'build' in data:
                build = Build(data['build']['dockerfile'], data['build']['context'])
            if 'image' in data:
                image = data['image']
            if 'ports' in data:
                ports = []
                for port in data['ports']:
                    spliced_port = port.split(':')
                    new_port = Port(spliced_port[0], spliced_port[1])
                    ports.append(new_port.port)
            if 'environment' in data:
                environments = []
                for environment in data['environment']:
                    env = Environment(environment)
                    environments.append(env.environment)
            if 'depends_on' in data:
                depends = []
                for dependency in data['depends_on']:
                    deps = Dependency(dependency)
                    depends.append(deps.dependency)
            if 'volumes' in data:
                volumes = []
                for volume in data['volumes']:
                    new_volume = Volume(volume)
                    volumes.append(new_volume.volume)
            key = f'-container-{i}-'
            containers[i] = Container(name, key, True, image, build, ports, environments, depends, volumes)
            containers[i] = Generator.SetCountersForContainer(containers[i], ports, environments, depends, volumes)
            window[key].update(name)
            i += 1
            image = None
            build = None
            ports = None
            environments = None
            depends = None
            volumes = None
        return containers, i

    @staticmethod
    def SetCountersForContainer(container, ports, evns, depends, volumes):
        if ports is not None:
            container.portsCount = len(ports)
        if evns is not None:
            container.environmentsCount = len(evns)
        if depends is not None:
            container.dependsCount = len(depends)
        if volumes is not None:
            container.volumesCount = len(volumes)
        return container

    @staticmethod
    def reset_containers():
        containers = []
        for i in range(0, 24):
            containers.append(Container('New container', f'-container-{i}-', False))
        return containers


# -*- coding: utf-8 -*-
"""
Created on Tue Mar 16 22:25:59 2021

@author: mofarrag
"""
import numpy as np
CWEIR = 1.704
BWIDTH = 10
HLIN = 0.001
power = 2/3

def HBC(Sub, River, Hbnd, dt, dx,inih,storewl, MinQ):

    xs = np.zeros(shape=(Sub.XSno,8))
    Diff_coeff = np.zeros(shape=(Sub.XSno,3))
    XSarea = np.zeros(shape=(Sub.XSno))

    wl = np.zeros(shape=(Sub.XSno))
    hx = np.zeros(shape=(Sub.XSno))
    qx = np.zeros(shape=(Sub.XSno))

    h = np.zeros(shape=(Sub.XSno,River.TS))
    q = np.zeros(shape=(Sub.XSno,River.TS))

    storewl = np.zeros(shape=(River.XSno,2))
    # OverTopFlow = np.zeros(shape=(River.XSno*2,24))
    # OverTopWL = np.zeros(shape=(River.XSno*2,24))
    Lateral_q = MinQ.values[:-1,:-2]

    q_outL = np.zeros(shape=(Sub.XSno,River.TS))
    q_outR = np.zeros(shape=(Sub.XSno,River.TS))
    q_out = np.zeros(shape=(Sub.XSno,River.TS))

    q_outLx = np.zeros(shape=(Sub.XSno))
    q_outRx = np.zeros(shape=(Sub.XSno))
    q_outx = np.zeros(shape=(Sub.XSno))

    for t in range(0,River.TS):
        dtrest = dt
         # IC
        if t == 0:
            # fill the water depth array with the initial condition at time step 1
            hx[:] = inih
        else :
            #water level in the previous time-step is now turned to be the current
            hx = h[:,t-1]

         # boundary condition
         # water level at the first cross section (x=1]is the BC
        hx[0] = Hbnd[0]
         # hx is the water depth of the previous time step
         # except for the first cross section water depth is the boundary condition
         # for this time step
         # hx=[t,t-1,t-1,t-1,.............]
        adaptiveTS_counter = 0
        # for each time step use adaptive time step
        # adaptive time step -----------------------------------------------------
        while dtrest > 0.001:
            adaptiveTS_counter = adaptiveTS_counter + 1
            # calculate the area and perimeter based on the water depth of the previous time step
            # for the whole cross sections in the sub-basin
            for x in range(0, Sub.XSno):
                # xs[:,:] = 0
                # calculate the area & perimeter of the whole XS
                Coords = River.GetVortices(hx[x], Sub.hl[x], Sub.hr[x], Sub.cl[x], Sub.cr[x], Sub.mw[x],Sub.Dbf[x])
                xs[x,0:2] = River.PolygonGeometry(Coords)

                # area & perimeter of the Upper part only
                if hx[x] <= Sub.Dbf[x]:
                    xs[x,2] = 0
                    xs[x,3] = 0
                else :
                # area of upper part only
                    xs[x,2] =  xs[x,0] - (Sub.Dbf[x] * Sub.mw[x])
                # perimeter of upper part
                    xs[x,3] =  xs[x,1] -  (2* Sub.Dbf[x] + Sub.mw[x])

                # area & perimeter of the lower part only
                xs[x,4] = xs[x,0] - xs[x,2]
                xs[x,5] = xs[x,1] - xs[x,3]

                # to calculate hydraulic radius perimeter is in the denominator so it has not to be zero
                if xs[x,1] == 0 or xs[x,5] == 0:
                    assert False, 'at x= ' + str(Sub.xsid[x]) + ' t= ' + str(t) + ' total perimiter is zero'

            #for each cross section -------------------------------
            for x in range(0, Sub.XSno) :
                #print(*,'(a3,i4,a4,i6,a]'] 't= ',t,' x= ', xsid[x],'------------------'
                # forward difference
                # surface slope is calculated based on the previous time step water depth
                # except for the first cross section hx[1]is from current time step
                # while hx[2]is from previous time step
                if x < Sub.XSno-1:
                    #friction slope = (so - dhx/dx] - diffusive wave
                    sf = (hx[x] + Sub.bedlevel[x] - hx[x+1] - Sub.bedlevel[x+1])/dx
                else:
                    #for LOWER BOUNDARY node
                    sf = (hx[x-1] + Sub.bedlevel[x-1] - hx[x] - Sub.bedlevel[x])/dx

     			#if sf <= 0 :
                    #print[800000,'(a]'] '----------'
                    #print(*,'(a4,i4,2x,a6,G10.4]'] 'XS= ',xsid[x], ', sf= ', sf
                    #print[800000,'(a7,i4,a5,i6,2x,a6,G10.4]'] 'min = ',t ,' XS= ',xsid[x], ', sf= ', sf

                if River.D1['ModelMode'] == 2 :
                    #check for the dike overtopping
                    #to LEFT?
                    # overtoping dischargee is zero unless water level exceeds the dike level
                    q_outLx[x] = 0
                    # check first the water level in the 2d grid
                    # if water level in the 1D river is less than the water depth in
                    # nighbouring cell in the 2D grid don't calculate overtopping

                    if storewl[Sub.xsid[x]] - Sub.bedlevel[x]  <  hx[x] :

                        # if water depth is higher than the left dike height and the threshold
                        if  hx[x] > max(Sub.zl[x] - Sub.bedlevel[x], River.D1['MinDepth']):
                            #weir formular - free flow
                            q_outLx[x] = CWEIR*BWIDTH * (hx[x] - max(Sub.zl[x] - Sub.bedlevel[x] , River.D1['MinDepth']))**1.5

                    #to RIGHT?
                    q_outRx[x] = 0
                    # nxs is added to the ipf just because of the numbering system of the
                    # cross section
                    if  storewl[Sub.xsid[x] + River.XSno] - Sub.bedlevel[x] < hx[x] :

                        if hx[x] > max(Sub.zr[x] - Sub.bedlevel[x],River.D1['MinDepth']) :
                            q_outRx[x] = CWEIR * BWIDTH * (hx[x] - max( Sub.zr[x] - Sub.bedlevel[x],River.D1['MinDepth']) )**1.5

                    # correction factor
                    q_outx[x] = q_outLx[x] + q_outRx[x]
                    if q_outx[x] == 0:
                        corrL=0
                        corrR=0
                    else :
                        corrL = q_outLx[x]/q_outx[x]
                        corrR = q_outRx[x]/q_outx[x]

                # compute mean area and hydraulic radius
                # all cross section except the last one
                if x < Sub.XSno-1:
                    if hx[x] <= Sub.Dbf[x]:
                        # upper discharge
                        xs[x,6] = 0
                        # diffusive wave coefficient for upper wave
                        Diff_coeff[x,0] = 0
                        # calculate only lower part
                        # Lower mean area and hydraulic radius
                        Area_LM = (xs[x,4] + xs[x+1,4])/2							#mean area
                        R_LM = ( xs[x,4]/xs[x,5] + xs[x+1,4]/xs[x+1,5] )/2		#mean radius
                    else :
                        # Upper mean area and hydraulic radius
                        Area_UM = (xs[x,2] + xs[x+1,2])/2						#mean area
                        #print(*,'(a7,f8.3]'] 'A_UM = ', Area_UM
                        if xs[x,3] != 0 and xs[x+1,3] == 0 :
                            R_UM = (xs[x,2]/xs[x,3])/2			#mean radius
                        elif xs[x,3] == 0 and xs[x+1,3] != 0:
                            R_UM = (xs[x+1,2]/xs[x+1,3])/2		#mean radius
                        elif xs[x,3] == 0 and xs[x+1,3] == 0:
                            R_UM = 0							#mean radius
                        else :
                            R_UM = (xs[x,2]/xs[x,3] + xs[x+1,2] / xs[x+1,3])/2		#mean radius

                        # upper discharge
                        xs[x,6] = (1.0/Sub.mn[x]) * Area_UM * (R_UM**power)
                        # diffusive wave coefficient for upper wave
                        Diff_coeff[x,0] = (1.0/Sub.mn[x])* (R_UM**power )

                        # Lower mean area and hydraulic radius
                        Area_LM = (xs[x,4]+xs[x+1,4])/2							#mean area
                        R_LM = (xs[x,4]/xs[x,5]+xs[x+1,4]/xs[x+1,5])/2		#mean radius
                else : # the last cross section
                    if hx[x] <= Sub.Dbf[x]:
                        # upper discharge
                        xs[x,6] = 0
                        # diffusive wave coefficient for upper wave
                        Diff_coeff[x,0] = 0
                        # calculate only lower part
                        # Lower mean area and hydraulic radius
                        Area_LM = (xs[x,4]+xs[x-1,4])/2						#for LOWER BOUNDARY node
                        R_LM = (xs[x,4]/xs[x,5]+xs[x-1,4]/xs[x-1,5])/2		#mean radius
                    else : #for LOWER BOUNDARY node
                        # Upper mean area and hydraulic radius
                        Area_UM = (xs[x,2]+xs[x-1,2])/2

                        if xs[x,3] != 0 and xs[x-1,3] == 0:
                            R_UM = (xs[x,2]/xs[x,3])/2		#mean radius
                        elif xs[x,3] == 0 and xs[x-1,3] != 0:
                            R_UM = (xs[x-1,2]/xs[x-1,3])/2		#mean radius
                        elif xs[x,3] == 0 and xs[x-1,3] == 0:
                            R_UM = 0
                        else :
                            R_UM = (xs[x,2]/xs[x,3] + xs[x-1,2]/xs[x-1,3])/2	#mean radius

                        # upper discharge
                        xs[x,6] = (1.0/Sub.mn[x]) * Area_UM * (R_UM**power)
                        # diffusive wave coefficient for upper wave
                        Diff_coeff[x,0] = (1.0/Sub.mn[x])* (R_UM**power)

                        # Lower mean area and hydraulic radius
                        Area_LM = (xs[x,4]+xs[x-1,4])/2						#for LOWER BOUNDARY node
                        R_LM = (xs[x,4]/xs[x,5]+xs[x-1,4]/xs[x-1,5])/2		#mean radius

                #calculation of fluxes
                if abs(sf) > HLIN/dx:
                    # diffusive wave coefficient for upper wave
                    Diff_coeff[x,0] = Diff_coeff[x,0] / np.sqrt(abs(sf))
                    # diffusive wave coefficient for Lower wave
                    Diff_coeff[x,1] = (1.0/Sub.mn[x])* (R_LM**power) / np.sqrt(abs(sf))
                    # total diffusion coefficient
                    Diff_coeff[x,2] = Diff_coeff[x,0] + Diff_coeff[x,1]
                    # discharge
                    # upper discharge
                    xs[x,6] = xs[x,6] * (np.sqrt(abs(sf))*sf/abs(sf))
                    # Lower discharge
                    xs[x,7] = (1.0/Sub.mn[x]) * Area_LM * (R_LM**power) * (np.sqrt(abs(sf))*sf/abs(sf))
                else :
                    # diffusive wave coefficient for upper wave
                    Diff_coeff[x,0] = Diff_coeff[x,0] / np.sqrt(HLIN/dx)

                    # diffusive wave coefficient for Lower wave
                    Diff_coeff[x,1] = (1.0/Sub.mn[x])* (R_LM**power) / np.sqrt(HLIN/dx)
                    # total diffusion coefficient
                    Diff_coeff[x,2] = Diff_coeff[x,0] + Diff_coeff[x,1]

                    # discharge
                    # upper discharge
                    xs[x,6] = xs[x,6] * (np.sqrt(dx/HLIN)*sf)
                    #xs[x,7] = xs[x,7] * (np.sqrt(HLINQ/dx]]
                    # Lower discharge
                    xs[x,7] = (1.0/Sub.mn[x]) * Area_LM * (R_LM**power) * (np.sqrt(dx/HLIN)*sf)
                    #xs[x,8] = (1.0/mn[x]] * Area_LM * (R_LM** (2.0/3.0]] * (np.sqrt(HLINQ/dx]]

                # total Discharge
                qx[x] = xs[x,6] + xs[x,7]

    # 			if qx[x] < 0:
                    #print(*,'(a,i4]'] 'Q is -ve at XS= ',xsid[x]
                    #print[800000,'(a7,i4,a17,i6,a4,f8.3]'] 'min = ',t ,' Q is -ve at XS= ',xsid[x],' Q= ',qx[x]
                    #print[800000,'(a,f8.3]'] 'Q is -ve at Q= ',qx[x]
                    #exit

                if River.D1['ModelMode'] == 2:
                    # if the overtopping is less than 0.5 the flow
                    if qx[x] > 2*q_outx[x] :
                        # the whole overtopping will be considered
                        qx[x] = qx[x]- q_outx[x]
                    else :
                        # if the overtopping is greater than 0.5 the flow
                        # overtopping will be 0.5 the flow only
                        q_outx[x] = 0.5*qx[x]
                        q_outLx[x] = corrL*q_outx[x]
                        q_outRx[x] = corrR*q_outx[x]
                        qx[x] = qx[x]- q_outx[x]

            #for each cross section -------------------------------
            #print(*,'(a17,f8.3]'] 'max diff coeff = ', maxval[Diff_coeff(:,3]]

            # adjusting the time step
            dto = (dx**2)/(2*max(Diff_coeff[:,2]))

            if dto > dt:
                dto = dt
            else :
                if dto == 0:
                    print('adaptive time step is almost zero dto= '+ str(t))
                    #arr = Diff_coeff(:,3]
                    #call Find_FInArrayF[maxval[arr],arr,loc1[1]]
                    #loc =maxloc (Diff_coeff(:,3]]
                    #print(*,'(a37,i4]'] 'At XS= ', xsid[loc1[1]]
                    #print(*,'(a37,i4]'] 'Diff coeff= ', Diff_coeff[loc1[1],3]
                    #print(*,'(a37,i4]'] 'discharge= ', qx[loc1[1]]
                    assert False ,'dto= ' + str(dto)

            if dto > dtrest:
                dto = dtrest

            #print[800000,'(a3,f8.2,a7,f4.2,a7,f8.2]'] 'dto= ', dto,' ratio=', dto/dt, ' max Q= ',qx[Sub.XSno]

            # update the water level at each cross section except the upstream boundary node
            for x in range(1, (Sub.XSno)-2) :
                # check if the XS has laterals
                # FindInArrayF(real[xsid[x]],sub_XSLaterals,loc)
                if Sub.xsid[x] in Sub.LateralsTable:
                    loc = Sub.LateralsTable.index(Sub.xsid[x])
                    # have only the laterals
                    qlat = Lateral_q[t,loc]
                    #print(*,*] "Lat= ", qlat
                else :
                    qlat = 0

                # Forward time backward scpace
                XSarea[x] = xs[x,0] - ((qx[x] - qx[x-1]) * (dto/dx)) + qlat * (dto/dx) #dto # difference between two consecutive XS areas

                if XSarea[x] <= 0:
                    break
                    print(x)
                    print(XSarea[x])
                    assert False, "Error cross section area is less than zero"
                else :
                    # calculate the bankful area
                    bankful_area = Sub.Dbf[x] * Sub.mw[x]

                    # if the new area is less than the area of the min[hl,hr]
                    if XSarea[x] <= Sub.AreaPerLow[x,0] :
                        # if the area is less than the bankful area
                        if XSarea[x] <= bankful_area:
                            hx[x] = XSarea[x]/Sub.mw[x]
                        else :
                            # Case 1
                            dummyarea = XSarea[x] - bankful_area
                            dummyh = QuadraticEqn(Sub.cr[x]/Sub.hr[x] + Sub.cl[x]/Sub.hl[x], 2*Sub.mw[x],-2*dummyarea)
                            hx[x] = dummyh + Sub.Dbf[x]

                    # if the new area is less than the area of the max[hl,hr]
                    elif XSarea[x] <= Sub.AreaPerHigh[x,1]:
                        dummyarea = XSarea[x] - bankful_area
                        # check which dike is higher
                        if Sub.hl[x] < Sub.hr[x] :
                            # case 2
                            dummyh = QuadraticEqn(Sub.cr[x]/Sub.hr[x]*0.5, Sub.mw[x]+Sub.cl[x],-dummyarea-Sub.hl[x]*Sub.cl[x]*0.5)
                        else :
                            # case 3
                            dummyh = QuadraticEqn(Sub.cl[x]/Sub.hl[x]*0.5,Sub.mw[x]+Sub.cr[x],-dummyarea-Sub.hr[x]*Sub.cr[x]*0.5)

                        hx[x] = dummyh + Sub.Dbf[x]

                    else :
                        dummyarea = XSarea[x] - bankful_area
                        # case 4 (linear function]
                        dummyh = (dummyarea+Sub.cl[x]*Sub.hl[x]/2.0+Sub.cr[x]*Sub.hr[x]/2.0)/(Sub.cr[x]+Sub.cl[x]+Sub.mw[x])
                        hx[x] = dummyh + Sub.Dbf[x]

                    # to prevent -ve Sf in the next time step calculation
                    if hx[x]+Sub.bedlevel[x] > hx[x-1]+Sub.bedlevel[x-1]:
                        #print[800000,'(a]'] '-----'
                        #print[800000,'(a,i5,a11,i2]'] 'time = ',t , ' round no= ',adaptiveTS_counter
                        #print[800000,'(a9,i5,a4,f10.3]'] 'Q at x = ', xsid[x],' Q= ' ,qx[x]
                        #print[800000,'(a9,i5,a4,f10.3]'] 'Q at x = ', xsid[x-1],' Q= ' ,qx[x-1]
                        # g = (hx[x]+Sub.bedlevel[x])- (hx[x-1]+Sub.bedlevel[x-1])
                        #print[800000,'(a,i5,a3,f10.4,a2]'] 'H is higher than previous XS= ',xsid[x], "by ", g,' m'
                        #print(*,'(a,i5]'] 'H is higher than previous XS= ',xsid[x]
                        hx[x] = hx[x-1] + Sub.bedlevel[x-1] - Sub.bedlevel[x] -0.01

                    # this check to prevent the previous step from creating -ve values
                    # as after calculating the h[x]by solving the quadratic equation (QuadraticEqn]the step
                    # of hx[x] = hx[x-1] + bedlevel[x-1] - bedlevel[x] -0.01 can result in -ve hx
                    # so this check should be after not before
                    if hx[x] <= 0.01:
                        hx[x] = 0.01

            # water depth at the last point equals to wl at point before the last
            hx[Sub.XSno-1] = hx[Sub.XSno-2]- 0.001

            if min(hx)<0:
                assert False ,'calculated water depth is less than 0 '

            # update the discharge array & dt
            dtrest = dtrest - dto
            q[:,t] = q[:,t] + qx[:]*(dto/dt)

            if River.D1['ModelMode'] == 2:
                q_outL[:,t] = q_outL[:,t] + q_outLx* (dto/dt)
                q_outR[:,t] = q_outR[:,t] + q_outRx* (dto/dt)
                q_out[:,t] = q_outL[:,t] + q_outR[:,t]

        # adaptive time step ------------------------------------------------

        # store the calculated water level & water depth
        h[:,t] = hx
        wl = hx + Sub.bedlevel

    return q, h, wl

def QuadraticEqn(a,b,c):
    delta = (b**2) - 4*a*c
    return (-b + np.sqrt(delta))/(2*a)


# Documentation is like sex.
# When it's good, it's very good.
# When it's bad, it's better than nothing.
# When it lies to you, it may be a while before you realize something's wrong.

age = int(input("Vnesi starost"))
name = input("Vnesi ime: ")

if age > 21 and name[-1] == "z":
    print("Pivo v USA da!")
else:
    print("SMTH")


"""
Learn to apply different geometric transformation to images
    like translation, rotation, affine transformation etc.
"""

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

def scale():
    """
    对图片进行缩放的两种方法
    """
    img = cv.imread(r'../resources/messi5.jpg')
    cv.imshow(winname='image', mat=img)
    cv.waitKey(0)
    # 对图片进行 x ， y上的缩放
    res = cv.resize(img, None, fx=0.5, fy=0.5, interpolation=cv.INTER_CUBIC)
    cv.imshow(winname='image', mat=res)
    cv.waitKey(0)
    height, width = img.shape[:2]
    # 将图片缩放到指定大小
    res = cv.resize(img, (2*width, 2*height), interpolation=cv.INTER_CUBIC)
    cv.imshow(winname='image', mat=res)
    cv.waitKey(0)

    cv.destroyAllWindows()

def translation():
    """
    对图片进行平移操作，使用函数  cv.warpAffine() 针对灰色处理后的数据
    向量公式
     M = | 1  0 tx |
        | 0  1 ty |
    :return:
    """
    img = cv.imread(r'../resources/messi5.jpg', flags=cv.IMREAD_GRAYSCALE)
    rows, cols = img.shape
    # 分别在x，y上正向移动 100,50
    M = np.float32([[1, 0, 100], [0, 1, 50]])
    # 进行向量计算获取目标数据
    dst = cv.warpAffine(img, M, (cols, rows))

    cv.imshow('img', img)
    cv.imshow('dst', dst)
    cv.waitKey(0)
    cv.destroyAllWindows()

def rotation():
    """
    对图片进行旋转
    普通旋转的 使用向量：
    M=[cosθ−sinθ
       sinθcosθ]
    但 openCV中支持旋转带缩放，使用向量
    M=[ α β (1−α)⋅center.x−β⋅center.y
       −β α β⋅center.x+(1−α)⋅center.y]
    其中 α=scale⋅cosθ, β=scale⋅sinθ
    M 使用 getRotationMatrix2D 来获取
    """
    img = cv.imread(r'../resources/messi5.jpg', flags=cv.IMREAD_GRAYSCALE)
    rows, cols = img.shape
    # 参数 ： 旋转中心点，角度，放大倍数
    M = cv.getRotationMatrix2D(((cols - 1) / 2.0, (rows - 1) / 2.0), 90, 0.5)
    dst = cv.warpAffine(img, M, (cols, rows))

    cv.imshow('img', img)
    cv.imshow('dst', dst)
    cv.waitKey(0)
    cv.destroyAllWindows()

def affine_transformation():
    """
    仿射变换,变换的向量 M 可以通过 定出原图中的三个点和目标图中的三个点
    使用 cv.getAffineTransform 获取需要的向量
    """

    img = cv.imread(r'../resources/messi5.jpg')
    rows, cols, ch = img.shape
    pts1 = np.float32([[50, 50], [200, 50], [50, 200]])
    pts2 = np.float32([[10, 100], [200, 50], [100, 250]])
    M = cv.getAffineTransform(pts1, pts2)  # 使用三个点对应的变换获取向量
    dst = cv.warpAffine(img, M, (cols, rows))
    plt.subplot(121), plt.imshow(img), plt.title('Input')
    plt.subplot(122), plt.imshow(dst), plt.title('Output')
    plt.show()

def perspective_transformation():
    """
    透视变化,变换的向量 M 可以通过 定出原图中的4个点和目标图中的4个点
    使用 cv.getPerspectiveTransform 获取需要的向量
    :return:
    """
    img = cv.imread(r'../resources/messi5.jpg')
    pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
    pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])
    M = cv.getPerspectiveTransform(pts1, pts2) # 使用四个点对应的变换获取向量
    dst = cv.warpPerspective(img, M, (300, 300))
    plt.subplot(121), plt.imshow(img), plt.title('Input')
    plt.subplot(122), plt.imshow(dst), plt.title('Output')
    plt.show()

# scale()
# translation()
# rotation()
# affine_transformation()
perspective_transformation()


from django.shortcuts import render
from django.http import HttpResponse
from examples.models import study
from examples.models import SimpleTable
from examples.models import SNP_entry
from django.template.response import TemplateResponse
from django.shortcuts import render
from itertools import chain
import simplejson as json
import xlsxwriter
import subprocess
import os
import xlrd

# Create your views here.

currentGene = "NULL"

def home(request):
	return render(request, 'pages/home.html')

def get_GENE(request):
	if request.method == 'GET':
		geneName = request.GET['text_box']
		disorder_num = request.GET['dropdown']
		studyData = study.objects.all()
		SNPData = SNP_entry.objects.all()
		filterGene = SNP_entry.objects.filter(gene_name=geneName).filter(disorder=disorder_num)

		#WRITE TO EXCEL FILE
		if os.path.exists('geneData.xlsx'): os.remove('geneData.xlsx')
		workbook = xlsxwriter.Workbook('geneData.xlsx')
		worksheet1 = workbook.add_worksheet('studyData')
		worksheet2 = workbook.add_worksheet('SNP_entryData')

		excel_data(workbook, worksheet1, worksheet2, filterGene)

		table = SimpleTable(filterGene, template_name='django_tables2/bootstrap-responsive.html')
		return render(request, 'pages/database.html', {'table': table})

def get_SNP(request):
	if request.method == 'GET':
		SNPname = request.GET['text_box']
		disorder_num = request.GET['dropdown']
		studyData = study.objects.all()
		SNPData = SNP_entry.objects.all()
		filterSNP = SNP_entry.objects.filter(SNP_id=SNPname).filter(disorder=disorder_num)

		# WRITE TO EXCEL FILE
		if os.path.exists('SNPData.xlsx'): os.remove('geneData.xlsx')
		workbook = xlsxwriter.Workbook('geneData.xlsx')
		worksheet1 = workbook.add_worksheet('studyData')
		worksheet2 = workbook.add_worksheet('SNP_entryData')

		excel_data(workbook, worksheet1, worksheet2, filterSNP)

		table = SimpleTable(filterSNP, template_name='django_tables2/bootstrap-responsive.html')
		return render(request, 'pages/database.html', {'table': table})

def get_Disorder(request):
	if request.method == 'GET':
		disorder_num = request.GET['dropdown']
		studyData = study.objects.all()
		SNPData = SNP_entry.objects.all()
		filterDisorder = SNP_entry.objects.filter(disorder=disorder_num)

		# WRITE TO EXCEL FILE
		if os.path.exists('geneData.xlsx'): os.remove('geneData.xlsx')
		workbook = xlsxwriter.Workbook('geneData.xlsx')
		worksheet1 = workbook.add_worksheet('studyData')
		worksheet2 = workbook.add_worksheet('SNP_entryData')

		excel_data(workbook, worksheet1, worksheet2, filterDisorder)

		table = SimpleTable(filterDisorder, template_name='django_tables2/bootstrap-responsive.html')
		return render(request, 'pages/database.html', {'table': table})

def index(request):
	return render(request, 'pages/index.html')

def results(request):
	return render(request, 'pages/results.html')

def methods(request):
	return render(request, 'pages/methods.html')

def about(request):
	return render(request, 'pages/about.html')

def contacts(request):
	return render(request, 'pages/contact.html')

def input(request):
	return render(request, 'pages/input.html')

#Trigger Rscript
def gene(request):

	retcode = subprocess.call("Rscript --vanilla examples/meta_analysis_SNP.r", shell=True)
	wb=xlrd.open_workbook("geneData.xlsx")
	sheet = wb.sheet_by_index(1)
	context = {
		"name": sheet.cell_value(1, 19)
	}
	return render(request, 'pages/gene.html', context)

def search(request):
	return render(request, 'pages/search.html')

def database(request):
	data = study.objects.all()
	table = SimpleTable(data, template_name='django_tables2/bootstrap-responsive.html')
	return render(request, 'pages/database.html', {'table': table})
	#return TemplateResponse(request, 'pages/disorders.html',{"data": data})

def excel_data(workbook, worksheet1, worksheet2, filter):
	row = 0
	# write headers
	worksheet1.write(row, 0, "studyId")
	worksheet1.write(row, 1, "Pmid")
	worksheet1.write(row, 2, "design")
	worksheet1.write(row, 3, "type of study")
	worksheet1.write(row, 4, "ethnic Population")
	worksheet1.write(row, 5, "source")
	worksheet1.write(row, 6, "platform")
	worksheet1.write(row, 7, "the_domain")
	worksheet1.write(row, 8, "num_SNPs")
	worksheet1.write(row, 9, "num_polys")
	worksheet1.write(row, 10, "DX")
	worksheet1.write(row, 11, "Case_N")
	worksheet1.write(row, 12, "Case_perc_fem")
	worksheet1.write(row, 13, "Case_age")
	worksheet1.write(row, 14, "Control_N")
	worksheet1.write(row, 15, "Control_perc_fem")
	worksheet1.write(row, 16, "Control_age")
	worksheet1.write(row, 17, "num_families")
	worksheet1.write(row, 18, "num_affected")
	worksheet1.write(row, 19, "num_generations")
	worksheet1.write(row, 20, "mean_score")
	worksheet1.write(row, 21, "SD_score")
	worksheet1.write(row, 22, "measure_used")
	worksheet1.write(row, 23, "disorder")
	worksheet1.write(row, 24, "test")
	worksheet1.write(row, 25, "hyperlink")

	worksheet2.write(row, 0, "entryId")
	worksheet2.write(row, 1, "SNP_id")
	worksheet2.write(row, 2, "Meta_p_value")
	worksheet2.write(row, 3, "SNP_chromosome_location")
	worksheet2.write(row, 4, "SNP_chromosome_band")
	worksheet2.write(row, 5, "SNP_position")
	worksheet2.write(row, 6, "SNP_version")
	worksheet2.write(row, 7, "odds_risk")
	worksheet2.write(row, 8, "odds_risk_lci")
	worksheet2.write(row, 9, "odds_risk_uci")
	worksheet2.write(row, 10, "ethnicity_1000_pop")
	worksheet2.write(row, 11, "REF_allele")
	worksheet2.write(row, 12, "ALT_allele")
	worksheet2.write(row, 13, "EFF_score")
	worksheet2.write(row, 14, "EFF_var")
	worksheet2.write(row, 15, "mtc_pvalue")
	worksheet2.write(row, 16, "SNP_risk")
	worksheet2.write(row, 17, "SNP_test")
	worksheet2.write(row, 18, "SNP_hyperlink")
	worksheet2.write(row, 19, "gene_name")
	worksheet2.write(row, 20, "gene_ensmbl_id")
	worksheet2.write(row, 21, "gene_chr")
	worksheet2.write(row, 22, "gene_band")
	worksheet2.write(row, 23, "gene_start")
	worksheet2.write(row, 24, "gene_end")
	worksheet2.write(row, 25, "gene_risk_status")
	worksheet2.write(row, 26, "gene_hyperlink")
	worksheet2.write(row, 27, "disorder")
	worksheet2.write(row, 28, "study_id")

	row = 1
	# write data
	for g in filter:
		col = 0
		worksheet1.write(row, col, g.study_id.study_id)
		worksheet1.write(row, col + 1, g.study_id.pmid)
		worksheet1.write(row, col + 2, g.study_id.design)
		worksheet1.write(row, col + 3, g.study_id.type_of_study)
		worksheet1.write(row, col + 4, g.study_id.ethnic_Population)
		worksheet1.write(row, col + 5, g.study_id.source)
		worksheet1.write(row, col + 6, g.study_id.platform)
		worksheet1.write(row, col + 7, g.study_id.the_domain)
		worksheet1.write(row, col + 8, g.study_id.num_SNPs)
		worksheet1.write(row, col + 9, g.study_id.num_polys)
		worksheet1.write(row, col + 10, g.study_id.DX)
		worksheet1.write(row, col + 11, g.study_id.Case_N)
		worksheet1.write(row, col + 12, g.study_id.Case_perc_fem)
		worksheet1.write(row, col + 13, g.study_id.Case_age)
		worksheet1.write(row, col + 14, g.study_id.Control_N)
		worksheet1.write(row, col + 15, g.study_id.Control_perc_fem)
		worksheet1.write(row, col + 16, g.study_id.Control_age)
		worksheet1.write(row, col + 17, g.study_id.num_families)
		worksheet1.write(row, col + 18, g.study_id.num_affected)
		worksheet1.write(row, col + 19, g.study_id.num_generations)
		worksheet1.write(row, col + 20, g.study_id.mean_score)
		worksheet1.write(row, col + 21, g.study_id.SD_score)
		worksheet1.write(row, col + 22, g.study_id.measure_used)
		worksheet1.write(row, col + 23, g.study_id.disorder)
		worksheet1.write(row, col + 24, g.study_id.test)
		worksheet1.write(row, col + 25, g.study_id.hyperlink)
		worksheet2.write(row, col, g.entry_id)
		worksheet2.write(row, col + 1, g.SNP_id)
		worksheet2.write(row, col + 2, g.Meta_p_value)
		worksheet2.write(row, col + 3, g.SNP_chromosome_location)
		worksheet2.write(row, col + 4, g.SNP_chromosome_band)
		worksheet2.write(row, col + 5, g.SNP_position)
		worksheet2.write(row, col + 6, g.SNP_version)
		worksheet2.write(row, col + 7, g.odds_risk)
		worksheet2.write(row, col + 8, g.odds_risk_lci)
		worksheet2.write(row, col + 9, g.odds_risk_uci)
		worksheet2.write(row, col + 10, g.ethnicity_1000_pop)
		worksheet2.write(row, col + 11, g.REF_allele)
		worksheet2.write(row, col + 12, g.ALT_allele)
		worksheet2.write(row, col + 13, g.EFF_score)
		worksheet2.write(row, col + 14, g.EFF_var)
		worksheet2.write(row, col + 15, g.mtc_pvalue)
		worksheet2.write(row, col + 16, g.SNP_risk)
		worksheet2.write(row, col + 17, g.SNP_test)
		worksheet2.write(row, col + 18, g.SNP_hyperlink)
		worksheet2.write(row, col + 19, g.gene_name)
		worksheet2.write(row, col + 20, g.gene_ensmbl_id)
		worksheet2.write(row, col + 21, g.gene_chr)
		worksheet2.write(row, col + 22, g.gene_band)
		worksheet2.write(row, col + 23, g.gene_start)
		worksheet2.write(row, col + 24, g.gene_end)
		worksheet2.write(row, col + 25, g.gene_risk_status)
		worksheet2.write(row, col + 26, g.gene_hyperlink)
		worksheet2.write(row, col + 27, g.disorder)
		row += 1
	workbook.close()


#!/usr/bin/env python
import bpy
from math import log
from mathutils import Vector
from bpy.props import *

## CamAnim
## a Blender Python extension by Joshua R (GitHub user Botmasher)
##
## Ordered marking of camera locations and rotations.
## Automatic camera animation along those markers.
##

# TODO check that replace_current_markers and remove_current_markers do not break cycling or placement

# TODO adjust all markers, or all markers following currently selected one

# TODO allow for multiple cameras (currently leans on scene camera)
# - place, replace, jump, animate methods now take camera
# - check and pass currently selected camera from operators
# - update markers to store name of camera as well, allowing multiple tracks for multiple cameras

# TODO track markers (incl replace and remove) through something other than name (add uuid property?)

# TODO allow for undoing keyframing along path and resetting it

# NOTE sketch procedure to get all cameras
def get_scene_cameras():
	cams = []
	scene = bpy.context.scene
	for obj in scene.objects:
		if obj.type == 'CAMERA':
			cams.append(obj)
	return cams

# UI props for setting keyframing params
def setup_cam_ui_props():
	Cam = bpy.types.Camera
	cam.camanim_frames_per_space = FloatProperty(name="Location frames", description="How many frames to count between location units", default=3)
	Cam.camanim_frames_per_degree = FloatProperty(name="Rotation frames", description="How many frames to count between rotation degrees", default=0.1)
	Cam.camanim_min_frames_per_kf = IntProperty(name="Min in-betweens", description="Minimum number of frames between keyframes", default=0)
	Cam.camanim_max_frames_per_kf = IntProperty(name="Max in-betweens", description="Maximum number of frames between keyframes", default=9999)
	Cam.camanim_frames_pause = IntProperty(name="Pause frames", description="Length of \"long keyframes\" between movements", default=3)
	return

class CamAnim:
	def __init__(self, marker_name_text="camanim_marker"):
		# internal refs for building and storing markers
		self.sorted_markers = []                  # marker objects store cam loc-rot state
		self.marker_name_text = marker_name_text  # unique string found only in marker names - suffix added on duplication
		self.current_marker = None
		return None

	def find_highest_suffix(self):
		"""Find the highest numeral suffixed to placed marker names"""
		highest_i = 0
		found_marker = False
		for obj in bpy.context.scene.objects:
			if self.is_marker(obj):
				found_marker = True
				split_name = obj.name.split(".")
				marker_i = int(split_name[len(split_name)-1]) if len(split_name) > 0 else 0
				highest_i = marker_i if marker_i > highest_i else highest_i
		if found_marker:
			return highest_i
		else:
			return -1

	def place_marker(self, camera):
		"""Place marker in the scene at current cam loc and rot"""
		# create object
		marker = bpy.data.objects.new(name="", object_data=None)
		bpy.context.scene.objects.link(marker)
		marker.empty_draw_type = "SINGLE_ARROW"

		# orient to camera
		marker.rotation_euler = camera.rotation_euler

		# take over the duplication naming process
		# - append number to base name counting from "1"
		# - look for and increment largest suffix so far
		marker_suffix = self.find_highest_suffix() + 1
		marker.name = "{0}.{1}".format(self.marker_name_text, marker_suffix)
		marker.location = camera.location

		self.current_marker = marker
		return marker

	def replace_marker(self, camera, marker):
		"""Update selected placed marker in the scene to current cam loc and rot"""
		if not self.is_marker(marker): return
		marker.location = camera.location
		marker.rotation_euler = camera.rotation_euler
		self.current_marker = marker
		return marker

	def replace_current_marker(self, camera):
		"""Update current camera marker in the scene to a new cam loc and rot"""
		marker = self.current_marker
		if marker is None: return
		self.replace_marker(camera, marker)
		return marker

	def remove_marker(self, marker=None):
		"""Delete selected placed marker from camanim tracking"""
		if self.is_marker(marker):
			bpy.context.scene.objects.unlink(marker)					# remove from scene
			bpy.data.objects.remove(marker, do_unlink=True)		# delete and verify unlink from whole project
		return marker

	def remove_current_marker(self):
		"""Delete current camer marker from camanim tracking"""
		marker = self.current_marker
		if marker is None: return
		self.remove_marker(marker)
		return marker

	def jump_first_marker(self, camera):
		"""Jump to the first tracked marker"""
		self.sort_markers()
		if len(self.sorted_markers) < 1: return False
		self.snap_cam_to_marker(camera, self.sorted_markers[0])
		return True

	def jump_last_marker(self, camera):
		"""Jump to the final tracked marker"""
		self.sort_markers()
		if len(self.sorted_markers) < 1: return False
		self.snap_cam_to_marker(camera, self.sorted_markers[len(self.sorted_markers) - 1])
		return True

	def jump_marker(self, camera, marker_count):
		"""Jump camera a certain number of markers earlier or later along path"""
		self.sort_markers()
		if len(self.sorted_markers) < 1:
			return 0
		# determine index to jump from
		current_index = 0
		if self.current_marker is not None: 	# else current_index = 0
			for i in range(len(self.sorted_markers)):
				if self.sorted_markers[i] == self.current_marker:
					current_index = i
		# add index to jump to
		jump_i = current_index + marker_count
		# clamp jump to marker list length
		clamped_jump_i = jump_i % (len(self.sorted_markers))
		self.snap_cam_to_marker(camera, self.sorted_markers[clamped_jump_i])
		return clamped_jump_i

	def has_current_marker(self):
		"""Check if there is a stored current marker"""
		if self.current_marker is not None:
			return True
		return False

	def has_any_marker(self):
		"""Check if there are any stored markers"""
		self.sort_markers()
		if len(self.sorted_markers) > 0:
			return True
		return False

	def is_marker(self, obj=None):
		"""Check that an object's name contains the unique marker name base string"""
		if obj is not None and len(obj.name) >= len(self.marker_name_text) and self.marker_name_text == obj.name[0:len(self.marker_name_text)]:
			return True
		return False

	def get_current_marker_details(self):
		"""Find the name and index of the current marker"""
		if self.current_marker:
			return {
				'name': self.current_marker.name,
				'id': self.get_marker_index(self.current_marker)
			}
		return {}

	def get_marker_index(self, marker):
		"""Return the index along path of the current marker"""
		if marker is not None:
			self.sort_markers()
			marker_i = None
			for i in range(len(self.sorted_markers)):
				if self.sorted_markers[i] == marker:
					marker_i = i
			if marker_i is not None: return marker_i
		return None

	def snap_cam_to_marker(self, camera, marker):
		"""Set camera location and rotation to match marker"""
		camera.location = marker.location
		camera.rotation_euler = marker.rotation_euler
		self.current_marker = marker
		return marker

	def sort_markers(self):
		"""Retrieve well-named markers and sort from earliest to latest"""

		marker_indexes = [] 	# store all suffix "indexes" to sort
		markers_by_index = {} 	# marker_index: marker_object pairs for hash retrieval after sort

		# catalog indexes suffixed to all marker objects
		# NOTE relies on proper name formatting on marker creation
		for obj in bpy.context.scene.objects:
			if self.is_marker(obj):
				marker_split_name = obj.name.split(".") 	# "name_base.nnn"
				marker_index = int(marker_split_name[len(marker_split_name)-1])
				markers_by_index[marker_index] = obj
				marker_indexes.append(marker_index)
		# sort split suffixes and grab markers in that order
		marker_indexes.sort()
		markers = [markers_by_index[i] for i in marker_indexes]
		self.sorted_markers = markers
		return markers

	def animate(self, camera, frames_per_space=3, frames_per_degree=0.1, min_frames_per_kf=0, max_frames_per_kf=9999, frames_pause=3):
		"""Use placed markers to set keyframes timed out by frames per loc and rot unit"""
		self.sort_markers()
		bpy.context.scene.frame_current = bpy.context.scene.frame_start + 1

		# keyframe cam along markers
		for i in range(len(self.sorted_markers)):
			marker = self.sorted_markers[i]
			self.snap_cam_to_marker(camera, marker)
			camera.keyframe_insert("location")
			camera.keyframe_insert("rotation_euler")
			# start/end stasis gaps
			if 0 < i < len(self.sorted_markers) - 1 and frames_pause > 0:
				bpy.context.scene.frame_current += frames_pause
				camera.keyframe_insert("location")
				camera.keyframe_insert("rotation_euler")

			# calculate diff between keyframes
			if i < len(self.sorted_markers) - 1:
				this_marker = self.sorted_markers[i]
				next_marker = self.sorted_markers[i + 1]
				loc_distance = (next_marker.location - this_marker.location).length
				rot_distance = (Vector(next_marker.rotation_euler) - Vector(this_marker.rotation_euler)).magnitude * 57.2958
				# smooth frame count over distance to give sense of reaching top speed
				added_loc_frames = int(log(max(1, 10 * frames_per_space * loc_distance), 2))
				added_rot_frames = int(log(max(1, frames_per_degree * rot_distance), 2))
				added_frames = added_loc_frames + added_rot_frames
				# clamp frame count between the two keyframes
				clamped_frames = min(max(min_frames_per_kf, int(added_frames)), max_frames_per_kf)
			else:
				clamped_frames = 0
			bpy.context.scene.frame_current += clamped_frames

		# stretch timeline to fit keyframes
		if bpy.context.scene.frame_current > bpy.context.scene.frame_end:
			bpy.context.scene.frame_end = bpy.context.scene.frame_current + 1

		return None

camanim = CamAnim()

def is_camera(obj=bpy.context.scene.objects.active):
	"""Check if an object has type 'CAMERA'"""
	return ctx.scene.objects.active.type == ctx.scene.camera.type

class CamAnimPanel(bpy.types.Panel):
	bl_label = "CamAnim"
	bl_idname = "camera.camanim_panel"
	bl_space_type = "VIEW_3D"
	bl_region_type = "TOOLS"
	bl_category = "CamAnim"

	def draw(self, ctx):
		setup_cam_ui_props()

		layout = self.layout

		if ctx.scene.objects.active == ctx.scene.camera or camanim.is_marker(obj=ctx.scene.objects.active):
			col = layout.column(align=True)

			# update marker data and marker objects
			col.label("Manage markers")
			col.operator("camera.camanim_set_marker", text="Place marker")
			col.operator("camera.camanim_replace_current_marker", text="Update marker")
			col.operator("camera.camanim_remove_current_marker", text="Delete marker")

			# update camera loc-rot to match marker loc-rot
			if camanim.has_any_marker():
				col.label("Jump to marker")
				row = col.row(align=True)
				row.operator("camera.camanim_first_marker", text="First")
				row.operator("camera.camanim_last_marker", text="Last")
				if camanim.has_current_marker():
					row = col.row(align=True)
					row.operator("camera.camanim_prev_marker", text="Previous")
					row.operator("camera.camanim_next_marker", text="Next")

			# update marker data and display marker stats
			current_marker_stats = camanim.get_current_marker_details()
			col.operator("camera.camanim_refresh_markers", text="Refresh markers")
			if current_marker_stats and current_marker_stats['id'] is not None and current_marker_stats['id'] > -1:
				col.label("marker %s: %s" % (current_marker_stats.get('id'), current_marker_stats.get('name')))
			else:
				col.label("(no current marker)")

			# set keyframes
			if camanim.has_any_marker():
				col.label("Animate camera")
				cam = ctx.scene.camera.data
				col.row().prop(cam, "camanim_frames_per_space")
				col.row().prop(cam, "camanim_frames_per_degree")
				col.row().prop(cam, "camanim_min_frames_per_kf")
				col.row().prop(cam, "camanim_max_frames_per_kf")
				col.row().prop(cam, "camanim_frames_pause")
				col.row().operator("camera.camanim_animate", text="Keyframe camera")

		# invalid selection
		else:
			layout.label("Select Scene Camera...")

		return None

class CamAnimSetMarker(bpy.types.Operator):
	bl_label = "CamAnim Set Marker"
	bl_idname = "camera.camanim_set_marker"
	bl_description = "Place marker along CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def execute(self, ctx):
		obj = ctx.scene.objects.active
		if is_camera():
			camanim.place_marker(obj)
		return {'FINISHED'}

class CamAnimReplaceMarker(bpy.types.Operator):
	bl_label = "CamAnim Replace Marker"
	bl_idname = "camera.camanim_replace_current_marker"
	bl_description = "Replace current marker along CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def execute(self, ctx):
		camanim.replace_current_marker(bpy.context.scene.camera)
		return {'FINISHED'}

class CamAnimRemoveMarker(bpy.types.Operator):
	bl_label = "CamAnim Remove Marker"
	bl_idname = "camera.camanim_remove_current_marker"
	bl_description = "Remove marker from CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def execute(self, ctx):
		camanim.remove_current_marker(bpy.context.scene.objects.active)
		return {'FINISHED'}

class CamAnimRefreshMarkers(bpy.types.Operator):
	bl_label = "CamAnim Refresh Markers"
	bl_idname = "camera.camanim_refresh_markers"
	bl_description = "Jump to current marker along CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def execute(self, ctx):
		camanim.jump_marker(bpy.context.scene.camera, 0)
		return {'FINISHED'}

class CamAnimFirstMarker(bpy.types.Operator):
	bl_label = "CamAnim First Marker"
	bl_idname = "camera.camanim_first_marker"
	bl_description = "Jump to first marker along CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def draw(self, ctx):
		self.layout.row().label("Jumping to first available marker")

	def execute(self, ctx):
		camanim.jump_first_marker(bpy.context.scene.camera)
		return {'FINISHED'}

class CamAnimPrevMarker(bpy.types.Operator):
	bl_label = "CamAnim Previous Marker"
	bl_idname = "camera.camanim_prev_marker"
	bl_description = "Jump to previous marker along CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def draw(self, ctx):
		self.layout.row().label("Jumping to previous available marker")

	def execute(self, ctx):
		camanim.jump_marker(bpy.context.scene.camera, -1)
		return {'FINISHED'}

class CamAnimNextMarker(bpy.types.Operator):
	bl_label = "CamAnim Next Marker"
	bl_idname = "camera.camanim_next_marker"
	bl_description = "Jump to next marker along CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def draw(self, ctx):
		self.layout.row().label("Jumping to next available marker")

	def execute(self, ctx):
		camanim.jump_marker(bpy.context.scene.camera, 1)
		return {'FINISHED'}

class CamAnimLastMarker(bpy.types.Operator):
	bl_label = "CamAnim Last Marker"
	bl_idname = "camera.camanim_last_marker"
	bl_description = "Jump to final marker along CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def draw(self, ctx):
		self.layout.row().label("Jumping to last available marker")

	def execute(self, ctx):
		camanim.jump_last_marker(bpy.context.scene.camera)
		return {'FINISHED'}

class CamAnimAnimate(bpy.types.Operator):
	bl_label = "CamAnim Animate"
	bl_idname = "camera.camanim_animate"
	bl_description = "Follow and keyframe along CamAnim path"
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(c, ctx):
		return ctx.mode == "OBJECT"

	def execute(self, ctx):
		camanim.animate(bpy.context.scene.camera)
		return {'FINISHED'}

def register():
	bpy.utils.register_class(CamAnimPanel)
	bpy.utils.register_module(__name__)

def unregister():
	bpy.utils.unregister_class(CamAnimPanel)
	bpy.utils.unregister_module(__name__)

if __name__ == "__main__": register()


import math

# fast-power  O(logN) time
def fast_power(g, p, MOD):
    # base num is a
    # result is b
    a = g
    b = 1
    while p > 0:
        # fast power
        # do mod every time

        # if p is odd, we should multiple a single base num a to result
        if p % 2 == 1:
            b = b * a % MOD

        # do a^2 to reduce time to compute b by multipling b every time
        a = a ** 2 % MOD
        p = int(p / 2)
    return b % MOD

def getECCResult(Xp, Yp, Xq, p, lambdaK):
    # get b by using b = yp - lamba * xp
    b = Yp - lambdaK * Xp

    # get Xr by using Xr = lamba^2 - Xp - Xq
    Xr = (lambdaK * lambdaK - Xp - Xq) % p

    # get Yr by using Yr = lambda * Xr + b
    Yr = lambdaK * Xr + b

    # get Yr' by using Yr' = -Yr (mod p)
    Yr1 = (-Yr) % p

    # return result
    return Xr, Yr1

def point_double(A, B, p, Xp, Yp):
    # derivation is (3 * X^2 + A) / (2 * Y)
    numerator = (3 * Xp * Xp + A) % p
    denominator = (2 * Yp) % p

    # lambdaK = numerator / denominator, run as numerator * (1 / denominator)
    # call fast_power to reduce running time
    lambdaK = (numerator * fast_power(denominator, p - 2, p)) % p
    return getECCResult(Xp, Yp, Xp, p, lambdaK)

def point_add(A, B, p, Xp, Yp, Xq, Yq):
    # get lambaK by using point P and point Q
    numerator = (Yq - Yp) % p
    denominator = (Xq - Xp) % p

    # lambdaK = numerator / denominator,  run as numerator * (1 / denominator)
    # call fast_power to reduce running time
    lambdaK = (numerator * fast_power(denominator, p - 2, p)) % p

    # get ECC result = P + Q
    result = getECCResult(Xp, Yp, Xq, p, lambdaK)

    # return result
    return result

def ECCMultiple(A, B, p, Xp, Yp, a):
    # if a is 1, just return point P
    if a == 1:
        return Xp, Yp

    # copy a for iteration
    n = a

    # initial value for double-add algorithm
    # consider odd or even to make logic right
    if n % 2 == 1:
        R = (Xp, Yp)
        Q = (Xp, Yp)
        n = a - 1
    else:
        R = point_double(A, B, p, Xp, Yp)
        Q = R
        n = a - 2

    # double and add to reduce running time
    while n > 0:
        if n % 2 == 1:
            # call point_add function to calculate R = R + Q
            R = point_add(A, B, p, R[0], R[1], Q[0], Q[1])

        # calculate Q = 2 * Q
        Q = point_double(A, B, p, Q[0], Q[1])
        n = n // 2

    # return result
    return R

# open files
input_file = open("input.txt", "r")

# get nums and points from file
A = int(input_file.readline().strip('\n'))
B = int(input_file.readline().strip('\n'))
p = int(input_file.readline().strip('\n'))
Point_P = input_file.readline().strip('\n')

# get coordinates of point p
Xp = int(Point_P.split(',')[0])
Yp = int(Point_P.split(',')[1])

# check if fifth element is point or integer
fifth_input = input_file.readline().strip('\n')

# if it is point Q
if ',' in fifth_input:
    # get point Q
    Xq = int(fifth_input.split(',')[0])
    Yq = int(fifth_input.split(',')[1])

    # call point_add function to calculate R = P + Q
    print('P = (', Xp, ',', Yp, ')')
    print('Q = (', Xq, ',', Yq, ')')
    print('P + Q = ', point_add(A, B, p, Xp, Yp, Xq, Yq))

else:
    # get a
    a = int(fifth_input)
    # call point_add function to calculate R = a * P
    print('a = ', a)
    print('P = (', Xp, ',', Yp, ')')
    print('R = a * P = ', ECCMultiple(A, B, p, Xp, Yp, a))

input_file.close()


#Entradas
nombre=str(input("Ingrese nombre del trabajador: "))
hijos=int(input("Ingrese numero de hijos del trabajador: "))
hogares=int(input("Ingrese numero de hogares del trabajador: "))
act=int(input("Ingrese la cantidad de actualizaciones academicas del trabajador: "))
nhoras=int(input("Ingrese numero de horas de trabajo: "))
phoras=float(input("Ingrese el precio por una hora: "))
ehoras=int(input("Ingrese numero de horas extra: "))
#Caja Negra
pehoras=(ehoras*0.25)
sbase=(nhoras*phoras)
d1=(sbase*0.95)
d2=(sbase*0.98)
d3=(sbase*0.93)
dt=(d1+d2+d3)
a1=(sbase+250000*act)
a2=(sbase+173000*hijos)
a3=(sbase+180000*hogares)
at=(a1+a2+a3)
sneto=(sbase+pehoras+dt+at)
#Salidas
print(f"Las deducciones sobre el sueldo son de ${dt}.")
print(f"Las asignaciones sobre el sueldo son de ${at}.")
print(f"El sueldo neto de {nombre} es: ${sneto}.")


import numpy as np
import matplotlib.pyplot as plt
import cv2
# my processing function - make sure that this file is imported
import processingFunctions as pf

def channelToImage(channels):
    _, M, N = channels.shape
    Blue = (channels[0]).reshape((M, N, 1))
    Green = (channels[1]).reshape((M, N, 1))
    Red = (channels[2]).reshape((M, N, 1))
    img = np.concatenate([Blue, Green, Red], axis=-1)
    return img

# extracts channel and normalizes the channels
def channelExtractor(I):
    M, _ = I.shape
    N = int(np.floor(M/3))
    Blue_channel = (I[0 : N] / (2 ** 16 - 1)).astype(np.float64)
    Green_channel = (I[N : 2*N] / (2 ** 16 - 1)).astype(np.float64)
    Red_channel = (I[2*N : 3*N] / (2 ** 16 - 1)).astype(np.float64)
    channels = np.stack([Blue_channel, Green_channel, Red_channel], axis=0)
    return channels

# calculate error:
def errorCal(chn1, chn2, errMod):
    M, N = chn1.shape
    Error = 0
    if errMod == 'ABS':
        return np.sum( np.abs(chn1 - chn2) )
    else:
        return np.sqrt(np.sum( (chn1 - chn2) ** 2 ))

# shift the channel along with 'one' axis at a time
def channelShifter(chn, shift):
    chnShifted = np.copy(chn)

    M, N = chnShifted.shape
    if shift[0] >= 0:
        for i in range(M):
            chnShifted[i, int(shift[0]):] = chnShifted[i, 0:N-int(shift[0])]
    else:
        for i in range(M):
            chnShifted[i, 0:N+int(shift[0])] = chnShifted[i, -int(shift[0]):]

    if shift[1] >= 0:
        for j in range(N):
            chnShifted[int(shift[1]):, j] = chnShifted[0:M-int(shift[1]), j]
    else:
        for j in range(N):
            chnShifted[0:M+int(shift[1]), j] = chnShifted[-int(shift[1]):, j]

    return chnShifted

# resolution change
def changeRes(chn, coeff):
    M, N = chn.shape
    Mo, No = ( int(np.ceil(M / coeff)), int(np.ceil(N / coeff)) )
    resizedChn = np.zeros((Mo, No), dtype=chn.dtype)
    for i in range(0,M,coeff):
        resizedChn[int(i / coeff), : ] = chn[i, np.arange(0, N, coeff)]

    return resizedChn

def findProperShift(fixedChn, movingChn, resFactor, fixedInterval, errMod='RMS'):
    properShift = np.zeros(2, dtype=int)
    for frac in range(int(np.log2(resFactor)) + 1):
        properShift *= 2

        currentFactor = int(resFactor / ( 2 ** frac) ) # changing resultion factor
        fixedResized = changeRes(fixedChn, currentFactor)
        movingResized = changeRes(movingChn, currentFactor)

        M, N = fixedResized.shape

        if frac == 0:
            errors = np.zeros( (4 * fixedInterval + 1 , 4 * fixedInterval + 1) ) # in last level enlarge interval by two
            for i in range(4 * fixedInterval + 1):
                for j in range(4 * fixedInterval + 1):
                    xshift = int((i - 2 * fixedInterval + properShift[0]))
                    yshift = int((j - 2 * fixedInterval + properShift[1]))
                    C = channelShifter(movingResized, (xshift, yshift) )
                    errors[i, j] = errorCal(fixedResized[2*fixedInterval:M-2*fixedInterval, 2*fixedInterval:N-2*fixedInterval],
                                                       C[2*fixedInterval:M-2*fixedInterval, 2*fixedInterval:N-2*fixedInterval], errMod)

            ind = np.array(np.unravel_index(np.argmin(errors), errors.shape), dtype=properShift.dtype)
            properShift += ind - np.array([2 * fixedInterval, 2 * fixedInterval], dtype=properShift.dtype)

        else:
            errors = np.zeros( (2*fixedInterval+1 , 2*fixedInterval+1) )
            for i in range(2 * fixedInterval + 1):
                for j in range(2 * fixedInterval + 1):
                    xshift = int((i - fixedInterval + properShift[0]))
                    yshift = int((j - fixedInterval + properShift[1]))
                    C = channelShifter(movingResized, (xshift, yshift) )
                    errors[i, j] = errorCal(fixedResized[fixedInterval:M-fixedInterval, fixedInterval:N-fixedInterval],
                                                       C[fixedInterval:M-fixedInterval, fixedInterval:N-fixedInterval], errMod)

            ind = np.array(np.unravel_index(np.argmin(errors), errors.shape), dtype=properShift.dtype)
            properShift += ind - np.array([fixedInterval, fixedInterval], dtype=properShift.dtype)

        print("Current stage: {}".format(frac))
        print("Current shifts: ({}, {})".format(properShift[0], properShift[1]) )

    return properShift

def findClip(chn1_shift, ch2_shift):
    positive_clip = 0
    negative_clip = -1
    if chn1_shift * ch2_shift > 0:
        if chn1_shift > 0:
            positive_clip = np.amax([chn1_shift, ch2_shift])
        else:
            negative_clip = np.amin([chn1_shift, ch2_shift])
    else:
        if chn1_shift > 0:
            positive_clip = chn1_shift
            negative_clip = ch2_shift
        else:
            positive_clip = ch2_shift
            negative_clip = chn1_shift

    return [positive_clip, negative_clip]

def whiteColorClipper(cols, chn_col_numbers):
    white_thr = np.sum(cols[:, 0:5]) / (3 * 5) - 0.02
    _, y = np.where(cols >= white_thr)
    left_margin = np.amax(y[np.where(y < chn_col_numbers//32)])
    right_margin = np.amin(y[np.where(y > chn_col_numbers//32)])
    return [left_margin, right_margin]

def calColorRow(chns):
    _, _, N = chns.shape
    color_rows = np.sum(chns, axis=2) / N
    return color_rows

def calColorCol(chns):
    _, M, _ = chns.shape
    color_cols = np.sum(chns, axis=1) / M
    return color_cols

def gaussianKernel(sigma, N):
    gauss = lambda sig, x: 1 / (np.sqrt(2 * np.pi) * sig) * np.exp(-x**2 / (2 * (sig ** 2)))
    sigmaList = np.ones(N*N) * sigma
    xList = np.arange(N) - ((N-1) / 2)
    gaussVal = np.array(list(map(gauss, sigmaList, xList))).reshape(N, 1)
    # for two dimmensional kernel:
    # kernel = gaussVal @ gaussVal.T
    return gaussVal / (np.sum(gaussVal))

# if col is inserted => negative: left, positive: right
# if row is inserter => negative: up, positive: down
def findFracIndex(chn_color, len_val, sigma, ksize):
    # cal derivative:
    chn_color_diff = np.abs(np.sum(np.diff(chn_color), axis=0) / 3)

    # filtering
    kernel = gaussianKernel(sigma, ksize)
    kernel = kernel.reshape(len(kernel))
    chn_color_diff = np.convolve(chn_color_diff, kernel, 'same')

    # normalizing
    chn_color_diff /= np.amax(chn_color_diff)

    # used for report:
    # plt.plot(np.arange(len(chn_color_diff)), chn_color_diff)
    # plt.xlabel('Pixels')
    # plt.ylabel('value')
    # plt.title('Smoothed derivative (abs)')
    # plt.grid(True)
    # plt.show()

    thr = 10 * np.sum(chn_color_diff) / len_val

    indices = np.array(np.where(chn_color_diff >= thr))
    indices = indices.reshape(indices.shape[1])
    negative_halves = indices[indices <= len_val // 2]
    positive_halves = indices[indices > len_val // 2]

    if len(negative_halves) == 0:
        negative_half = 0
    else:
        negative_half = negative_halves[-1]

    if len(positive_halves) == 0:
        positive_half = 0
    else:
        positive_half = positive_halves[0]

    return [negative_half, positive_half]

# change the picture name to use other pictures
print("Enter the img's name (without .tif, e.g. Amir, Train, Mosque etc)")
picture_name = input()
I = cv2.imread(picture_name + '.tif', cv2.IMREAD_UNCHANGED)
if I is None:
    raise(AttributeError("Img's name is wrong. Please make sure to enter ONLY the picture name (without .tif). Then check that if the img and this script are togheter."))
else:
    channels = channelExtractor(I)
    print("Img loaded successfully!")
    print("Starting procedures ...")
    print("--------------------------------------------------")
# channel extraction:

################################################################################
# proper shift finder:

# green channel is fixed:
resFactor = 16 # pyramid depth
fixedInterval = 4 # search interval
print("Finding red channel proper shift:")
redShift = findProperShift(channels[1], channels[2], resFactor, fixedInterval, 'ABS')
print("Finding blue channel shifts:")
blueShift = findProperShift(channels[1], channels[0], resFactor, fixedInterval, 'ABS')

# shift channels with respect to blueShift and redShift
print("--------------------------------------------------")
print("Final red channel's shift:")
print(redShift)
print("Final blue channel's shift:")
print(blueShift)
channels[0] = channelShifter(channels[0], blueShift)
channels[2] = channelShifter(channels[2], redShift)

################################################################################
# clip extra color caused by shifting the image:

[left_clip, right_clip] = findClip(redShift[1], blueShift[1])
[top_clip, bottom_clip] = findClip(redShift[0], blueShift[0])
channels = channels[:, left_clip:right_clip, top_clip:bottom_clip]

###############################################################################
# white color clipping:
color_cols = calColorCol(channels)
[left_margin, right_margin] = whiteColorClipper(color_cols, channels.shape[1])
channels = channels[:, :, left_margin:right_margin]

###############################################################################
# dark color clipping:
color_cols = calColorCol(channels)
color_rows = calColorRow(channels)

_, M, N = channels.shape

# find proper fraction of picture to be clipped
sigma = 2
[left_frac, right_frac] = findFracIndex(color_cols, N, sigma, 6*sigma+1)
[top_frac, bottom_frac] = findFracIndex(color_rows, M, sigma, 6*sigma+1)

channels = channels[:, top_frac:bottom_frac, left_frac:right_frac]

channels *= (2 ** 8 - 1)
img = channelToImage(channels.astype(np.uint8))

cv2.imwrite('res03-{}.jpg'.format(picture_name), img)

pf.showImg(img, (960, 960), 'Color Image')
cv2.waitKey(0)
cv2.destroyAllWindows()


water1 = [
    '너무 축축해요.',
    '너무 습한것 같아요.',
    '하마가 된 기분이에요.',
]

water2 = [
    '습도는 적당해요.',
    '적당히 건조해요.',
    '행복한 습도네요.',
]

water3 = [
    '너무 건조해요.',
    '땅이 갈라지고 있어요.',
    '목 말라요.',
]

temp1 = [
    '너무 더워요.',
    '온도가 너무 높아요.',
    '쪄 죽을것 같아요.',
]

temp2 = [
    '적당히 시원해요.',
    '행복해지는 온도네요.',
    '살것 같아요.',
]

temp3 = [
    '너무 추워요.',
    '얼어 죽을것 같아요.',
    '온도가 너무 낮아요.',
]

light1 = [
    '너무 마음에 들어요.',
    '무럭무럭 자라는 것 같아요.',
]

light2 = [
    '조금 어두워요.',
    '조금만 더 햇빛을 비춰주세요.',
]

light3 = [
    '너무 어두워요.',
    '성장판이 닫히는 느낌이에요.',
]

todayConditon1 = [
    '오늘 기분 최고에요!',
    '좋은 날이에요!',
    '행복해요!',
]

todayConditon2 = [
    '나쁘지 않네요.',
    '그럭저럭이네요.',
    '조금 힘들어요.',
]

todayConditon3 = [
    '너무 힘드네요.',
    '컨디션이 별로 안좋아요.',
    '저는 좋지 않네요.',
]


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

M=int(input())
num=list(map(int, input().split(' ')))

def find(num):
    left = 0
    right = N-1

    while left<=right:
        mid = (left + right) // 2

        if A[mid] == num:
            return True

        if A[mid] < num:
            left = mid + 1

        if A[mid] > num:
            right = mid - 1

for i in range(M):
    if find(num[i]):
        print(1)
    else:
        print(0)


import time
import gc
from datetime import datetime
from os import makedirs

import torch

from eval_run import eval_and_save_metrics
from utils import get_device, ResultWriter, log
from task import pubmed_task
from train import SentenceClassificationTrainer
from models import BertHSLN
import os

# BERT_VOCAB = "bert-base-uncased"
BERT_MODEL = "bert-base-uncased"
# BERT_VOCAB = "bert_model/scibert_scivocab_uncased/vocab.txt"
#BERT_MODEL = "allenai/scibert_scivocab_uncased"

config = {
    "bert_model": BERT_MODEL,
    "bert_trainable": False,
    "model": BertHSLN.__name__,
    "cacheable_tasks": [],

    "dropout": 0.5,
    "word_lstm_hs": 758,
    "att_pooling_dim_ctx": 200,
    "att_pooling_num_ctx": 15,

    "lr": 3e-05,
    "lr_epoch_decay": 0.9,
    "batch_size":  32,
    "max_seq_length": 128,
    "max_epochs": 20,
    "early_stopping": 5,

}

MAX_DOCS = -1
def create_task(create_func):
    return create_func(train_batch_size=config["batch_size"], max_docs=MAX_DOCS)

def create_generic_task(task_name):
    return generic_task(task_name, train_batch_size=config["batch_size"], max_docs=MAX_DOCS)

# ADAPT: Uncomment the task that has to be trained and comment all other tasks out

# ADAPT: Uncomment the task that has to be trained and comment all other tasks out
task = create_task(pubmed_task)
#task = create_task(pubmed_task_small)
#task = create_task(nicta_task)
#task = create_task(dri_task)
#task = create_task(art_task)
#task = create_task(art_task_small)
#task = create_generic_task(GEN_DRI_TASK)
#task = create_generic_task(GEN_PMD_TASK)
#task = create_generic_task(GEN_NIC_TASK)
# task = create_generic_task(GEN_ART_TASK)

# ADAPT: Set to False if you do not want to save the best model
save_best_models = True

# ADAPT: provide a different device if needed
device = get_device(0)

timestamp = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")

# ADAPT: adapt the folder name of the run if necessary
run = f"{timestamp}_{task.task_name}_baseline"

# -------------------------------------------

os.makedirs("results/complete_epoch_wise_new",exist_ok=True)
#run_results = f'/nfs/data/sentence-classification/results/{run}'
run_results = f'results/{run}'
makedirs(run_results, exist_ok=False)

# preload data if not already done
task.get_folds()

restarts = 1 if task.num_folds == 1 else 1
for restart in range(restarts):
    for fold_num, fold in enumerate(task.get_folds()):
        start = time.time()
        result_writer = ResultWriter(f"{run_results}/{restart}_{fold_num}_results.jsonl")
        result_writer.log(f"Fold {fold_num} of {task.num_folds}")
        result_writer.log(f"Starting training {restart} for fold {fold_num}... ")

        trainer = SentenceClassificationTrainer(device, config, task, result_writer)
        best_model = trainer.run_training_for_fold(fold_num, fold, return_best_model=save_best_models)
        if best_model is not None:
            model_path = os.path.join(run_results, f'{restart}_{fold_num}_model.pt')
            result_writer.log(f"saving best model to {model_path}")
            torch.save(best_model.state_dict(), model_path)

        result_writer.log(f"finished training {restart} for fold {fold_num}: {time.time() - start}")

        # explicitly call garbage collector so that CUDA memory is released
        gc.collect()

log("Training finished.")

log("Calculating metrics...")
eval_and_save_metrics(run_results)
log("Calculating metrics finished")


import canada
import caribbean
import centralamerica
import southamerica
import asia
import mideast
import europe
import africa
import australia
import worldcaps
import subprocess as sp
from time import sleep
import sys
import os
import contextlib
import re

def main():
	USA = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida","Georgia", "Hawaii",
		   "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine","Maryland", "Massachusetts", "Michigan",
		   "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska","Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York",
		   "North Carolina", "North Dakota","Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
		   "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"]

	USACC = ["Montgomery", "Juneau", "Phoenix", "Little Rock", "Sacramento", "Denver", "Hartford", "Dover","Tallahassee", "Atlanta", "Honolulu",
			 "Boise", "Springfield", "Indianapolis", "Des Moines", "Topeka","Frankfort", "Baton Rouge", "Augusta", "Annapolis", "Boston",
			 "Lansing", "St. Paul", "Jackson","Jefferson City", "Helena", "Lincoln", "Carson City", "Concord", "Trenton", "Santa Fe", "Albany",
			 "Raleigh", "Bismarck", "Columbus", "Oklahoma City", "Salem", "Harrisburg", "Providence", "Columbia","Pierre", "Nashville", "Austin",
			 "Salt Lake City", "Montpelier", "Richmond", "Olympia", "Charleston", "Madison", "Cheyenne"]

	tmp = sp.call('clear',shell=True)
	selection = print("\033[2;17HYou have chosen the \u001b[1mU.S.A..\033[0m")
	y = len(USA)
	score = 0

	for p in range(len(USA)):
		print("\033[2;17HYou have chosen the \u001b[1mU.S.A..\033[0m")
		print("\033[4;17HThere are %d States in the U.S.A.." % y)
		print("\033[6;17HLet's see how well you know your American geography.")
		print("\033[8;17HGOOD LUCK!")
		print("\033[10;35H*** U.S.A.***")
		print("\033[12;10H*******************************************************************")
		guess = str(input("\033[14;17H\033[0mWhat is the Capital of {}?: \033[0m".format(USA[p], p + 1)))

		if titlecase(guess) in USACC[p]:
			print("\033[16;17H\033[1;32mCongratulations! \033[0mYou are correct.")
			score += 1
			sleep(2)
			tmp = sp.call('clear',shell=True)
		else:
			print("\033[16;17H\033[1;31mSorry! \033[0mYou guessed wrong. The answer was \033[1;33m{}\033[0m".format(USACC[p]))
			score += 0
			sleep(2)
			tmp = sp.call('clear',shell=True)

	total = len(USA)
	divisor = score
	result = score / total * 100
	print("\033[2;17HYou have chosen the \u001b[1mU.S.A..\033[0m")
	print("\033[4;17HThere are %d States in the U.S.A.." % y)
	print("\033[6;17HLet's see how well you know your American geography.")
	print("\033[8;17HGOOD LUCK!")
	print("\033[10;35H*** U.S.A.***")
	print("\033[1;33m\033[12;10H*******************************************************************\033[0m")
	print("\033[14;16HYou got a {} out of {} correct for a total of {}%".format(score, total, (round(result))))
	sleep(2)
	if result == 100:
		with contextlib.redirect_stdout(None):
			with open('/home/cogiz/boxscore.txt', 'r') as f:
				data = f.readlines()
			print (data)
			print (data[0])
			data[3] = "U.S.A.               {}%\n".format(round(result))

		with open('/home/cogiz/boxscore.txt', 'w') as f:
			f.writelines( data )
			f.close()
	else:
		with contextlib.redirect_stdout(None):
			with open('/home/cogiz/boxscore.txt', 'r') as f:
				data = f.readlines()
			print (data)
			print (data[0])
			data[3] = "U.S.A.                {}%\n".format(round(result))

		with open('/home/cogiz/boxscore.txt', 'w') as f:
			f.writelines( data )
			f.close()

	menu_reset()

	tmp = sp.call('clear',shell=True)

def region_menu():
	tmp = sp.call('clear',shell=True)
	print("\033[2;32H*** REGIONS ***\n", "\033[4;31H1.  Canada\n", "\033[6;31H2.  U.S.A.\n", "\033[8;31H3.  Caribbean\n",
		  "\033[10;31H4.  Central America\n", "\033[12;31H5.  South America\n", "\033[14;31H6.  Asia\n", "\033[16;31H7.  Middle East\n",
		  "\033[18;31H8.  Europe\n", "\033[20;31H9.  Africa\n", "\033[22;30H10.  Australia\n")
	choice = input("\033[24;30HEnter Region #: ")
	print("\n\n")
	if choice == "1":
		tmp = sp.call('clear',shell=True)
		canada.main()
	if choice == "2":
		tmp = sp.call('clear',shell=True)
		main()
	if choice == "3":
		tmp = sp.call('clear',shell=True)
		caribbean.main()
	if choice == "4":
		tmp = sp.call('clear',shell=True)
		centralamerica.main()
	if choice == "5":
		tmp = sp.call('clear',shell=True)
		southamerica.main()
	if choice == "6":
		tmp = sp.call('clear',shell=True)
		asia.main()
	if choice == "7":
		tmp = sp.call('clear',shell=True)
		mideast.main()
	if choice == "8":
		tmp = sp.call('clear',shell=True)
		europe.main()
	if choice == "9":
		tmp = sp.call('clear',shell=True)
		africa.main()
	if choice == "10":
		tmp = sp.call('clear',shell=True)
		australia.main()

def menu_reset():
	choice = input("\033[18;16HPress [b] for Box Score or [r] for Region Menu: ")
	print("\n\n")
	if choice == "b":
		tmp = sp.call('clear',shell=True)
		os.system("cat /home/cogiz/boxscore.txt")
		choice2 = input("\033[25;0HPress [r] for Region Menu or [q] to quit: ")
		print("\n\n")
		if choice2 == "r":
			region_menu()
		if choice2 == "q":
			tmp = sp.call('clear',shell=True)
			print("\033[13;24HThanks for playing....Good Bye!")
			sleep(2)
			tmp =sp.call('clear',shell=True)
			sys.exit()

	if choice == "r":
		region_menu()

def titlecase(s):
    return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
                   lambda mo: mo.group(0)[0].upper() +
                             mo.group(0)[1:].lower(),
                   s)

if __name__ == '__main__':
	main()


"""singular value weather model prediction table

Revision ID: 2442f07d975c
Revises: f49418d95584
Create Date: 2023-09-26 16:14:01.658515

"""
from alembic import op
import sqlalchemy as sa
from app.db.models.common import TZTimeStamp

# revision identifiers, used by Alembic.
revision = '2442f07d975c'
down_revision = 'f49418d95584'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('model_run_predictions',
                    sa.Column('id', sa.Integer(), nullable=False),
                    sa.Column('prediction_model_run_timestamp_id', sa.Integer(), nullable=False),
                    sa.Column('prediction_timestamp', TZTimeStamp, nullable=False),
                    sa.Column('tmp_tgl_2', sa.Float(), nullable=True),
                    sa.Column('rh_tgl_2', sa.Float(), nullable=True),
                    sa.Column('apcp_sfc_0', sa.Float(), nullable=True),
                    sa.Column('wdir_tgl_10', sa.Float(), nullable=True),
                    sa.Column('wind_tgl_10', sa.Float(), nullable=True),
                    sa.ForeignKeyConstraint(['prediction_model_run_timestamp_id'], [
                                            'prediction_model_run_timestamps.id'], ),
                    sa.PrimaryKeyConstraint('id'),
                    sa.UniqueConstraint('prediction_model_run_timestamp_id', 'prediction_timestamp'),
                    comment='The prediction values of a particular model run.'
                    )
    op.create_index(op.f('ix_model_run_predictions_id'), 'model_run_predictions', ['id'], unique=False)
    op.create_index(op.f('ix_model_run_predictions_prediction_model_run_timestamp_id'),
                    'model_run_predictions', ['prediction_model_run_timestamp_id'], unique=False)
    op.create_index(op.f('ix_model_run_predictions_prediction_timestamp'),
                    'model_run_predictions', ['prediction_timestamp'], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_model_run_predictions_prediction_timestamp'), table_name='model_run_predictions')
    op.drop_index(op.f('ix_model_run_predictions_prediction_model_run_timestamp_id'),
                  table_name='model_run_predictions')
    op.drop_index(op.f('ix_model_run_predictions_id'), table_name='model_run_predictions')
    op.drop_table('model_run_predictions')
    # ### end Alembic commands ###


import sys
import os
from jsonHandler import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import functools

class CustomerDialog(QDialog):

    def __init__(self):
        super(CustomerDialog, self).__init__()
        self.createFormGroupBox()
        self.role = "Betreiber"
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        buttonBox.accepted.connect(self.accept)
        cancel = QPushButton("abbrechen")
        cancel.setIcon(QIcon(ICON_PATH+"cancel.png"))
        buttonBox.addButton(cancel, QDialogButtonBox.RejectRole)
        buttonBox.rejected.connect(self.reject)
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.formGroupBox)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)
        self.setWindowTitle("Prüfung der Richtlinien")
        self.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)

    def createFormGroupBox(self):
        self.formGroupBox = QGroupBox("Zuständigkeit:")
        layout = QFormLayout()
        self.combBox = QComboBox()
        self.combBox.addItems(["Betreiber", "Bevollmächtigter", "Händler", "Hersteller"])
        layout.addRow(QLabel("Zuständig als"), self.combBox)
        self.formGroupBox.setLayout(layout)

    def newAccept(self):
        self.role = self.combBox.currentText()
        self.accept()

    def getRole(self):
        return self.role


class Weather:
    location = ''
    conditions = {'clear': 'ясно', 'partly-cloudy': 'малооблачно', 'cloudy': 'облачно с прояснениями',
                  'overcast': 'пасмурно', 'drizzle': 'морось', 'light-rain': 'небольшой дождь', 'rain': 'дождь',
                  'moderate-rain': 'умеренно сильный дождь', 'heavy-rain': 'сильный дождь',
                  'continuous-heavy-rain': 'длительный сильный дождь', 'showers': 'ливень',
                  'wet-snow': 'дождь со снегом', 'light-snow': 'небольшой снег', 'snow': 'снег',
                  'snow-showers': 'снегопад', 'hail': 'град', 'thunderstorm': 'гроза',
                  'thunderstorm-with-rain': 'дождь с грозой', 'thunderstorm-with-hail': 'гроза с градом'}
    wind_dir = {'nw': 'северо-западный', 'n': 'северный', 'ne': 'северо-восточный', 'e': 'восточный',
                'se': 'юго-восточный', 's': 'южный', 'sw': 'юго-западный', 'w': 'западный', 'c': 'штиль'}

class Horo:
    zodiac = ''
    period = ''
    keys = {'aries': '♈ Овен', 'taurus': '♉ Телец', 'gemini': '♊ Близнецы', 'cancer': '♋ Рак', 'leo':  '♌ Лев',
            'virgo': '♍ Дева', 'libra': '♎ Весы', 'scorpio': '♏ Скорпион', 'sagittarius': '♐ Стрелец',
            'capricorn': '♐ Козерог', 'aquarius': '♒ Водолей', 'pisces': '♒ Рыбы'}

class Currency:
    currency = ''
    amount = 0
    currency_codes = {'AUD': 'A$ Австралийский доллар', 'AZN': '₼ Азербайджанский манат', 'GBP': '£ Фунт стерлингов',
                      'AMD': 'Դ Армянский драм', 'BYN': 'Br Белорусский рубль', 'BGN': 'лв Болгарский лев',
                      'BRL': 'R$ Бразильский реал', 'HUF': 'ƒ Венгерский форинт', 'KRW': '₩ Вона Республики Корея',
                      'HKD': 'HK$ Гонконгскй доллар', 'DKK': 'kr Датская крона', 'USD': '$ Доллар США', 'EUR': '€ Евро',
                      'INR': '₹ Индийская рупия', 'KZT': '₸ Казахстанский тенге', 'CAD': 'C$ Канадский доллар',
                      'KGS': 'с Киргизский сом', 'CNY': '¥ Китайский юань', 'MDL': 'L Молдавский лей',
                      'TMT': 'TMT Новый туркменский манат', 'NOK': 'kr Норвежская крона', 'PLN': 'zł Польский злотый',
                      'RON': 'lei Румынский лей', 'SGD': 'S$ Сингапурский доллар', 'TJS': 'SM Таджикский сомони',
                      'TRY': '₺ Турецкая лира', 'UZS': 'Soʻm Узбекский сум', 'UAH': '₴ Украинская гривна',
                      'CZK': 'Kč Чешская крона', 'SEK': 'kr Шведская крона', 'CHF': 'Fr. Швейцарский франк',
                      'ZAR': 'R Южноафриканский рэнд', 'JPY': '¥ Японская иена'}

def print_currency_codes():
    currency_codes = ''
    for k in Currency.currency_codes.keys():
        currency_codes += k + ': ' + Currency.currency_codes[k][Currency.currency_codes[k].find(' '):] + '\n'
    return currency_codes


import robotoc
from robotoc_sim import MPCSimulation, CameraSettings
from a1_simulator import A1Simulator
import numpy as np

jump_type = 'longitudinal'
# jump_type = 'lateral'
# jump_type = 'back'
# jump_type = 'rotational'

if jump_type == 'longitudinal':
    jump_length = [0.6, 0, 0]
    jump_yaw = 0
elif jump_type == 'lateral':
    jump_length = [0, 0.4, 0]
    jump_yaw = 0
elif jump_type == 'back':
    jump_length = [-0.3, 0, 0]
    jump_yaw = 0
elif jump_type == 'rotational':
    jump_length = [0.1, 0.0, 0]
    jump_yaw = np.pi / 4

model_info = robotoc.RobotModelInfo()
model_info.urdf_path = '../a1_description/urdf/a1.urdf'
model_info.base_joint_type = robotoc.BaseJointType.FloatingBase
baumgarte_time_step = 0.05
model_info.point_contacts = [robotoc.ContactModelInfo('FL_foot', baumgarte_time_step),
                             robotoc.ContactModelInfo('RL_foot', baumgarte_time_step),
                             robotoc.ContactModelInfo('FR_foot', baumgarte_time_step),
                             robotoc.ContactModelInfo('RR_foot', baumgarte_time_step)]
robot = robotoc.Robot(model_info)

T = 0.8
N = 20
mpc = robotoc.MPCJump(robot, T, N)

planner = robotoc.JumpFootStepPlanner(robot)
planner.set_jump_pattern(jump_length, jump_yaw)
mpc.set_jump_pattern(planner, flying_time=0.3, min_flying_time=0.2,
                     ground_time=0.3, min_ground_time=0.2)

t0 = 0.0
q0 = np.array([0, 0, 0.3181, 0, 0, 0, 1,
               0.0,  0.67, -1.3,
               0.0,  0.67, -1.3,
               0.0,  0.67, -1.3,
               0.0,  0.67, -1.3])
v0 = np.zeros(robot.dimv())
option_init = robotoc.SolverOptions()
option_init.max_iter = 100
option_init.initial_sto_reg_iter = 100
option_init.nthreads = 4
mpc.init(t0, q0, v0, option_init, sto=(jump_type=='longitudinal'))

option_mpc = robotoc.SolverOptions()
option_mpc.max_iter = 2 # MPC iterations
option_mpc.initial_sto_reg_iter = 0
option_mpc.max_dt_mesh = T / N
option_mpc.nthreads = 4
mpc.set_solver_options(option_mpc)

time_step = 0.0025 # 400 Hz MPC
a1_simulator = A1Simulator(urdf_path=model_info.urdf_path, time_step=time_step)
if jump_type == 'longitudinal':
    camera_settings = CameraSettings(2.0, 35,  -0, q0[0:3]+np.array([-0.1, 0.5, 0.]))
elif jump_type == 'lateral':
    camera_settings = CameraSettings(2.0, 55,  -0, q0[0:3]+np.array([-0.1, 0.5, 0.]))
elif jump_type == 'back':
    camera_settings = CameraSettings(1.5, 20,  -0, q0[0:3]+np.array([-0.4, 0.3, 0.]))
elif jump_type == 'rotational':
    camera_settings = CameraSettings(2.0, 45, -10, q0[0:3]+np.array([-0.1, 0.5, 0.]))
a1_simulator.set_camera_settings(camera_settings=camera_settings)

simulation_time = 5.0
log = False
record = False
simulation = MPCSimulation(simulator=a1_simulator)
simulation.run(mpc=mpc, t0=t0, q0=q0, simulation_time=simulation_time,
               feedback_delay=True, verbose=False,
               record=record, log=log, name='a1_jump')

if record:
    robotoc.utils.adjust_video_duration(simulation.name+'.mp4',
                                        desired_duration_sec=simulation_time)

if log:
    q_log = np.genfromtxt(simulation.q_log)
    v_log = np.genfromtxt(simulation.v_log)
    t_log = np.genfromtxt(simulation.t_log)
    sim_steps = t_log.shape[0]

    vcom_log = []
    wcom_log = []
    for i in range(sim_steps):
        R = robotoc.utils.rotation_matrix_from_quaternion(q_log[i][3:7])
        robot.forward_kinematics(q_log[i], v_log[i])
        vcom_log.append(R.T@robot.com_velocity()) # robot.com_velocity() is expressed in the world coordinate
        wcom_log.append(v_log[i][3:6])

    plot_mpc = robotoc.utils.PlotCoMVelocity()
    plot_mpc.plot(t_log, vcom_log, wcom_log,
                  fig_name=simulation.name+'_com_vel')


from typing import List, Optional

from overrides import overrides
from torch import nn

from archai.discrete_search.api.archai_model import ArchaiModel
from archai.discrete_search.api.model_evaluator import ModelEvaluator

class NonEmbeddingParamsProxy(ModelEvaluator):
    """Total number of non-embedding parameters."""

    def __init__(self, exclude_cls: Optional[List[nn.Module]] = None, trainable_only: Optional[bool] = True) -> None:
        """Initialize the evaluator.

        Used as a proxy for the perplexity of decoder-only transformer LMs.

        Args:
            exclude_cls: List of PyTorch module classes to exclude from parameter counting.
                If `None`, defaults to `[torch.nn.Embedding]`.
            trainable_only: Whether only trainable parameters should be counted.

        Reference:
            "LiteTransformerSearch: Training-free Neural Architecture Search for
                Efficient Language Models", Javaheripi et. al, 2022

        """

        self.exclude_cls = exclude_cls or [nn.Embedding]
        self.trainable_only = trainable_only

    @overrides
    def evaluate(self, model: ArchaiModel, budget: Optional[float] = None) -> float:
        total_params = sum(
            param.numel() for param in model.arch.parameters() if not self.trainable_only or param.requires_grad
        )

        embed_params = sum(
            sum(param.numel() for param in module.parameters())
            for module in model.arch.modules()
            if isinstance(module, tuple(self.exclude_cls))
        )

        return total_params - embed_params