#!/usr/bin/env python

import pandas as pd
from collections import defaultdict

import argparse

def bowtie2bed(fn, fo):
    """
    From a bowtie output (tsv, NOT sam) file, return a BED file.

    :param fn: string
        name of bowtie default output tsv file
    :param fo: string
        name of bedfile output to write
    :return:
    """
    bowtie_headers = [
        "read_name", "strand", "chrom", "start", "seq", "ascii_score", "alt_align", "mismatches"
    ]
    df = pd.read_csv(fn, names=bowtie_headers, sep="\t")
    df['len'] = df['seq'].apply(lambda x: len(x))
    df['read_name_fixed'] = df['read_name'].apply(lambda x: x.split("_")[0].split('#')[:-1])
    df['end'] =  df['start'] + df['len']
    df = df[['chrom','start','end','read_name_fixed','alt_align','strand']]
    df.to_csv(fo, sep="\t", header=False, index=False)

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--in_file",
        required=True,
    )
    parser.add_argument(
        "--out_file",
        required=True,
    )

    # Process arguments
    args = parser.parse_args()
    out_file = args.out_file
    in_file = args.in_file

    # main func
    bowtie2bed(
        fn=in_file,
        fo=out_file
    )

if __name__ == "__main__":
    main()


import datetime

categories = ['INACTIVE', 'WEB', 'AUDIO', 'VIDEO', 'GAMING']

inp = raw_input("Clear? Y/N\n")

if inp in ["y", "Y"]:
	with open('log.txt', 'w') as f:
		f.write("")

while True:
	for i, c in enumerate(categories):
		print("{}: {}".format(i, c))
	cat = raw_input()
	print("\n")
	time = datetime.datetime.now()
	with open('log.txt', 'a') as f:
		f.write(str(time) + '\n' + str(cat) + '\n')


# -*- coding: utf-8 -*-
"""
This is a prototype script.
"""
import numpy as np
from PIL import Image
from PIL import ImageEnhance
from scipy.ndimage import gaussian_filter
import cv2
from skimage import io as ip

frame_rate = 24 #output frame rate

vidcap = cv2.VideoCapture('video9.mov')
success,image = vidcap.read()
count = 1
print('Demuxing video')
while success:
  cv2.imwrite("frame%d.png" % count, image)     # save frame as JPEG file
  success,image = vidcap.read()
  count += 1

def initial_processing(iminit, low_val, max_val):
    img = Image.open(iminit)
    converter = ImageEnhance.Contrast(img)
    print(low_val)
    print(max_val)
    cont = (1/(max_val/low_val))*2.0
    img = converter.enhance(cont)
    array = np.array(img)
    ip.imsave('temp1.png', array)

def calc_val(im1):
    img = Image.open(im1)
    array = np.array(img)
    low_val = np.mean(array)
    max_val = np.amax(array)
    return low_val, max_val

def imadd(I, K):

    import numbers
    if isinstance(K, numbers.Number):
        J = I.astype('int32')
        J += K
    elif isinstance(K, np.ndarray):
        assert K.shape == I.shape, f'Cannot add images with sizes {I.shape} and {K.shape}.'
        J = I.astype('int32') + K.astype('int32')
    else:
        raise TypeError('K must be a number or an array.')

    np.clip(J, 0, 255, out=J)
    J = J.astype('uint8')
    return J

def gaussian_filt(I, sigma, pad=0):

    import numbers
    assert isinstance(pad, numbers.Number) or pad in ['reflect', 'nearest', 'wrap'], \
            'Choose a correct value for pad: a number (0-255), ''reflect'', ''nearest'', or ''wrap''.'

    if isinstance(pad, numbers.Number):
        md = 'constant'
        c = pad
    else:
        md = pad
        c = 0
    return gaussian_filter(I, sigma, mode=md, cval=c)

def final_processing(finalim, k):
    I = ip.imread(finalim)

    R = np.logical_and(I[:, :, 0] > 254, I[:, :, 1] < 255)

    new_R = gaussian_filt(255 * R, 5)

    J = I.copy()
    J[:, :, 0] = imadd(new_R, J[:, :, 0])

    ip.imsave('temp.png', J)
    img2 = Image.open('temp.png')
    converter = ImageEnhance.Color(img2)
    img2 = converter.enhance(1.4)
    im = np.array(img2)
    ip.imsave('final{}.png'.format(k), im)

def process_loop():
    for i in range(count):
        low_val, max_val=calc_val('frame{}.png'.format(i+1))
        print('Processing image {}'.format(i+1))
        initial_processing('frame{}.png'.format(i+1), low_val, max_val)
        final_processing('temp1.png', i+1)

def video_mux():
    print("Remuxing Files")
    pathOut = 'video_out.mp4'
    fps = frame_rate
    frame_array = []
    files = ['final{}.png'.format(i+1) for i in range(count)]
    for i in range(len(files)):
        #filename=pathIn + files[i]
        filename=files[i]
        #reading each files
        img = cv2.imread(filename)
        height, width, layers = img.shape
        size = (width,height)
        #inserting the frames into an image array
        frame_array.append(img)
    out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'H264'), fps, size)
    for i in range(len(frame_array)):
        # writing to a image array
        out.write(frame_array[i])
    out.release()
count = count-1
process_loop()
video_mux()


from pymongo import MongoClient

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def hello():
    new_list = []
    client = MongoClient()
    db = client.variables
    variables = db.variables
    cursor = variables.find({})
    # print(variables)
    for doc in cursor:
        message = ''
        symbol = doc['symbol']
        fiveMinSuccess =  doc['values']["5MIN"]['success']
        fiveMinBlackX =  doc['values']["5MIN"]['black_x']
        fiveMinPrice =  doc['values']["5MIN"]['price']
        fiveMinMa =  doc['values']["5MIN"]['ma']

        fifteenMinSuccess = doc['values']["15MIN"]['success']
        fifteenMinBlackX = doc['values']["15MIN"]['black_x']
        fifteenMinPrice =  doc['values']["15MIN"]['price']
        fifteenMinMa =  doc['values']["15MIN"]['ma']

        oneHourSuccess = doc['values']["1HRS"]['success']
        oneHourBlackX = doc['values']["1HRS"]['black_x']
        oneHourPrice =  doc['values']["1HRS"]['price']
        oneHourMa =  doc['values']["1HRS"]['ma']

        fourHourSuccess = doc['values']["4HRS"]['success']
        fourHourBlackX = doc['values']["4HRS"]['black_x']
        fourHourPrice =  doc['values']["4HRS"]['price']
        fourHourMa =  doc['values']["4HRS"]['ma']

        oneDaySuccess = doc['values']["1DAY"]['success']
        oneDayBlackX = doc['values']["1DAY"]['black_x']
        oneDayPrice =  doc['values']["1DAY"]['price']
        oneDayMa =  doc['values']["1DAY"]['ma']

        new_dict = {"symbol": symbol, "fiveMin": f"{fiveMinSuccess}/{fiveMinBlackX}     {calculate_difference(fiveMinPrice, fiveMinMa)}", "fifteenMin": f"{fifteenMinSuccess}/{fifteenMinBlackX}  {calculate_difference(fifteenMinPrice, fifteenMinMa)}", "oneHour": f"{oneHourSuccess}/{oneHourBlackX}    {calculate_difference(oneHourPrice, oneHourMa)}", "fourHour": f"{fourHourSuccess}/{fourHourBlackX}   {calculate_difference(fourHourPrice, fourHourMa)}", "oneDay": f"{oneDaySuccess}/{oneDayBlackX}    {calculate_difference(oneDayPrice, oneDayMa)}"}
        new_list.append(new_dict)
        print(new_list)
    return jsonify(new_list)

def calculate_difference(price, ma) -> str:
    up = '↗'
    down = '↘'
    if price > ma:
        return up
    return down

app.run(debug=True)


#!/usr/bin/env python3
#encoding: UTF-8

# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
import numpy as np
import matplotlib.pyplot as plt
import math
import TrashCan.Mathieson as mat

import C.PyCWrapper as PCWrap
import Util.plot as uPlt
import Util.dataTools as tUtil

def vErf(x):
    y = np.zeros( x.shape )
    for i in range( x.shape[0]):
        y[i] = math.erf( x[i] )
    return y

def computeGaussian1D( x,  mu=0.0, var=1.0):
    # print ( "???", __name__, x[-1], x.shape )
    # print "x", x
    TwoPi = 2 * np.pi
    SqrtTwoPi = np.sqrt( TwoPi )
    sig = np.sqrt(var)
    u = (x - mu) / sig
    # print "u", u
    u = - 0.5 * u * u
    cst = 1.0 / ( sig * SqrtTwoPi)
    y = cst * np.exp( u )
    return y

def gaussianIntegral(x):
    mu0 = 0.0
    var0 = 1.0
    sig0 = np.sqrt( var0 )
    cstx = 1.0 / ( np.sqrt(2.0)*sig0 )
    integral = vErf( (x - mu0) * cstx )
    return integral

class TabulatedChargeIntegration:

  # Spline implementation of the book "Numerical Analysis" - 9th edition
  # Richard L Burden, J Douglas Faires
  # Section 3.5, p. 146
  # Restrictions : planed with a regular sampling (dx = cst)
  # spline(x) :[-inf, +inf] -> [-1/2, +1/2]
  # Error < 7.0 e-11 for 1001 sampling between [0, 3.0]
  def __init__(self, x, f, dx, lDerivate, rDerivate ):
    self.nTabulations = x.size
    N = x.size
    self.a = np.copy( f )
    self.b = np.zeros(N)
    self.c = np.zeros(N)
    self.d = np.zeros(N)
    self.dx = dx

    # Step 1
    # for (i = 0; i < n - 1; ++i) h[i] = x[i + 1] - x[i];
    #for i in range(0, N-1):
    #  self.h[i] = x[i+1] - x[i];
    # h = x[0:N-1] = x[1:N] - x[0:N-1]
    h = self.dx

    # Step 2
    # for (i = 1; i < n-1; ++i)
    #    A[i] = 3 * (a[i + 1] - a[i]) / h[i] - 3 * (a[i] - a[i - 1]) / h[i - 1];
    # A[1:N-1] = 3 * (a[2:N] - a[1:N-1]) / h[1:N-1]  -  3 * (a[1:N-1] - a[0:N-2]) / h[0:N-2]];

    # Step 2 & 3
    alpha = np.zeros(N)
    # alpha[0] = 3.0 / self.h[0] * (f[1] - f[0]) - 3*lDerivate
    alpha[0] = 3.0 / h * (f[1] - f[0]) - 3*lDerivate
    # alpha[N-1] =  3*rDerivate - 3.0 / self.h[N-2] * (f[N-1] - f[N-2])
    alpha[N-1] =  3*rDerivate - 3.0 / h * (f[N-1] - f[N-2])
    # for (i = 1; i < n-1; ++i)
    for i in range(1, N-1):
      # alpha[i] = 3.0/self.h[i] * (f[i+1] - f[i]) - 3.0/self.h[i-1] * (f[i] - f[i-1]);
      alpha[i] = 3.0/h * (f[i+1] - f[i]) - 3.0/h * (f[i] - f[i-1]);

    # Step 4 to 6 solve a tridiagonal linear system

    # Step 4
    l = np.zeros(N)
    mu = np.zeros(N)
    z = np.zeros(N)
    # l[0] = 2 * self.h[0]
    l[0] = 2 * h
    mu[0] = 0.5
    z[0] = alpha[0] / l[0]

    # Step 5
    # for (i = 1; i < n - 1; ++i) {
    for i in range(1, N-1):
      # l[i] = 2 * (x[i+1] - x[i-1]) - self.h[i-1] * mu[i - 1];
      # mu[i] = self.h[i] / l[i];
      # z[i] = (alpha[i] - self.h[i-1]*z[i-1]) / l[i];
      l[i] = 2 * (x[i+1] - x[i-1]) - h * mu[i-1];
      mu[i] = h / l[i];
      z[i] = (alpha[i] - h*z[i-1]) / l[i];

    # Step 6 & 7
    # l[N-1] = self.h[N-2]*(2.0-mu[N-2])
    # z[N-1] = (alpha[N-1] - self.h[N-2]*z[N-2]) / l[N-1]
    l[N-1] = h*(2.0-mu[N-2])
    z[N-1] = (alpha[N-1] - h*z[N-2]) / l[N-1]

    self.c[N-1] = z[N-1]
    # for (j = n - 2; j >= 0; --j) {
    for j in range(N-2, -1, -1):
      self.c[j] = z[j] - mu[j] * self.c[j+1]
      # self.b[j] = (f[j+1]-f[j]) / self.h[j] - self.h[j]/3.0 * (self.c[j+1] + 2*self.c[j])
      # self.d[j] = (self.c[j+1]-self.c[j]) / (3 * self.h[j])
      self.b[j] = (f[j+1]-f[j]) / h - h/3.0 * (self.c[j+1] + 2*self.c[j])
      self.d[j] = (self.c[j+1]-self.c[j]) / (3 * h)

  def splineAtanTanh( self, x ):
      a = self.a
      b = self.b
      c = self.c
      d = self.d
      N = self.nTabulations

      signX = np.where( x >= 0, 1.0, -1.0 )
      # unsigned x
      uX = x * signX
      # 0.49999999724624
      # 0.499999996965014 point precedent f0(2OO-1)
      # 0.49999999724624 f0(200)
      # 0.499999997245073 f(200-1)
      # 0.499999997232819 y[200-1]
      # 0.49999999748923 y[200]
      # 0.       890
      # 0.49999999724624 f0(200)
      np.set_printoptions(precision=15)
      # print("???  x / self.dx", x / self.dx)
      cst = 1.0 / self.dx
      u = np.trunc( uX * cst + self.dx*0.1)
      # idx = u.astype(np.int)
      idx = np.int32(u)
      # print("??? idx ", idx)
      idx = np.where( idx >= N, N-1, idx)
      h = np.where( idx < N-1, uX - idx * self.dx, 0)
      # h = x - idx * self.dx
      # print("??? idx filter large indexes", idx)

      print ("uX ",  uX)
      print ("h ",  h)
      print ("f(x0) ",  a[idx])
      print ("df|dx0",  h*( b[idx] + h*( c[idx] + h *(d[idx]))))
      print ("f, ",  a[idx] + h*( b[idx] + h*( c[idx] + h *(d[idx]))))
      f = signX * (a[idx] + h*( b[idx] + h*( c[idx] + h *(d[idx]))))
      return f

if __name__ == "__main__":

    #pcWrap = PCWrap.setupPyCWrapper()
    #pcWrap.initMathieson()

    xPrecision = 1.0e-3
    xLimit = 3.0
    N = int(xLimit / xPrecision) + 1
    x = np.linspace(0.0, xLimit, N)
    dxVar = x[1:] - x[0:-1]
    print("Verify sampling N, xPrecision, dxMin, dxMax", N, xPrecision, np.min(dxVar), np.max(dxVar))
    dx = xPrecision
    mat0 = mat.Mathieson( 0, 1.0 )
    leftDerivate = 2.0 * mat0.curK4x * mat0.curSqrtK3x * mat0.curK2x * mat0.curInvPitch
    print("leftDerivate", leftDerivate)
    # leftDerivate = 2.77
    y = mat0.computeAtanTanh( x)
    tf = TabulatedChargeIntegration(x, y, dx, leftDerivate, 0.0)

    """
    m = int( N/2 )
    print("N", N, x.size )
    print("x ", x[0], x[1], x[2], '...', x[m-1], x[m], x[m+1], "...", x[-3], x[-2], x[-1] )
    print("\n")
    print("maxErr", np.max(np.abs(f-y)) )
    """

    fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(10, 7))
    # Spline at sampling points
    f = tf.splineAtanTanh(x)
    ax[0,0].plot( x, y)
    ax[0,0].scatter( x, f, marker='x', color="red")
    # , markersize=4)
    ax[0,0].set_ylabel( "atan(tanh(x0)) and spline(x0) [in red]")
    #
    ax[0,1].scatter( x, f-y, marker='x')
    ax[0,1].set_ylabel( "atan(tanh(x0)) - spline(x0)")

    # Far away points
    print("--------------------")
    x1 = x + 0.0095
    y1 = mat0.computeAtanTanh( x1)
    f1 = tf.splineAtanTanh(x1)
    print("y1", y1)
    ax[1,0].scatter( x1, f1-y1, marker='x')
    ax[1,0].set_ylabel( "atan(tanh(x1)) - spline(x1)")
    print("--------------------")
    # RND
    xrnd = (np.random.ranf(20*N) * 2  - 1.0) * (xLimit + 1.0)
    frnd = tf.splineAtanTanh(xrnd)
    yrnd = mat0.computeAtanTanh(xrnd)
    #
    ax[1,1].scatter( xrnd, frnd-yrnd, marker='x')
    ax[1,1].set_ylabel( "atan(tanh(rnd)) - spline(rnd)")
    # relative error
    # ax[1,1].scatter( x1[1:], (f1[1:]-y1[1:]) / y1[1:] )
    #
    print("maxErr f1", np.max(np.abs(f1-y1)) )
    print( "convergence last point y, dy ",  y1[-1], np.max(np.abs(f1[-1]-y1[-1])))
    np.set_printoptions(precision=15)
    print( "f(x) x=[0, ..,9]", mat0.computeAtanTanh( np.arange(10.0)) - 0.5 )

    print("FIRST POINT")
    tf.splineAtanTanh( np.array([0.0]) )
    print("Function",  mat0.computeAtanTanh( np.array([0.0])) )
    print("Last POINT")
    tf.splineAtanTanh( np.array([2.0]) )
    print("Function",  mat0.computeAtanTanh( np.array([2.0])) )
    print("Outer POINT")
    tf.splineAtanTanh( np.array([15.0]) )
    print("Function",  mat0.computeAtanTanh( np.array([15.0])) )

    xx = np.arange(6.0)
    print("xx",  xx )
    print("f(xx) - 0.5",  mat0.computeAtanTanh( xx ) - 0.5)

    plt.show()


import sqlite3
conn=sqlite3.connect("Stationary_inventt.db")
c = conn.cursor()
print(" database successful")
#using drop table to avoid duplicate copy
c.execute("DROP TABLE  IF EXISTS Stationery_stock")
c.execute("""
CREATE TABLE Stationery_stock(
ITEM_ID INTEGER,
ITEMS TEXT,
COST_PRICE INTEGER,
QUANTITY_IN_STOCK INTEGER
)
""")
print("table created successfully")
Avail_items = [
(1,"2b 60 leaves bks",600,10),
(2,"Staple pin",800,5),
(3,"Gum",1000,15),
(4,"Pencils",500,30),
(5,"A4 paper",5000,7),
(6,"Flexible Ruler",1500,22),
(7,"set square",4000,5),
(8,"Math set",2500,3),
(9,"Eraser",750,8),
(10,"Calculator",3000,10)
]
c.executemany("INSERT INTO Stationery_stock VALUES(?,?,?,?)",Avail_items)
#amount the business owner invested in the procurement of the items.
c.execute("SELECT SUM(COST_PRICE) FROM Stationery_stock" )
print(c.fetchall())
# average quantity of items in stock.
c.execute("SELECT AVG(QUANTITY_IN_STOCK) FROM Stationery_stock")
print(c.fetchall())
#item with the least quantity in stock
c.execute("SELECT ITEMS, MIN(QUANTITY_IN_STOCK) FROM Stationery_stock")
print(c.fetchall())
# item with the most quantity in stock
c.execute("SELECT ITEMS,MAX(QUANTITY_IN_STOCK) FROM Stationery_stock")
print(c.fetchall())

conn.commit()
conn.close()


import cinn
import numpy as np
import time
from cinn import runtime

# from PIL import Image

# def getimg(fname):

#     image=Image.open(fname)
#     image= np.array(image)
#     return image

# print(getimg("/root/RemoteWorking/huazhibin.webp"))

def randomImgNCHW(w,h,c=3,n=1):
    return np.random.randint(0,255,(n,c,h,w))

def runCinn(C,args,n="matmul"):
    stages = cinn.create_stages([C])

    target = cinn.Target()
    builder = cinn.Module.Builder(n, target)

    func = cinn.lower(n, stages, [A.to_tensor(), B.to_tensor(), C])

    print(func)

    builder.add_function(func)
    module = builder.build()

    jit = cinn.ExecutionEngine()
    jit.link(module)

    exefn = jit.lookup(n)
    exefn(args)

m = cinn.Expr(4)
n = cinn.Expr(3)
k = cinn.Expr(2)

A = cinn.Placeholder("float32", "A", [m, k])
B = cinn.Placeholder("float32", "B", [k, n])

C = cinn.compute([
    m, n
], lambda v: A(v[0],v[1]) + B(v[0],v[1]),  "C")

a = runtime.cinn_buffer_t(

    np.arange(1,m.int()*k.int()+1).reshape(m.int(), k.int()).astype("float32"),

    runtime.cinn_x86_device)

b = runtime.cinn_buffer_t(
    np.arange(1,k.int()*n.int()+1).reshape(k.int(), n.int()).astype("float32"),
    runtime.cinn_x86_device)

c = runtime.cinn_buffer_t(
    np.zeros([m.int(), n.int()]).astype("float32"), runtime.cinn_x86_device)

args = [runtime.cinn_pod_value_t(_) for _ in [a, b, c]]

runCinn(C,args)

npa = a.numpy()
npb = b.numpy()
npc = c.numpy().astype("int32")

npr =np.random.randint(0,255,(6,8,3))

# print("a:",npa,npa.shape)
# print("b:",npb,npb.shape)
# print("c:",npc,npc.shape)

# print("npr:",npr)

t = randomImgNCHW(8,6)

print("npr-transpose:",t)


import uvicorn
import datetime
from loguru import logger
from fastapi import FastAPI
from sqlalchemy import select
from fastapi.middleware.cors import CORSMiddleware

from SAGIRIBOT.ORM.AsyncORM import orm
from SAGIRIBOT.Core.AppCore import AppCore
from SAGIRIBOT.command_parse.Commands import *
from SAGIRIBOT.ORM.AsyncORM import Setting, FunctionCalledRecord

app = FastAPI(docs_url=None, redoc_url=None)

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get('/getGroups')
async def getGroups():
    groups = await orm.fetchall(select(Setting.group_id, Setting.group_name).where(Setting.active == True))
    return [{"value": group[0], "label": group[1]} for group in groups]

@app.get('/getGroupSetting')
async def getGroupSetting(groupId: int):
    options_bool = ["repeat", "frequency_limit", "setu", "real", "real_high_quality", "bizhi", "r18", "img_search",
                    "bangumi_search", "debug", "compile", "anti_revoke", "online_notice", "switch"]
    options_str = ["long_text_type", "r18_process", "speak_mode", "music"]
    valid_str_option_value = {
        "long_text_type": LongTextType.valid_values,
        "r18_process": R18Process.valid_values,
        "speak_mode": SpeakMode.valid_values,
        "music": Music.valid_values
    }
    bool_result = await orm.fetchone(select(
        Setting.repeat,
        Setting.frequency_limit,
        Setting.setu, Setting.real, Setting.real_high_quality, Setting.bizhi, Setting.r18,
        Setting.img_search,
        Setting.bangumi_search,
        Setting.debug,
        Setting.compile,
        Setting.anti_revoke,
        Setting.online_notice,
        Setting.switch
    ).where(
        Setting.group_id == groupId
    ))
    str_result = await orm.fetchone(select(
        Setting.long_text_type,
        Setting.r18_process,
        Setting.speak_mode,
        Setting.music
    ).where(
        Setting.group_id == groupId
    ))
    return [
        [{"label": options_bool[i], "value": bool_result[i]} for i in range(len(bool_result))],
        [{"label": options_str[i], "value": str_result[i], "validValue": valid_str_option_value[options_str[i]]} for i in range(len(str_result))]
    ]

@app.get('/modifyGroupSetting')
async def modifyGroupSetting(groupId: int, settingName: str, newValue):
    if newValue in ["true", "false"]:
        newValue = True if newValue == "true" else False
    try:
        await orm.update(
            Setting,
            [Setting.group_id == groupId],
            {"group_id": groupId, settingName: newValue}
        )
    except Exception as e:
        logger.error(f"api error: {e}")
        return False
    return True

@app.get("/getStatus")
async def getStatus():
    return {
        "functionCalled": len(await orm.fetchall(
            select(FunctionCalledRecord).where(FunctionCalledRecord.time >= datetime.date.today())
        )),
        "handlerCount": len(AppCore.get_core_instance().get_group_chains()),
        "sayaCount": len(AppCore.get_core_instance().get_saya_channels())
    }

def run_api():
    uvicorn.run(app, host="127.0.0.1", port=8000, log_level="error")


import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel
from PyQt6.QtGui import QPixmap, QFont

class MainWindow(QWidget):
    def __init__(self):
        """constructor for Empty windows """
        super().__init__()
        self.initializeUI()

    def initializeUI(self):
        """Set up the application"""
        # setGeometry()两个参数用于指定窗口显示的位置, 后两个参数用于指定窗口大小
        self.setGeometry(500, 500, 250, 400)
        self.setWindowTitle("User profile")

        self.setupMainWindow()
        self.show()
    def creatImageLabels(self):
        """Create Qlabel to be displayed in the main windows"""
        skyblue_path = '../Beginning-PyQt-resource/Chapter02/images/skyblue.png'
        try:
            with open(skyblue_path):
                skyblue = QLabel(self)
                pixmap = QPixmap(skyblue_path)
                skyblue.setPixmap(pixmap)
        except FileNotFoundError as error:
            print(f"Image not found. \nError: {error}")
        profile_path = '../Beginning-PyQt-resource/Chapter02/images/profile_image.png'
        try:
            with open(profile_path):
                profile = QLabel(self)
                pixmap = QPixmap(profile_path)
                profile.setPixmap(pixmap)
                profile.move(80, 20)
        except FileNotFoundError as error:
            print(f"Image not found. \nError: {error}")

    def setupMainWindow(self):
        self.creatImageLabels()

        user_label = QLabel(self)
        user_label.setText("John Doe")
        user_label.setFont(QFont("Arial", 20))
        user_label.move(85, 140)

        bio_label = QLabel(self)
        bio_label.setText("Biography")
        bio_label.setFont(QFont("Arial", 17))
        bio_label.move(15, 170)

        about_label = QLabel(self)
        about_label.setText("I'm a software Engineer with 10 years\
                            exprience creating awesome code!")
        about_label.setWordWrap(True)   # set auto line
        about_label.move(15, 190)
# Run the program
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())


# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, models, _
_logger = logging.getLogger(__name__)

class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    @api.multi
    def action_auto_open(self):
        return_item = super(AccountInvoice, self).action_auto_open()
        # action_send_account_invoice_create_message_slack
        for item in self:
            item.action_send_account_invoice_create_message_slack()
        # return
        return return_item

    @api.multi
    def action_send_account_invoice_create_message_slack(self):
        self.ensure_one()
        web_base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        url_item = '%s/web?#id=%s&view_type=form&model=account.invoice' % (
            web_base_url,
            self.id
        )
        attachments = [
            {
                "title": _('Invoice has been created automatically'),
                "text": self.number,
                "color": "#36a64f",
                "fallback": "View invoice %s %s" % (
                    self.number,
                    url_item
                ),
                "actions": [
                    {
                        "type": "button",
                        "text": _("View invoice %s") % self.number,
                        "url": url_item
                    }
                ],
                "fields": [
                    {
                        "title": _("Customer"),
                        "value": self.partner_id.name,
                        'short': True,
                    },
                    {
                        "title": _("Origin"),
                        "value": self.origin,
                        'short': True,
                    }
                ],
            }
        ]
        vals = {
            'attachments': attachments,
            'model': 'account.invoice',
            'res_id': self.id,
            'channel': self.env['ir.config_parameter'].sudo().get_param(
                'slack_log_contabilidad_channel'
            ),
        }
        self.env['slack.message'].sudo().create(vals)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Sources of authentication from the request.

Each source is a :func:`callable`.
The source is called with the request and returns ``None`` if it cannot extract informations
or a dict with the values it has got.
The first source returning a non ``None`` value is used for the providers.
"""

import urlparse

from napixd.http.response import HTTPError

class CatchAllSource(object):
    def __call__(self, request):
        return {
            'is_secure': False
        }

class SecureAuthProtocol(object):
    """
    Implements the secure-auth provider.

    The *Authorization* header of the requests is checked.
    """
    def __init__(self):
        self._mandatory = frozenset(['path', 'host', 'method'])

    def __call__(self, request):
        if 'Authorization' not in request.headers:
            return None

        msg, l, signature = request.headers['Authorization'].rpartition(':')
        if l != ':':
            return None

        content = urlparse.parse_qs(msg)
        for x in content:
            content[x] = content[x][0]

        missing_keys = self._mandatory.difference(content)
        if missing_keys:
            raise HTTPError(403, 'Missing authentication data: {0}'.format(
                ', '.join(missing_keys)))

        content.update({
            'msg': msg,
            'signature': signature,
        })
        return content

class NonSecureAuthProtocol(object):
    """
    Implements the Non-secure authentication protocol.

    A token in the GET parameters is checked.
    """
    @classmethod
    def from_settings(cls, settings):
        token = settings.get('get_parameter', 'token')
        return cls(token)

    def __init__(self, token):
        self.token = token

    def __call__(self, request):
        if self.token not in request.GET:
            return None
        login, l, signature = request.GET[self.token].partition(':')
        if l != ':':
            raise HTTPError(401, 'Incorrect NAPIX non-secure Authentication')
        return {
            'login': login,
            'signature': signature,
            'msg': login,
            'is_secure': False
        }


"""
Sample Input:

Enter rotational copies: 5
Enter sides per polygon: 4
Enter edge pixel length: 100
Enter row range start: -200
Enter row range end: 200
Enter row range increment: 400
Enter col range start: -250
Enter col range end: 250
Enter col range increment: 250
"""
import turtle
import random

def draw_polygon(t,spp,epl):
    for j in range(spp):
        t.forward(epl)
        t.left(360/spp)

def draw_rotational_polygons(t,spp,epl,rc):
    for i in range(rc):
        draw_polygon(t,spp,epl)
        t.left(360/rc)

def draw_full_shape(t,spp,epl,rc):
    epl2 = epl
    while epl2 > 1:
        t.pensize(5)
        t.color(1,1,1)
        draw_rotational_polygons(t,spp,epl2,rc)
        epl2 = ((epl2)/2)

    epl2 = epl
    while epl2 > 1:
        t.pensize(1)
        t.color(0,0,0)
        draw_rotational_polygons(t,spp,epl2,rc)
        epl2 = ((epl2)/2)

def draw_grids(t,spp,epl,rc,rrs,rre,rri,crs,cre,cri):
    rows = int((rre - rrs)/rri)+1
    columns = int((cre - crs)/cri)+1
    col=crs
    row=rrs

    for y in range(rows):
        for x in range(columns):
            t.penup()
            t.goto(col,row)
            t.pendown()
            draw_full_shape(t,spp,epl,rc)
            col = col+cri
        col = crs
        row = row+rri

def main():
    background_red = 0
    background_green = 0
    background_blue = 0

    while background_red == 0 and background_green == 0 and background_blue == 0:
        background_red = random.choice([0.0,0.125,0.25,0.375,0.5])
        background_green = random.choice([0.0,0.125,0.25,0.375,0.5])
        background_blue = random.choice([0.0,0.125,0.25,0.375,0.5])

    print("Random background color is: (", background_red, ",", background_green, ",", background_blue, ")")

    wn = turtle.Screen()
    wn.bgcolor(background_red, background_green, background_blue)

    murtle = turtle.Turtle()
    murtle.hideturtle()
    murtle.speed(0)

    rotational_copies = int(input("Enter rotational copies: "))
    sides_per_polygon = int(input("Enter sides per polygon: "))
    edge_pixel_length = int(input("Enter edge pixel length: "))

    row_range_start = int(input("Enter row range start: "))
    row_range_end = int(input("Enter row range end: "))
    row_range_increment = int(input("Enter row range increment: "))
    col_range_start = int(input("Enter col range start: "))
    col_range_end = int(input("Enter col range end: "))
    col_range_increment = int(input("Enter col range increment: "))

    #row range is bottom/top bound of centers of shapes
    #row increment is vertical space between centers of shapes

    #col range is left/right bound of centers of shapes
    #col increment is horizontal space between centers of shapes

    draw_grids(murtle,sides_per_polygon,edge_pixel_length,rotational_copies,row_range_start,row_range_end,row_range_increment,col_range_start,col_range_end,col_range_increment)

    print("Click turtle screen to exit...")
    wn.exitonclick()

if __name__ == "__main__":
    main()


import numpy as np
import logging
import sys
import pkg_resources
import pytz
import datetime
import os
import re
from numpy import cos,sin

# Get the version
version_file = pkg_resources.resource_filename('pynortek','VERSION')

# Setup logging module
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger('pynortek')

def xyz2enu(u,v,w,head,pitch,roll,inverse=False):
    """
    Transforms velocities in XYZ coordinates to ENU, or vice versa if
    inverse=True. Transformation is done according to the Nortek
    convention

    """
    # convert to radians
    hh = np.pi*(head-90)/180
    pp = np.pi*pitch/180
    rr = np.pi*roll/180

    ut = np.zeros(np.shape(u))
    vt = np.zeros(np.shape(u))
    wt = np.zeros(np.shape(u))

    for i in range(len(head)):
        # generate heading matrix
        H = np.matrix([[cos(hh[i]), sin(hh[i]), 0],[-sin(hh[i]), cos(hh[i]), 0],[0, 0, 1]])
        # generate combined pitch and roll matrix
        P = [[cos(pp[i]), -sin(pp[i])*sin(rr[i]), -cos(rr[i])*sin(pp[i])],
             [0,           cos(rr[i]),                       -sin(rr[i])],
             [sin(pp[i]),  sin(rr[i])*cos(pp[i]),  cos(pp[i])*cos(rr[i])]]

        R = H*P
        #print(R)
        if(inverse):
            R = np.inv(R)

        # do transformation
        ut[i]  = R[0,0]*u[i] + R[0,1]*v[i] + R[0,2]*w[i];
        vt[i]  = R[1,0]*u[i] + R[1,1]*v[i] + R[1,2]*w[i];
        wt[i]  = R[2,0]*u[i] + R[2,1]*v[i] + R[2,2]*w[i];

    return [ut,vt,wt]

raw_data_files = ['.prf','.vec'] # Names of raw binary data files
class pynortek():
    """A Nortek parsing object

    Author: Peter Holtermann (peter.holtermann@io-warnemuende.de)

    Usage:
       >>>filename='test'
       >>>aquadopp = pynortek(filename)

    """
    def __init__(self,filename, verbosity=logging.DEBUG, timezone=pytz.UTC):
        """
        """
        logger.setLevel(verbosity)
        self.timezone = timezone
        self.deployment = os.path.split(filename)[-1]
        self.fpath = os.path.split(filename)[0]
        self.rawdata = {}
        print(self.deployment)
        print(self.fpath)
        filename_hdr = filename + '.hdr'
        logger.debug('Trying to open header file: ' + filename_hdr)
        try:
            fhdr = open(filename_hdr)
        except Exception as e:
            logger.warning('Could not open header file, exiting')
            return

        header = self.parse_header(fhdr)
        self.header = header
        print(header)
        print('Loading files')
        for fread in header['files']:
            print(fread)
            IS_RAW = False
            for rawname in raw_data_files:
                if(rawname in fread.lower()):
                    IS_RAW=True

            if(IS_RAW == False):
                print('Loading ' + fread)
                suffix = fread.split('.')[-1]
                fname_tmp = os.path.join(self.fpath,fread)
                print(fname_tmp)
                data_tmp = np.loadtxt(fname_tmp)
                self.rawdata[suffix] = data_tmp

        # Process the raw data just loaded
        self.process_rawdata()

    def parse_header(self,fhdr):
        """ Parses a nortek header file
        """
        header = {}
        datefmt = '%d.%m.%Y %H:%M:%S'
        header_field = None
        header['files'] = []
        while True:
            l = fhdr.readline()
            if(len(l) == 0):
                break

            # Find all files to be read
            if((l[0] == '[')):
                ftmp = l.split("\\")[-1].replace(']','').replace('\n','')
                header['files'].append(ftmp)
                # If we have a sensor file, check position of fields
                if('.sen' in l[-7:]):
                    print('Sensor file')
                    header_field = 'sensors'
                    header[header_field] = {}

            # Transducer distance
            if(('Beam' in l) and ('Vertical' in l)):
                print('Transducer distance')
                header_field = 'distance'
                header[header_field] = {'cell':[],'beam':[],'vertical':[]}
                continue

            # Check for the header field
            if('User setup' in l):
                print('User setup')
                header_field = 'User setup'
                header[header_field] = {}
            elif('Hardware configuration' in l):
                print('Hardware configuration')
                header_field = 'Hardware configuration'
                header[header_field] = {}
            elif('Head configuration' in l):
                header_field = 'Head configuration'
                header[header_field] = {}

            #print(l)
            if(header_field is not None): # Check if field is over (one empty line)
                if(len(l) <= 2):
                    print('Header ' + header_field + ' over')
                    header_field = None

            # Check for a one line list
            ind = l.find('  ')
            if(ind >= 0):
                if('Number of measurements' in l):
                    header['Number of measurements'] = int(l.split()[-1])
                elif('Coordinate system' in l):
                    header['Coordinate system'] = l.split()[-1]
                    logger.debug('Coordinate system found: ' + header['Coordinate system'])
                elif('Horizontal velocity range' in l):
                    header['Horizontal velocity range'] = float(l.split()[-2])
                    logger.debug('Horizontal velocity range: ' + str(header['Horizontal velocity range']))
                elif('Vertical velocity range' in l):
                    header['Vertical velocity range'] = float(l.split()[-2])
                    logger.debug('Vertical velocity range: ' + str(header['Vertical velocity range']))
                elif('Orientation' in l):
                    header['Orientation'] = l.split()[-1]
                    if('DOWN' in header['Orientation']):
                        header['updown'] = True
                    else:
                        header['updown'] = False

                    logger.debug('Orientation ' + header['Orientation'] + ' updown:' + str(header['updown']))

                elif('Number of checksum errors' in l):
                    header['Number of checksum errors'] = int(l.split()[-1])
                elif('Time of first measurement' in l):
                    ind2 = l.rfind('  ')
                    tstr = l[ind2+2:].replace('\n','')
                    ttmp = datetime.datetime.strptime(tstr,datefmt)
                    ttmp = ttmp.replace(tzinfo=self.timezone)
                    header['Time of first measurement'] = ttmp
                elif('Time of last measurement' in l):
                    ind2 = l.rfind('  ')
                    tstr = l[ind2+2:].replace('\n','')
                    ttmp = datetime.datetime.strptime(tstr,datefmt)
                    ttmp = ttmp.replace(tzinfo=self.timezone)
                    header['Time of last measurement'] = ttmp
                elif('Transformation matrix' in l):
                    logger.debug('Transformation matrix found')
                    header['Transformation matrix'] = np.zeros((3,3))
                    # Get all three lines
                    tmp = []
                    tmp.append(l)
                    tmp.append(fhdr.readline())
                    tmp.append(fhdr.readline())
                    for i in range(3):
                        T_tmp = np.asarray(tmp[i].split()[-3:]).astype(np.float)
                        header['Transformation matrix'][i,:] = T_tmp

                    logger.debug(str(header['Transformation matrix']))

                elif('Magnetometer calibration matrix' in l):
                    logger.debug('Magnetometer calibration matrix found')
                    header['Magnetometer calibration matrix'] = np.zeros((3,3))
                    # Get all three lines
                    tmp = []
                    tmp.append(l)
                    tmp.append(fhdr.readline())
                    tmp.append(fhdr.readline())
                    for i in range(3):
                        T_tmp = np.asarray(tmp[i].split()[-3:]).astype(np.float)
                        header['Magnetometer calibration matrix'][i,:] = T_tmp

                    logger.debug(str(header['Magnetometer calibration matrix']))

                else:
                    pass

                if(header_field is not None):
                    if(header_field == 'sensors'):
                        l = l.replace('\n','').replace('\r','').strip() # remove return and trailing/leading blanks
                        lsp = re.sub("  +" , "\t", l).split('\t')
                        print('sensors',lsp)
                        field = lsp[1]
                        value = lsp[0]
                        header[header_field][field] = int(value)
                    elif(header_field == 'distance'):
                        l = l.replace('\n','').replace('\r','').strip() # remove return and trailing/leading blanks
                        lsp = re.sub("  +" , "\t", l).split('\t')
                        cell = lsp[0]
                        beam = lsp[1]
                        vertical = lsp[2]
                        print(cell,beam,vertical)
                        header[header_field]['cell'].append(int(cell))
                        header[header_field]['beam'].append(float(beam))
                        header[header_field]['vertical'].append(float(vertical))
                    else:
                        ind2 = l.rfind('  ')
                        data = l[ind2+2:].replace('\n','').replace('\r','')
                        field = l[:ind].replace('\n','').replace('\r','')
                        header[header_field][field] = data

            #print(l.split())

        return header

    def process_rawdata(self):
        """ Processes .sen data stored in data['sen'] and the remaining rawdata
        """
        print('Creating time axis')
        t  = []
        tu = []
        for i in range(np.shape(self.rawdata['sen'][:,0])[0]):
            month  = int(self.rawdata['sen'][i,0])
            day    = int(self.rawdata['sen'][i,1])
            year   = int(self.rawdata['sen'][i,2])
            hour   = int(self.rawdata['sen'][i,3])
            minute = int(self.rawdata['sen'][i,4])
            millis = self.rawdata['sen'][i,5]%1
            second = int(self.rawdata['sen'][i,5] - millis)
            micro  = int(millis*1000*1000)
            ttmp = datetime.datetime(year,month,day,hour,minute,second,micro,tzinfo=self.timezone)
            t.append(ttmp)
            tu.append(ttmp.timestamp())

        self.t = t # datetime time
        self.tu = tu # unix time
        self.data = {}
        for k in self.header['sensors'].keys():
            ind_key = self.header['sensors'][k] - 1
            self.data[k] = self.rawdata['sen'][:,ind_key]

        # Processing the remaining data
        # For a profiler (Aquadopp)
        aquadopp_keys = ['v1','v2','v3','a1','a2','a3','c1','c2','c3']
        for key in aquadopp_keys:
            if(key in self.rawdata.keys()):
               print('Getting data from: ' + key + ' (profiler)')
               self.data[key] = self.rawdata[key][:,2:]

        if('distance' in self.header.keys()):
            self.data['dis_beam'] = np.asarray(self.header['distance']['beam'])
            self.data['dis_vertical'] = np.asarray(self.header['distance']['vertical'])

        vector_keys = ['dat']
        for key in vector_keys:
            if(key in self.rawdata.keys()):
               print('Getting data from: ' + key + ' (Vector)')
               self.data[key] = self.rawdata[key][:,2:]

    def rot_vel(self,coord,updown=None,save=False):
        """ Rotates the velocities to different coordinate system
        Args:
            coord:
            updown:
            save:
        """
        logger.debug('trans_coord():')
        T = self.header['Transformation matrix'][:]
        if(updown == None):
            updown = self.header['updown']

        # flip axes if instrument is pointing downward
        # (so from here on, XYZ refers to a right-handed coordinate system
        # with z pointing upward)

        if updown:
            logger.debug('Downlooking, changing matrix')
            T[1,:] = -T[1,:];
            T[2,:] = -T[2,:];

        v1_rot = np.zeros(np.shape(self.data['v1']))
        v2_rot = np.zeros(np.shape(self.data['v2']))
        v3_rot = np.zeros(np.shape(self.data['v3']))
        try:
            v1_rep_rot = np.zeros(np.shape(self.data['v1_rep']))
            v2_rep_rot = np.zeros(np.shape(self.data['v2_rep']))
            v3_rep_rot = np.zeros(np.shape(self.data['v3_rep']))
            repaired = True
        except:
            repaired_false = True
            pass

        print(np.shape(self.data['v1']))
        if(coord == 'XYZ'):
            if(self.header['Coordinate system'] == 'BEAM'):
                logger.debug('BEAM to XYZ')
                for i in range(np.shape(v1_rot)[0]):
                    for j in range(np.shape(v1_rot)[1]):
                        v1_rot[i,j] = T[0,0] * self.data['v1'][i,j] + T[0,1] * self.data['v2'][i,j] + T[0,2] * self.data['v3'][i,j]
                        v2_rot[i,j] = T[1,0] * self.data['v1'][i,j] + T[1,1] * self.data['v2'][i,j] + T[1,2] * self.data['v3'][i,j]
                        v3_rot[i,j] = T[2,0] * self.data['v1'][i,j] + T[2,1] * self.data['v2'][i,j] + T[2,2] * self.data['v3'][i,j]
                        if repaired:
                            v1_rep_rot[i,j] = T[0,0] * self.data['v1_rep'][i,j] + T[0,1] * self.data['v2_rep'][i,j] + T[0,2] * self.data['v3_rep'][i,j]
                            v2_rep_rot[i,j] = T[1,0] * self.data['v1_rep'][i,j] + T[1,1] * self.data['v2_rep'][i,j] + T[1,2] * self.data['v3_rep'][i,j]
                            v3_rep_rot[i,j] = T[2,0] * self.data['v1_rep'][i,j] + T[2,1] * self.data['v2_rep'][i,j] + T[2,2] * self.data['v3_rep'][i,j]

        if save:
            logger.debug('saving data in trans')
            try: # Check if self.trans is existing
                self.trans
            except:
                self.rotvel = {}
            if(coord == 'XYZ'):
                self.rotvel['u'] = v1_rot[:]
                self.rotvel['v'] = v2_rot[:]
                self.rotvel['w'] = v3_rot[:]
                if repaired:
                    # Save the repaired data as well
                    self.rotvel['u_rep'] = v1_rep_rot[:]
                    self.rotvel['v_rep'] = v2_rep_rot[:]
                    self.rotvel['w_rep'] = v3_rep_rot[:]

        return [v1_rot,v2_rot,v3_rot]

    def repair_phase_shift(self,vel=None,threshold=None, save = False):
        """Tries to repair a phase shift in pulse coherent measurements. It
        assumes that the first measured value is correct.

        """

        if(vel == None):
            vel = self.data
            logger.debug('repairing native velocity')
            coordinate_system = self.header['Coordinate system']
            vel_all = [self.data['v1'],self.data['v2'],self.data['v3']]
        else:
            vel_all = [vel]

        vel_rep_all = []
        for vel_tmp in vel_all:
        # Compute threshold from header data
            if( coordinate_system == 'BEAM'):
                logger.debug('Using thresholds for beam coordinates')
                # Get the factor for the beam from the vertical velocity
                fac = np.linalg.inv(self.header['Transformation matrix'])[0,2]
                threshold_tmp = self.header['Vertical velocity range']# * fac
            else:
                logger.debug('Unknown threshold, returning')
                return

            vel_rep = np.zeros(np.shape(vel_tmp))
            for i in range(np.shape(vel_rep)[1]):
                vel_rep[:,i] = self.repair_phase_shift_vector(vel_tmp[:,i],threshold_tmp)

            vel_rep_all.append(vel_rep)

        print('hallo',vel is self.data)
        if((vel is self.data) and save):
            logger.debug("Saving data as data['v1_rep'] etc")
            self.data['v1_rep'] = vel_rep_all[0]
            self.data['v2_rep'] = vel_rep_all[1]
            self.data['v3_rep'] = vel_rep_all[2]

    def repair_phase_shift_vector(self,vel,threshold):
        """Tries to repair a phase shift in pulse coherent measurements. It
        assumes that the first measured value is correct.

        """

        vel_rep = vel.copy()

        vthresh = threshold - 0.3 * threshold
        for i in range(1,len(vel)):
            if((np.sign(vel_rep[i-1]) != np.sign(vel_rep[i])) and (abs(vel_rep[i-1]) > vthresh) and (abs(vel_rep[i]) > vthresh)):
               #print('Phase shift!')
               dv = threshold - abs(vel_rep[i])
               vel_rep[i] =  np.sign(vel_rep[i-1]) * (threshold + dv)

        return vel_rep


def parens(num, the_str='()'):
    the_set = set()
    if num == 1:
        return [the_str]
    else:
        for i in range(len(the_str) + 1):
            the_set.add(the_str[:i] + '()' + the_str[i:])
        for i in the_set:
            temp_list = parens(num - 1, i)
            if type(temp_list) == set:
                the_set = the_set | temp_list
    return the_set

def workaround(num):
    output = list(parens(num))
    to_return = []
    for i in output:
        if len(i) == num * 2:
            to_return.append(i)
    return to_return

if __name__ == '__main__':
    print(workaround(8))


"""initial

Revision ID: 977a56225963
Revises: None
Create Date: 2016-09-24 22:05:55.701455

"""

# revision identifiers, used by Alembic.
revision = '977a56225963'
down_revision = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('series',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('title', sa.String(length=120), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('title')
    )
    op.create_table('chapter',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('title', sa.String(length=120), nullable=True),
    sa.Column('body', sa.String(length=1000000), nullable=True),
    sa.Column('series_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['series_id'], ['series.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('title')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('chapter')
    op.drop_table('series')
    ### end Alembic commands ###


from torch import nn
import torch
import utils
import cv2
import numpy as np
import supervisely_lib as sly

def inference(model: nn.Module, input_height, input_width, image_path, device=None):
    with torch.no_grad():
        model.eval()
    image = sly.image.read(image_path)  # RGB
    input = utils.prepare_image_input(image, input_width, input_height)
    input = torch.unsqueeze(input, 0)
    input = utils.cuda(input, device)
    output = model(input)

    image_height, image_width = image.shape[:2]
    predicted_classes_indices = output.data.cpu().numpy().argmax(axis=1)[0]
    result = cv2.resize(predicted_classes_indices, (image_width, image_height), interpolation=cv2.INTER_NEAREST)
    return result

def convert_prediction_to_sly_format(predicted_class_indices, classes_json, model_classes: sly.ProjectMeta):
    height, width = predicted_class_indices.shape[:2]
    labels = []
    for idx, class_info in enumerate(classes_json):  # curr_col2cls.items():
        class_mask = predicted_class_indices == idx  # exact match (3-channel img & rgb color)
        if not np.any(class_mask):
            # 0 pixels for class
            continue
        bitmap = sly.Bitmap(data=class_mask)
        obj_class = model_classes.get_obj_class(class_info["title"])
        labels.append(sly.Label(bitmap, obj_class))
    ann = sly.Annotation(img_size=(height, width), labels=labels)
    return ann

def load_model(weights_path, num_classes, model_name, device):
    from train import model_list
    model_class = model_list[model_name]["class"]
    model = model_class(num_classes=num_classes)
    state = torch.load(weights_path)
    model.load_state_dict(state)
    model.to(device)
    model.eval()
    return model


"""Unit test is expected to be here, while I use some usage cases instead."""

from name_analyzer.name_analysis import Name_analysis

if __name__ == '__main__':
    # query = 'Martin Reynolds British'
    # query = 'Martin Reynolds Maynard'
    # query = 'Darry Holliday University of Holy Cross'
    # query = 'Caron Anderson Emory University'
    # query = 'Darryl Holliday City Bureau'
    # query = 'Yi Fang SCU'
    query = {
        'first_name':'Yi',
        'last_name': 'Fang', #required
        'affiliation': 'SCU',
        'title': 'Dr.'
    }

    obj = Name_analysis(google_dir= 'google img directory', bing_dir= 'bing img directory')
    result = obj.analyze_name(query)
    print(result)


#https://docs.python.org/3/library/heapq.html
#https://www.programiz.com/python-programming/methods/dictionary/get

#Link: https://leetcode.com/problems/top-k-frequent-elements/
# Name: Top K Frequent Elements
# Difficulty: Medium
# Topic: Min Heap
#Time: O(n log k) since we update the root a maximum of n times, each update is a log k operation
#Space: O(n + k) for size of heap used and the hashmpa size
import heapq
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:

        freqMap = {}
        for num in nums:
            if(num not in freqMap):
                freqMap[num] = 0
            freqMap[num] += 1

        return heapq.nlargest(k, freqMap.keys(), key=freqMap.get)


import logging
from asyncio import CancelledError, Task, create_task
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager, suppress

from fastapi import FastAPI
from servicelib.logging_utils import log_context
from watchdog.observers.api import DEFAULT_OBSERVER_TIMEOUT

from ._context import OutputsContext
from ._event_filter import EventFilter
from ._event_handler import EventHandlerObserver
from ._manager import OutputsManager

_logger = logging.getLogger(__name__)

class OutputsWatcher:
    def __init__(
        self, *, outputs_manager: OutputsManager, outputs_context: OutputsContext
    ) -> None:
        self.outputs_manager = outputs_manager
        self.outputs_context = outputs_context

        self._task_events_worker: Task | None = None
        self._event_filter = EventFilter(outputs_manager=outputs_manager)
        self._observer_monitor: EventHandlerObserver = EventHandlerObserver(
            outputs_context=self.outputs_context,
            outputs_manager=self.outputs_manager,
            heart_beat_interval_s=DEFAULT_OBSERVER_TIMEOUT,
        )

    async def _worker_events(self) -> None:
        while True:
            event: str | None = (
                await self.outputs_context.port_key_events_queue.coro_get()
            )
            if event is None:
                break

            await self._event_filter.enqueue(event)

    async def enable_event_propagation(self) -> None:
        await self.outputs_context.toggle_event_propagation(is_enabled=True)

    async def disable_event_propagation(self) -> None:
        await self.outputs_context.toggle_event_propagation(is_enabled=False)

    async def start(self) -> None:
        with log_context(_logger, logging.INFO, f"{OutputsWatcher.__name__} start"):
            self._task_events_worker = create_task(
                self._worker_events(), name="outputs_watcher_events_worker"
            )

            await self._event_filter.start()
            await self._observer_monitor.start()

    async def shutdown(self) -> None:
        """cleans up spawned tasks which might be pending"""
        with log_context(_logger, logging.INFO, f"{OutputsWatcher.__name__} shutdown"):
            await self._event_filter.shutdown()
            await self._observer_monitor.stop()

            if self._task_events_worker is not None:
                self._task_events_worker.cancel()
                with suppress(CancelledError):
                    await self._task_events_worker

def setup_outputs_watcher(app: FastAPI) -> None:
    async def on_startup() -> None:
        assert isinstance(app.state.outputs_context, OutputsContext)  # nosec
        outputs_context: OutputsContext = app.state.outputs_context
        outputs_manager: OutputsManager
        outputs_manager = app.state.outputs_manager  # nosec

        app.state.outputs_watcher = OutputsWatcher(
            outputs_manager=outputs_manager,
            outputs_context=outputs_context,
        )
        await app.state.outputs_watcher.start()
        await disable_event_propagation(app)

    async def on_shutdown() -> None:
        outputs_watcher: OutputsWatcher | None = app.state.outputs_watcher
        if outputs_watcher is not None:
            await outputs_watcher.shutdown()

    app.add_event_handler("startup", on_startup)
    app.add_event_handler("shutdown", on_shutdown)

async def disable_event_propagation(app: FastAPI) -> None:
    outputs_watcher: OutputsWatcher | None = app.state.outputs_watcher
    if outputs_watcher is not None:
        await outputs_watcher.disable_event_propagation()

async def enable_event_propagation(app: FastAPI) -> None:
    outputs_watcher: OutputsWatcher | None = app.state.outputs_watcher
    if outputs_watcher is not None:
        await outputs_watcher.enable_event_propagation()

@asynccontextmanager
async def event_propagation_disabled(app: FastAPI) -> AsyncGenerator[None, None]:
    try:
        await disable_event_propagation(app)
        yield None
    finally:
        await enable_event_propagation(app)


import cv2 as cv
import numpy as np

def nothing(x):
    pass
cap= cv.VideoCapture('pranay1.avi')
fourcc= cv.VideoWriter_fourcc('X', 'V', 'I', 'D')
out= cv.VideoWriter('final1.avi', fourcc, 20.0, (640,480) )
#cv.namedWindow('Tracking')
#cv.createTrackbar('l_h', 'Tracking', 0, 255, nothing)
#cv.createTrackbar('l_s', 'Tracking', 0, 255, nothing)
#cv.createTrackbar('l_v', 'Tracking', 0, 255, nothing)
#cv.createTrackbar('u_h', 'Tracking', 255, 255, nothing)
#cv.createTrackbar('u_s', 'Tracking', 255, 255, nothing)
#cv.createTrackbar('u_v', 'Tracking', 255, 255, nothing)
while(True):
    ret, frame= cap.read()
    frame= cv.resize(frame, (640,480))
    hsv= cv.cvtColor(frame, cv.COLOR_BGR2HSV)
    #lh = cv.getTrackbarPos('l_h', 'Tracking')
    #ls = cv.getTrackbarPos('l_s', 'Tracking')
    #lv = cv.getTrackbarPos('l_v', 'Tracking')
    #uh = cv.getTrackbarPos('u_h', 'Tracking')
    #us = cv.getTrackbarPos('u_s', 'Tracking')
    #uv = cv.getTrackbarPos('u_v', 'Tracking')
    lh= 82
    ls= 51
    lv= 51
    uh= 133
    us= 255
    uv= 255
    lhb= 0
    lsb= 0
    lvb= 0
    uhb= 255
    usb= 255
    uvb= 0
    lbb= np.array([lhb, lsb, lvb])
    ubb= np.array([uhb, usb, uvb])
    lb= np.array([lh,ls,lv])
    ub= np.array([uh,us,uv])
    backg= cv.imread('pranay42.JPG')
    backg= cv.resize(backg, (640,480))
    mask= cv.inRange(hsv, lb, ub)
    masknot= cv.bitwise_not(mask)
    res= cv.bitwise_and(frame, frame, mask = masknot)
    a= cv.bitwise_and(backg, backg, mask=mask)
    fres= cv.addWeighted(res,1,a,1,1)
    cv.imshow('frame', frame)
    cv.imshow('fres', fres)
    key= cv.waitKey(1)
    if ret==True:
        out.write(fres)
    if key == 27:
        break
cap.release()
cv.destroyAllWindows()


from django.db import models

from book_archive.models import Genre
from config.models import User

class BookRequest(models.Model):
    title = models.CharField('Наименование', max_length=128)
    author = models.CharField('Автор', max_length=128, null=True, blank=True)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, verbose_name='Жанры', null=True, blank=True)
    year = models.PositiveIntegerField('Год', default=0)
    created_at = models.DateTimeField('Дата запроса', auto_now_add=True)
    user = models.ForeignKey(
        User, null=True, blank=True,
        on_delete=models.CASCADE, verbose_name='Кто добавил',
    )
    is_approved = models.BooleanField('Одобрено ли', null=True, blank=True)

    class Meta:
        db_table = 'book_request'
        verbose_name = 'Запрос книги'
        verbose_name_plural = 'Запросы книг'

    def __str__(self):
        return f'{self.title}'


"""See `TestSet` for an example."""
from typing import Type, MutableSet

from tests.collection_testing import unordered_equal

class MutableSetTests:
    mutable_set: Type = None

    @classmethod
    def create_mutable_set(cls) -> MutableSet:
        return cls.mutable_set()

    @staticmethod
    def get_element(i):
        return i

    def test_add_coverage(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)

        instance.add(element1)
        # And add a second time for good measure
        instance.add(element1)

    def test_discard_missing_element_passes(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)

        instance.discard(element1)

    def test_discard_passes(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)

        instance.add(element1)
        instance.discard(element1)

    def test_contains_len(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)

        assert len(instance) == 0
        assert element1 not in instance
        instance.add(element1)
        assert element1 in instance
        assert len(instance) == 1

        element2 = self.get_element(2)
        assert element2 not in instance
        instance.add(element2)
        assert element2 in instance
        assert len(instance) == 2

        assert element1 in instance
        instance.discard(element1)
        assert element1 not in instance
        assert len(instance) == 1

        assert element2 in instance
        instance.discard(element2)
        assert element1 not in instance
        assert element2 not in instance
        assert len(instance) == 0

    def test_iter(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)
        element2 = self.get_element(2)

        assert list(iter(instance)) == []
        instance.add(element1)
        assert unordered_equal(iter(instance), [element1])

        instance.add(element2)
        assert unordered_equal(iter(instance), [element1, element2])

class TestMutableSet(MutableSetTests):
    mutable_set = set


"""
This file defines the recorder classes which log eval results in different ways,
such as to a local JSON file or to a remote Snowflake database.

If you would like to implement a custom recorder, you can see how the
`LocalRecorder` and `Recorder` classes inherit from the `RecorderBase` class and
override certain methods.
"""
import atexit
import contextlib
import dataclasses
import logging
import threading
import time
from contextvars import ContextVar
from datetime import datetime, timezone
from typing import Any, List, Optional, Sequence, Text

import blobfile as bf
import requests

import evals
from evals.base import RunSpec
from evals.data import jsondumps
from evals.utils.misc import t
from evals.utils.snowflake import SnowflakeConnection

logger = logging.getLogger(__name__)

MIN_FLUSH_EVENTS = 100
MAX_SNOWFLAKE_BYTES = 16 * 10**6
MIN_FLUSH_SECONDS = 10

_default_recorder: ContextVar[Optional["RecorderBase"]] = ContextVar(
    "default_recorder", default=None
)

def default_recorder() -> Optional["RecorderBase"]:
    return _default_recorder.get()

@dataclasses.dataclass
class Event:
    run_id: str
    event_id: int
    sample_id: Optional[str]
    type: str
    data: dict
    created_by: str
    created_at: str

class RecorderBase:
    """
    The standard events for which recording methods are provided are:
    - `match`: A match or non match, as specified by the `correct` bool, between
        the `expected` and `picked` results.
    - `embedding`: An embedding of the `prompt` of type `embedding_type`.
    - `sampling`: What was `sampled` from the model given the input `prompt`.
    - `cond_logp`: The conditional log probability, as `logp`, of the
        `completion` from the model given the input `prompt`.
    - `pick_option`: The option `picked` by the model out of the valid `options`
        given the input `prompt`.
    - `raw`: A raw sample specified by the `data`.
    - `metrics`: A set of metrics specified by the `kwargs`.
    - `error`: An `error` along with an accompanying `msg`.
    - `extra`: Any extra `data` of interest to be recorded.
    For these events, helper methods are defined at the bottom of this file.
    More generally, you can record any event by calling `record_event` with the
    event `type` and `data`.
    Finally, you can also record a final report using `record_final_report`.
    """

    def __init__(
        self,
        run_spec: evals.base.RunSpec,
    ) -> None:
        self._sample_id: ContextVar[Optional[int]] = ContextVar("_sample_id", default=None)
        self.run_spec = run_spec
        self._events: List[Event] = []
        self._last_flush_time = time.time()
        self._flushes_done = 0
        self._written_events = 0
        self._flushes_started = 0
        self._event_lock = threading.Lock()
        self._paused_ids: List[str] = []
        atexit.register(self.flush_events)

    @contextlib.contextmanager
    def as_default_recorder(self, sample_id: str):
        sample_id_token = self._sample_id.set(sample_id)
        default_recorder_token = _default_recorder.set(self)
        yield
        _default_recorder.reset(default_recorder_token)
        self._sample_id.reset(sample_id_token)

    def current_sample_id(self) -> Optional[str]:
        return self._sample_id.get()

    def pause(self):
        sample_id = self.current_sample_id()
        with self._event_lock:
            if sample_id not in self._paused_ids:
                self._paused_ids.append(sample_id)

    def unpause(self):
        sample_id = self.current_sample_id()
        with self._event_lock:
            if sample_id in self._paused_ids:
                self._paused_ids.remove(sample_id)

    def is_paused(self, sample_id: str = None):
        if sample_id is None:
            sample_id = self.current_sample_id()
        with self._event_lock:
            return sample_id in self._paused_ids

    def get_events(self, type: str) -> Sequence[Event]:
        with self._event_lock:
            return [event for event in self._events if event.type == type]

    def get_metrics(self):
        return list(map(lambda x: x.data, self.get_events("metrics")))

    def get_scores(self, key: str):
        return list(map(lambda e: e.data[key], self.get_events("metrics")))

    def _create_event(self, type, data=None, sample_id=None):
        if sample_id is None:
            sample_id = self.current_sample_id()
        if sample_id is None:
            raise ValueError("No sample_id set! Either pass it in or use as_default_recorder!")

        return Event(
            run_id=self.run_spec.run_id,
            event_id=len(self._events),
            type=type,
            sample_id=sample_id,
            data=data,
            created_by=self.run_spec.created_by,
            created_at=str(datetime.now(timezone.utc)),
        )

    def _flush_events_internal(self, events_to_write: Sequence[Event]):
        pass

    def flush_events(self):
        with self._event_lock:
            if len(self._events) == self._written_events:
                return
            events_to_write = self._events[self._written_events :]
            self._written_events = len(self._events)
            self._flushes_started += 1
        self._flush_events_internal(events_to_write)

    def record_event(self, type, data=None, sample_id=None):
        if sample_id is None:
            sample_id = self.current_sample_id()
        if sample_id is None:
            raise ValueError("No sample_id set! Either pass it in or use as_default_recorder!")

        if self.is_paused(sample_id):
            return
        with self._event_lock:
            event = Event(
                run_id=self.run_spec.run_id,
                event_id=len(self._events),
                type=type,
                sample_id=sample_id,
                data=data,
                created_by=self.run_spec.created_by,
                created_at=str(datetime.now(timezone.utc)),
            )
            self._events.append(event)
            if (
                self._flushes_done < self._flushes_started
                or len(self._events) < self._written_events + MIN_FLUSH_EVENTS
                or time.time() < self._last_flush_time + MIN_FLUSH_SECONDS
            ):
                return
            events_to_write = self._events[self._written_events :]
            self._written_events = len(self._events)
            self._flushes_started += 1
            self._flush_events_internal(events_to_write)

    def record_match(self, correct: bool, *, expected=None, picked=None, sample_id=None, **extra):
        assert isinstance(
            correct, bool
        ), f"correct must be a bool, but was a {type(correct)}: {correct}"

        if isinstance(expected, list) and len(expected) == 1:
            expected = expected[0]
        data = {
            "correct": bool(correct),
            "expected": expected,
            "picked": picked,
            **extra,
        }
        self.record_event("match", data, sample_id=sample_id)

    def record_embedding(self, prompt, embedding_type, sample_id=None, **extra):
        data = {
            "prompt": prompt,
            "embedding_type": embedding_type,
            **extra,
        }
        self.record_event("embedding", data, sample_id=sample_id)

    def record_sampling(self, prompt, sampled, sample_id=None, **extra):
        data = {
            "prompt": prompt,
            "sampled": sampled,
            **extra,
        }
        self.record_event("sampling", data, sample_id=sample_id)

    def record_cond_logp(self, prompt, completion, logp, sample_id=None, **extra):
        data = {
            "prompt": prompt,
            "completion": completion,
            "logp": logp,
            **extra,
        }
        self.record_event("cond_logp", data, sample_id=sample_id)

    def record_pick_option(self, prompt, options, picked, sample_id=None, **extra):
        data = {
            "prompt": prompt,
            "options": options,
            "picked": picked,
            **extra,
        }
        self.record_event("pick_option", data, sample_id=sample_id)

    def record_raw(self, data):
        self.record_event("raw_sample", data)

    def record_metrics(self, **kwargs):
        self.record_event("metrics", kwargs)

    def record_error(self, msg: str, error: Exception, **kwargs):
        data = {
            "type": type(error).__name__,
            "message": str(error),
        }
        data.update(kwargs)
        self.record_event("error", data)

    def record_extra(self, data, sample_id=None):
        self.record_event("extra", data, sample_id=sample_id)

    def record_final_report(self, final_report: Any):
        logging.info(f"Final report: {final_report}. Not writing anywhere.")

def _green(str):
    return f"\033[1;32m{str}\033[0m"

def _red(str):
    return f"\033[1;31m{str}\033[0m"

class DummyRecorder(RecorderBase):
    """
    A "recorder" which only logs certain events to the console.
    Can be used by passing `--dry-run` when invoking `oaieval`.
    """

    def __init__(self, run_spec: RunSpec, log: bool = True):
        super().__init__(run_spec)
        self.log = log

    def record_event(self, type, data, sample_id=None):
        from evals.registry import registry

        if self.run_spec is None:
            return

        base_eval_spec = registry.get_base_eval(self.run_spec.base_eval)
        if base_eval_spec and len(base_eval_spec.metrics) >= 1:
            primary_metric = base_eval_spec.metrics[0]
        else:
            primary_metric = "accuracy"

        with self._event_lock:
            event = self._create_event(type, data)
            self._events.append(event)

        msg = f"Not recording event: {event}"

        if type == "match":
            accuracy_good = (
                primary_metric == "accuracy" or primary_metric.startswith("pass@")
            ) and (data.get("correct", False) or data.get("accuracy", 0) > 0.5)
            f1_score_good = primary_metric == "f1_score" and data.get("f1_score", 0) > 0.5
            if accuracy_good or f1_score_good:
                msg = _green(msg)
            else:
                msg = _red(msg)

        if self.log:
            logging.info(msg)

class LocalRecorder(RecorderBase):
    """
    A recorder which logs events to the specified JSON file.
    This is the default recorder used by `oaieval`.
    """

    def __init__(self,
        log_path: Optional[str],
        run_spec: RunSpec,
        hidden_data_fields: Sequence[Text] = []):
        """
        Initializes a LocalRecorder.

        Args:
            log_path (Optional[str]): Path to which the LocalRecorder will
                record events. Currently accepts local paths, google cloud
                storage paths, or Azure blob paths.
            run_spec (RunSpec): Passed to the superclass to provide metadata
                about the current evals run.
            hidden_data_fields (Sequence[Text]): Fields to avoid writing in the
                output. This is particularly useful when using a language model
                as an evaluator of sensitive customer data which should not be
                written to disc.
        """
        super().__init__(run_spec)
        self.event_file_path = log_path
        self.hidden_data_fields = hidden_data_fields
        if log_path is not None:
            with bf.BlobFile(log_path, "wb") as f:
                f.write((jsondumps({"spec": dataclasses.asdict(run_spec)}) + "\n").encode("utf-8"))

    def _flush_events_internal(self, events_to_write: Sequence[Event]):
        start = time.time()
        try:
            lines = [jsondumps(event, exclude_keys=self.hidden_data_fields) + "\n" for event in events_to_write]
        except TypeError as e:
            logger.error(f"Failed to serialize events: {events_to_write}")
            raise e

        with bf.BlobFile(self.event_file_path, "ab") as f:
            f.write(b"".join([line.encode("utf-8") for line in lines]))

        logger.info(
            f"Logged {len(lines)} rows of events to {self.event_file_path}: insert_time={t(time.time()-start)}"
        )

        self._last_flush_time = time.time()
        self._flushes_done += 1

    def record_final_report(self, final_report: Any):
        with bf.BlobFile(self.event_file_path, "ab") as f:
            f.write((jsondumps({"final_report": final_report}) + "\n").encode("utf-8"))

        logging.info(f"Final report: {final_report}. Logged to {self.event_file_path}")

class HttpRecorder(RecorderBase):
    def __init__(
        self,
        url: str,
        run_spec: RunSpec,
        local_fallback_path: str,
        fail_percent_threshold: int = 5,
        batch_size: int = 100,
    ):
        super().__init__(run_spec)
        self.url = url
        self.batch_size = batch_size
        self.fail_percent_threshold = fail_percent_threshold / 100
        self.failed_requests = 0  # Add this line to track failed requests
        self.local_fallback_path = local_fallback_path
        self.local_fallback_recorder = LocalRecorder(local_fallback_path, run_spec)
        logger.info(f"HttpRecorder initialized with URL {self.url}")

    def _flush_events_internal(self, events_to_write: Sequence[Event]):
        batch_size = self.batch_size
        for i in range(0, len(events_to_write), batch_size):
            batch = list(events_to_write[i : i + batch_size])
            try:
                self._send_event(batch)
            except RuntimeError as e:
                logger.error(f"Falling back to LocalRecorder due to error: {str(e)}")
                self.local_fallback_recorder._flush_events_internal(batch)
                raise RuntimeError(
                    "An error occurred when sending events. Your events have been saved locally using the Local recorder."
                )

    def _send_event(self, events: List[Event]):
        # Convert the events to dictionaries
        events_dict = [dataclasses.asdict(event) for event in events]

        logger.debug(f"Sending events: {events_dict}")

        try:
            # Send the events to the specified URL
            response = requests.post(self.url, json=events_dict)

            # If the request succeeded, log a success message
            if response.ok:
                logger.debug(f"Events sent successfully")

            # If the request failed, log a warning and increment failed_requests
            else:
                logger.warning(f"Failed to send events: {response.text}")
                self.failed_requests += len(
                    events
                )  # Increase the count by the number of events in the failed request

        except Exception as e:
            logger.warning(f"Failed to send events: {str(e)}")
            self.failed_requests += len(
                events
            )  # Increase the count by the number of events in the failed request

            # Check if the proportion of failed requests exceeds the threshold
            fail_threshold = self.fail_percent_threshold
            # Make a string for human comprehention
            fail_threshold_str = str(fail_threshold * 100) + "%"

            if self.failed_requests / len(self._events) > fail_threshold:
                raise RuntimeError(
                    "The proportion of failed events has exceeded the threshold of: "
                    + fail_threshold_str
                    + "."
                    + " Falling back to LocalRecorder. "
                    "You can modify this via the cli flag --http-fail-percent-threshold"
                )

    def record_final_report(self, final_report: Any):
        # Convert the final report to a dictionary and prepare it as an event
        report_event = Event(
            run_id=self.run_spec.run_id,
            event_id=len(self._events),
            sample_id=None,  # or you could use a specific id for final reports
            type="final_report",
            data=final_report,
            created_by=self.run_spec.created_by,
            created_at=str(datetime.now(timezone.utc)),
        )

        # Send the final report event
        try:
            self._send_event([report_event])
            logging.info(f"Final report: {final_report}.")
            logging.info(f"Data logged to: {self.url}")
        except RuntimeError as e:
            logger.error(f"Falling back to LocalRecorder due to error: {str(e)}")
            self.local_fallback_recorder.record_final_report(final_report)

class Recorder(RecorderBase):
    """
    A recorder which logs events to Snowflake.
    Can be used by passing `--no-local-run` when invoking `oaieval`.
    """

    def __init__(
        self,
        log_path: Optional[str],
        run_spec: RunSpec,
        snowflake_connection: Optional[SnowflakeConnection] = None,
    ) -> None:
        super().__init__(run_spec)
        self.event_file_path = log_path
        self._writing_lock = threading.Lock()

        if snowflake_connection is None:
            snowflake_connection = SnowflakeConnection()
        self._conn = snowflake_connection

        if log_path is not None:
            with bf.BlobFile(log_path, "wb") as f:
                f.write((jsondumps({"spec": dataclasses.asdict(run_spec)}) + "\n").encode("utf-8"))

        query = """
            INSERT ALL INTO runs (run_id, model_name, eval_name, base_eval, split, run_config, settings, created_by, created_at)
            VALUES (%(run_id)s, %(model_name)s, %(eval_name)s, %(base_eval)s, %(split)s, run_config, settings, %(created_by)s, %(created_at)s)
            SELECT PARSE_JSON(%(run_config)s) AS run_config, PARSE_JSON(%(settings)s) AS settings
        """
        self._conn.robust_query(
            command=query,
            params={
                "run_id": run_spec.run_id,
                # TODO: model_name -> completion_fns
                "model_name": jsondumps(dict(completions=run_spec.completion_fns)),
                "eval_name": run_spec.eval_name,
                "base_eval": run_spec.base_eval,
                "split": run_spec.split,
                "run_config": jsondumps(run_spec.run_config),
                "settings": jsondumps(run_spec.run_config.get("initial_settings", {})),
                "created_by": run_spec.created_by,
                "created_at": run_spec.created_at,
            },
        )
        atexit.register(self.flush_events)

    def _flush_events_internal(self, events_to_write: Sequence[Event]):
        with self._writing_lock:
            try:
                lines = [jsondumps(event) + "\n" for event in events_to_write]
            except TypeError as e:
                logger.error(f"Failed to serialize events: {events_to_write}")
                raise e
            idx_l = 0
            while idx_l < len(events_to_write):
                total_bytes = 0
                idx_r = idx_l
                while (
                    idx_r < len(events_to_write)
                    and total_bytes + len(lines[idx_r]) < MAX_SNOWFLAKE_BYTES
                ):
                    total_bytes += len(lines[idx_r])
                    idx_r += 1
                assert idx_r > idx_l
                start = time.time()
                buffer = [
                    (
                        event.run_id,
                        event.event_id,
                        event.sample_id,
                        event.type,
                        jsondumps(event.data),
                        event.created_by,
                        event.created_at,
                    )
                    for event in events_to_write[idx_l:idx_r]
                ]
                query = """
                INSERT INTO events (run_id, event_id, sample_id, type, data, created_by, created_at)
                SELECT Column1 AS run_id, Column2 as event_id, Column3 AS sample_id, Column4 AS type, PARSE_JSON(Column5) AS data, Column6 AS created_by, Column7 AS created_at
                FROM VALUES(%s, %s, %s, %s, %s, %s, %s)
                """
                self._conn.robust_query(command=query, seqparams=buffer, many=True)
                logger.info(
                    f"Logged {len(buffer)} rows of events to Snowflake: insert_time={t(time.time()-start)}"
                )
                idx_l = idx_r

            with bf.BlobFile(self.event_file_path, "ab") as f:
                f.write(b"".join([line.encode("utf-8") for line in lines]))
            self._last_flush_time = time.time()
            self._flushes_done += 1

    def record_final_report(self, final_report: Any):
        with self._writing_lock:
            with bf.BlobFile(self.event_file_path, "ab") as f:
                f.write((jsondumps({"final_report": final_report}) + "\n").encode("utf-8"))
            query = """
                UPDATE runs
                SET final_report = PARSE_JSON(%(final_report)s)
                WHERE run_id = %(run_id)s
            """
            self._conn.robust_query(
                command=query,
                params={
                    "run_id": self.run_spec.run_id,
                    "final_report": jsondumps(final_report),
                },
            )

    def record_event(self, type, data=None, sample_id=None):
        # try to serialize data so we fail early!
        _ = jsondumps(data)
        return super().record_event(type, data, sample_id)

#########################################################################
### Helper methods which use the thread local global default recorder ###
#########################################################################

def current_sample_id() -> str:
    return default_recorder().current_sample_id

def record_match(correct: bool, *, expected=None, picked=None, **extra):
    return default_recorder().record_match(correct, expected=expected, picked=picked, **extra)

def record_embedding(prompt, embedding_type, **extra):
    return default_recorder().record_embedding(prompt, embedding_type, **extra)

def record_sampling(prompt, sampled, **extra):
    return default_recorder().record_sampling(prompt, sampled, **extra)

def record_cond_logp(prompt, completion, logp, **extra):
    return default_recorder().record_cond_logp(prompt, completion, logp, **extra)

def record_pick_option(prompt, options, picked, **extra):
    return default_recorder().record_pick_option(prompt, options, picked, **extra)

def record_raw(data):
    return default_recorder().record_raw(data)

def record_metrics(**extra):
    return default_recorder().record_metrics(**extra)

def record_error(msg: str, error: Exception = None, **extra):
    return default_recorder().record_error(msg, error, **extra)

def record_extra(data):
    return default_recorder().record_extra(data)

def record_event(type, data=None, sample_id=None):
    return default_recorder().record_event(type, data, sample_id)

def pause():
    return default_recorder().pause()

def unpause():
    return default_recorder().unpause()


import cv2
import numpy as np
import matplotlib.pyplot as plt

img=cv2.imread('/home/hasantha/Desktop/repos/old-yolov4-deepsort-master/data/download2.png' ,0)
#img=img[423:998,806:1408]

ret, bw_img = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY) #165
kernel = np.ones((1,1),np.uint8)
#erosion = cv2.erode(img,kernel,iterations = 1)
opening = cv2.morphologyEx(bw_img, cv2.MORPH_OPEN, kernel)
#closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)

#Append lane line coordinates to a matrix
lane_line_co=[]
x_cord_lane = np.where(opening == 255)[1]#+806     #+805
y_cord_lane = np.where(opening == 255)[0]#+423     #+389

for q in range(0, len(x_cord_lane)):
    lane_line_co.append((x_cord_lane[q],y_cord_lane[q]))

def get_lane_line_co():
    return x_cord_lane,y_cord_lane,lane_line_co

#print(lane_line_co)

#print(get_lane_line_co()[2])


#!/bin/python3

import math
import os
import random
import re
import sys

def getMaxStreaks(toss):
    result = [0,0]
    for num in range(len(toss)-1):
        repeat = 0
        if toss[num] == "Heads":
            for t in toss[num:]:
                if t == "Heads":
                    repeat += 1
            if repeat > result[0]:
                result[0] = repeat
        else:
            for t in toss[num:]:
                if t == "Tails":
                    repeat += 1
            if repeat > result[1]:
                result[1] = repeat
    return result

if __name__ == '__main__':

    toss_count = int(input().strip())

    toss = []

    for _ in range(toss_count):
        toss_item = input()
        toss.append(toss_item)

    ans = getMaxStreaks(toss)

    fptr.write(' '.join(map(str, ans)))
    fptr.write('\n')

    fptr.close()


# Add Binary - https://leetcode.com/problems/add-binary/
'''Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"'''

class Solution:
    def addBinary(self, a: str, b: str) -> str:

        maxLength = max(len(a), len(b))
        a = a.zfill(maxLength)
        b = b.zfill(maxLength)
        carry = 0
        output = ""
        for i in range(maxLength - 1, -1, -1):
            if a[i] == "1":
                carry += 1
            if b[i] == "1":
                carry += 1

            if carry % 2 == 1:
                output += "1"
            else:
                output += "0"

            carry //= 2

        if carry:
            output += str(carry)
        return output[::-1]


import random
from datetime import datetime

ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
conteudo = 'There are many variations of passages of Lorem Ipsum available, but the ' \
           'majority have suffered alteration in some form, by injected humour, or randomised ' \
           'words which look even slightly believable. '
excerto = 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots' \
          ' in a piece of classical Latin'
now = datetime.now()
year = str(now.year).zfill(4)
month = str(now.month).zfill(2)
hour = str(now.hour).zfill(2)
minute = str(now.minute).zfill(2)
second = str(now.second).zfill(2)

for categoria_post_id in range(1, 5):  # Pressupõe 4 categorias
    for i in range(5):  # 5 posts para cada categoria
        titulo_post = ' '.join([''.join(random.choices(ALPHABET, k=random.randint(3, 8))) for i in range(3)])
        data_post = f'{year}-{month}-{str((now.day - i) % 29).zfill(2)} {hour}:{minute}:{second}'
        conteudo_post = (conteudo * random.randint(3, 25) + '.</br>') * 5
        excerto_post = excerto * random.randint(3, 5) + '. '
        imagem_post = f'post_img/2022/02/26/13estacio-sistemas.jpg'  # Mude para uma imagem que você tenha feito upload
        publicado_post = random.randint(0, 1)
        autor_post_id = 1  # id do seu super usuário

        sql_post = (f"INSERT INTO blog_django.posts_post"
                    f"(titulo_post,data_post,conteudo_post,excerto_post,imagem_post,"
                    f"publicado_post,autor_post_id,categoria_post_id)"
                    f"VALUES ('{titulo_post}','{data_post}','{conteudo_post}',"
                    f"'{excerto_post}','{imagem_post}',{publicado_post},"
                    f"{autor_post_id},{categoria_post_id});")

        print(sql_post)