import gpgmp.job
import gpgmp.io
import gpgmp.helpers
import numpy
import matplotlib.pyplot as plt

# plot a single problem
def plot_single(hdffile, deterministic=False, sampletime=1000., speciesid=1., length=89.4):

    # read in problem
    n, times, species, nspecies = gpgmp.io.read_gmp_hdf5(hdffile, deterministic=deterministic)
    im=numpy.squeeze(n[0,numpy.where(times==sampletime),speciesid,:,:])

    # get plot specs and create figure
    specs = gpgmp.helpers.getPlotSpecs('plos')
    fig=plt.figure(1, figsize=(specs['width2c'], specs['width2c']*3./4.), dpi=300)
    plt.clf()

    # plot it
    plt.imshow(im, extent=[0,length,0,length])

    # remove ticklabels
    ax = plt.gca()
    for tick in ax.xaxis.get_major_ticks():
        tick.label1On = False
        tick.label2On = False
    for tick in ax.yaxis.get_major_ticks():
        tick.label1On = False
        tick.label2On = False

# run Gray-Scott problem
def run_single(problemdir, clSourceDir, initDir,
               executable='test',
               deterministic=False, aqss=False,
               length=89.4, nx=256, tmax=1000, numRuns=1, dtOut=50, U=0., V=0.005,
               k = 0.0225, F = 0.0025, Omega = 250):

    # Parameters
    #./gpgmp -x 256 -y 256 -t 1000 -l 89.4 -r 1 -o 50 -s 2 -p 20 0 0.005 0.0225 0.0025 250

    # run it and get the timing
    # we assume that the init script and the executable are already in the current directory..
    if deterministic:
        numruns = 1
        if aqss:
            solver = 4
        else:
            solver = 3
    else:
        solver = 2

    time = gpgmp.job.run_job(problemdir, executable, clSourceDir = clSourceDir, initDir=initDir,
                             parameters='{0:g} {1:g} {2:g} {3:g} {4:g}'.format(U, V, k, F, Omega),
                             problem=20, length=length, nx=nx, runtime=tmax, dtout=dtOut, solver=solver,
                             datafile='gray_scott.h5', outlog='gray_scott.out', errlog='gray_scott.err')

    return time

def run_range(datadir, clSourceDir, initDir, executable='test', deterministic=False):

    # problem parameters
    diffU = 0.
    diffV = 0.005
    k = 0.0225
    F = 0.0025
    omegabase = 250.

    # geometry
    length = 44.7*2

    # runtime
    tmax = 5000.
    tout = 50.

    # loop over scale
    for scale in range(5):
        omega = omegabase*10**(scale-2)

        # create directory
        fulldir = basedir+'/{0:d}/run_{1:g}/'.format(nx, 10**scale)
        os.makedirs(fulldir)

        time = gpgmp.job.run_job(datadir, executable, clSourceDir=clSourceDir, initDir=initDir,
                                 parameters='{0:g} {1:g} {2:g} {3:g} {4:g}'.format(U, V, k, F, Omega),
                                 problem=20, length=length, nx=nx, runtime=tmax, dtout=dtOut, solver=solver,
                                 datafile='gray_scott.h5', outlog='gray_scott.out', errlog='gray_scott.err')


import pylab as PL
import scipy as SP

def plot_inferred(models, model_names, sim, step=0.02, name=None, title=None, X_logscale=False, qtl_loci=None):
    PL.figure()
    plot_sim(sim)
    colors = 'rc'
    tau_mean = 0
    f1_err = 0
    f10_err = 0
    qtl_mode = 0

    for i in range(len(models)): # AF estimates
        if len(models[i].F.E1.shape) == 1:
            PL.plot(models[i].F.E1, colors[i])
        else:
            if qtl_loci is None: qtl_loci = [models[i].F.E1.shape[0]/2]
            for q in qtl_loci:
                PL.plot(models[i].F.E1[q], colors[i])

    for i, m in enumerate(models): # QTL estimates
        if model_names[i] == 'Inferred F1':
            x = m.X.E1
            if X_logscale:
                x = (m.X.lnX - min(m.X.lnX))/(abs(m.X.lnX - min(m.X.lnX)).max())
            PL.plot(m.qtl_loci, x[m.qtl_loci], 'k')
            #PL.plot(models[i].Rho.E1*2 + 0.3, 'm--') # true rec rate
            #PL.plot(models[i].F.E1[1:] - models[i].F.E1[0:-1] + 0.2, 'y') # inferred change
            #tau_mean = models[i].Tau.E1
            f1_err = abs(m.F.E1[m.X.E1.argmax()] - sim.F1).mean()
            qtl_mode = m.X.E1[len(m.X.E1)/2]
        if model_names[i] == 'Smoothed F1':
            f10_err = abs(m.F.E1 - sim.F1).mean()

    PL.legend(['F0', 'True F1', 'Data'] + model_names)
    T = models[0].F.E1.shape[0]/50.
    PL.xticks([5*T,15*T,25*T,35*T,45*T], [-100,-50,0,50,100])
    PL.xlabel('Distance to QTL (cM)')
    PL.ylabel('A allele frequency')
    if title is None: title = ''
#    title = title + ' $\\langle \\tau \\rangle = %.3f$'%tau_mean
    title = title + ' $|\Delta f_1|=%.3f$ '%f1_err
    title = title + ' $|\Delta f^0_1|=%.3f$ '%f10_err
    title = title + ' $p(X)=%.3f$ '%qtl_mode
    PL.title(title)
    if name is not None: PL.savefig('plot_%s.pdf'%name)

def plot_single(af, sd=None, locs=None, color="b", linewidth=2, alpha_multiplier=0.1):
    if locs is None: locs = range(len(af))
    line = PL.plot(locs, af, color+'-', linewidth=linewidth)

    if sd != None:
        x_ci = SP.array(list(locs) + list(locs)[::-1])
        y_ci = SP.array(list(af) + list(af)[::-1])
        sds = SP.array(list(sd) + list(-sd)[::-1])
        PL.fill(x_ci, y_ci + sds, color, alpha=alpha_multiplier)
        PL.fill(x_ci, y_ci + 2*sds, color, alpha=2*alpha_multiplier)

    return line

def plot_sim(sim):
    PL.plot(sim.F0, '--')
    PL.plot(sim.F1, '--')
    PL.plot(sim.D[:,0]/sim.D.sum(axis=1), 'r.', markersize=8)

def plot_prediction_forlocus(model, F1, l, q):
    L = len(model.F.E1)
    res = SP.zeros(L)
    for l2 in range(L):
        #if l != q and l2 == 230: pdb.set_trace()
        res[l2] = get_estimate(model, l, l2, q)[0]## estimate allele frequency posterior at locus l from data at locus l2, regardless of position of qtl locus q
    PL.plot(range(L), SP.ones(L)*F1[l], "k--")
    PL.plot(range(L), res, "b.")
    PL.show()

def plot_prediction_fromlocus(model, F1, l, q):
    L = len(model.F.E1)
    res = SP.zeros(L)
    for l2 in range(L):
        qtl_l = (q <= l and l <= l2) or (q >= l and l >= l2) # qtl towards l
        if (l <= q and q <= l2) or (l2 <= q and q <= l):  # if QTL between two loci, estimate from q
            res[l2] = get_simple_estimate(model, F1[q], 0, l2, q, True)[0]
        else:
            res[l2] = get_simple_estimate(model, F1[l], 0, l2, l, qtl_l)[0]
    PL.plot(range(L), F1, "k--")
    PL.plot(range(L), res, "b.")
    PL.show()


import cv2
import os
import numpy as np
from functools import cmp_to_key

# Function to compute texture difference
def compute_texture_difference(hist1, hist2):
    diff = 0
    for i in range(len(hist1)):
        diff += abs(hist1[i] - hist2[i])
    return diff / (2 * 89 * 60)

# Function to compare two images based on their T values
def compare_images(a, b):
    return a[1] - b[1]

def main():
    # Read images from dir
    directory = "images"
    image_files = [f"i{str(i).zfill(2)}.jpg" for i in range(1, 41)]

    # Load crowd data from the text file
    with open("Crowd.txt", "r") as f:
        lines = f.readlines()
        crowd_data = [[float(value) for value in line.strip().split()] for line in lines]

    # Calculate grayscale intensity for all images
    histograms = []
    for filename in image_files:
        img = cv2.imread(os.path.join(directory, filename))
        height, width, channels = img.shape
        gray = np.zeros((height, width), dtype=np.uint8)
        for y in range(height):
            for x in range(width):
                pixel = img[y, x]
                avg = int(np.mean(pixel))
                gray[y, x] = avg

        #Calculate Laplacian for all images
        laplacian = cv2.Laplacian(gray, cv2.CV_64F, ksize=3)    #hybrid
        laplacian_abs = cv2.convertScaleAbs(laplacian)
        histTex = cv2.calcHist([laplacian_abs], [0], None, [4], [0, 256])
        histograms.append(histTex.flatten())

    # Compute T values for each pair of images
    T_values = []
    for i, hist1 in enumerate(histograms):
        image_diffs = []
        for j, hist2 in enumerate(histograms):
            if i != j:
                T = compute_texture_difference(hist1, hist2)
                image_diffs.append((image_files[j], T))

        # Sort the images by their T values
        sorted_diffs = sorted(image_diffs, key=cmp_to_key(compare_images))
        T_values.append((image_files[i], sorted_diffs[:3]))

    # Create HTML output
    html_output = '''
    <!DOCTYPE html>

                q
                t1
                t2
                t3
                score

'''

    #Calculate q_scores for all images, rows, and for the entire table
    grand_total_score = 0
    for row_index, row in enumerate(T_values):
        row_total_score = 0
        html_output += "

{}	".format(row[0], row[0])
        for col in row[1]:
            col_index = int(col[0][1:3]) - 1
            q_value = crowd_data[row_index][col_index]
            row_total_score += q_value
            html_output += "
{}
{}	".format(col[0], col[0], q_value)
        html_output += "{}
".format(row_total_score)
        grand_total_score += row_total_score

    html_output += '''

PERSONAL HAPPINESS SCORE: {}

    '''.format(grand_total_score)

    # Save HTML output to a file
    with open("output_texture_crowd.html", "w") as f:
        f.write(html_output)

if __name__ == "__main__":
    main()


from urllib.request import urlopen
from dataclasses import dataclass
import json

from aiogram.types.user import User

from config import WEATHER_API_KEY, WEEK_FORECAST_API_CALL, WEATHER_NOW_API_CALL

@dataclass(slots=True, frozen=True)
class Weather:
    temp: str
    condition: str

@dataclass(slots=True, frozen=True)
class Forecast:
    date: str
    max_temp: str
    min_temp: str
    condition: str

def get_weather() -> Weather:
    url = WEATHER_NOW_API_CALL.format(api_key=WEATHER_API_KEY, city=User.city)
    response = urlopen(url)
    data = json.load(response)["current"]
    temp = data["temp_c"]
    condition = data["condition"]["text"]
    return Weather(temp=temp, condition=condition)

def week_forecast():
    url = WEEK_FORECAST_API_CALL.format(api_key=WEATHER_API_KEY, city=User.city)
    response = urlopen(url)
    data = json.load(response)["forecast"]["forecastday"]
    forecast = []

    for day in data:
        date = day["date"]
        max_temp, min_temp = day["day"]["maxtemp_c"], day["day"]["mintemp_c"]
        condition = day["day"]["condition"]["text"]
        forecast.append(
            Forecast(
                date=date, max_temp=max_temp, min_temp=min_temp, condition=condition
            )
        )
    return forecast


import asyncio
import websockets

async def listen():
    """
        read about binance websocket: https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md
    """
    url = "wss://stream.binance.com:9443/ws/bnbusdt@kline_3m"

    async with websockets.connect(url) as ws:
        while True:
            msg = await ws.recv()
            print("=============")
            print(msg)
            # await asyncio.sleep(1)

asyncio.get_event_loop().run_until_complete(listen())


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

from pysqlcipher import dbapi2 as sqlcipher
import xml.etree.cElementTree as et
import os
import sqlite3
import sys
import uuid

# Example usage:
# python WriteDatabase.py -i CancerTerms

config = {
    'DB'  : 'glossary.db',
    'KEY' : uuid.uuid4().hex
}

with open('config.ini', 'w') as f:
    f.write(config['KEY'])

#####################################################################
# Returns the contents of a single XML document as a tuple
# Parameter - Path to the XML document
#####################################################################

def loadXML(filename):
    if not filename.endswith('.xml'):
        return

    root = et.parse(filename).getroot()
    term = {'id': root.attrib['id']}
    term['TermName'] = root.find('TermName').text

    for child in root.findall('TermDefinition'):
        audience = child.find('Audience')
        dictionary = child.find('Dictionary')

        if (audience.text == 'Patient') or \
           (dictionary and dictionary.text == 'Cancer.gov'):

            definition = child.find('DefinitionText')
            text = definition.text if definition.text else ''

            for subchild in definition:
                text += subchild.text + subchild.tail if subchild.tail else ''

            term['DefinitionText'] = ' '.join(text.replace('\n', '').split())

            if (type(term['DefinitionText']) == unicode):
                term['DefinitionText'] = term['DefinitionText'].encode('ascii', 'xmlcharrefreplace')

            return (term['id'], term['TermName'], term['DefinitionText'])

#####################################################################
# Returns the contents of a directory as an array of glossary terms
# Parameter - Path to the glossary terms directory
#####################################################################

def generateDictionary(directory):
    terms = []

    files = os.listdir(directory)
    for index, file in enumerate(files):
        print('Reading xml documents ({0}/{1})\r'.format(index + 1, len(files))),
        sys.stdout.flush()

        term = loadXML(os.path.join(directory, file))

        if term:
            terms.append(term)

    print()

    return terms

#####################################################################
# Creates an encrypted glossary database from a directory
# Parameters - 1. Path to the glossary terms directory
#              2. Path to the generated database file
#####################################################################

def createDatabase(directory, dbname):

    if os.path.isfile(dbname):
        print('Replacing existing database: {0}'.format(dbname))
        os.remove(dbname)

    db = sqlcipher.connect(dbname)
    db.executescript('pragma key = "%s" ' % config['KEY'])
    db.execute('create table terms(id text, term text, definition text)')

    terms = generateDictionary(directory)
    for index, term in enumerate(terms):
        print('Adding terms ({0}/{1})\r'.format(index + 1, len(terms))),
        sys.stdout.flush()

        db.executescript('pragma key = "{0}"'.format(config['KEY']))
        db.execute('insert into terms values (?, ?, ?)', term)

    db.commit()
    db.close()

    print('Finished writing database: {0}'.format(dbname))

#####################################################################
# Queries an encrypted glossary database
# Parameters - 1. Path to the database
#              2. User Query
#              3. Search Type:
#                 1. 'contains' - The term name contains the query
#                 2. 'begins'   - The term name begins with the query
#                 3. 'exact'    - The term name matches the query
#####################################################################

def query(dbname, column, term, type = 'exact'):

    # return empty array if invalid column was supplied
    if (not column in ['id', 'term', 'definition']):
        return []

    db = sqlcipher.connect(dbname)

    if type == 'contains':
        term = '%' + term + '%'

    elif type == 'begins_with':
        term += '%'

    db.executescript('pragma key = "{0}"'.format(config['KEY']))

    results = db.execute(
        'select * from terms where {0} like ?'.format(column),
        tuple([term])
    ).fetchall()

    db.close()

    return results

################################################################################
# Generates a glossary database from a specified archive
#
# Parameters
#             -i, --input     The path to the directory containing xml terms
#             -o, --output    The path to the output file (default: glossary.db)
################################################################################

import argparse
if __name__ == '__main__':

    parser = argparse.ArgumentParser(
        description = '''Creates an encrypted sqlite3 database from a directory
                         containing xml terms'''
    )

    parser.add_argument(
        '-i', '--input',
        dest    = 'input',
        default = 'GlossaryTerm',
        help    = 'Sets the directory containing xml terms'
    )

    parser.add_argument(
        '-o', '--output',
        dest    = 'output',
        default = config['DB'],
        help    = 'Sets the output filename'
    )

    args = parser.parse_args()
    createDatabase(args.input, args.output)


#!/usr/bin/env python
# This script is used to modified the assignment value in a Makefile. It only applies to the variable assignment level.
# Usage: script [current_makefile] [new_makefile] [sequence_of_assignments]
# Example: script make.old make.new "CFLAGS=-Wall" "LDFLAGS+=-lpthread"

import sys
import re
from string import maketrans

class Assignments:
	def __init__(self, seqs):
		self.variables = []
		self.operations = []
		self.values = []
		for e in seqs:
			oper  = "="
			if e.find("+=") >= 0:
				oper = "+="
			self.operations.append(oper)
			self.variables.append(e.split(oper, 1)[0].strip().rstrip())
			self.values.append(e.split(oper,1)[1])
	def has(self, var):
		if var in self.variables:
			return True
		else:
			return False
	def operation_of(self, var):
		return self.operations[self.variables.index(var)]
	def value_of(self, var):
		return self.values[self.variables.index(var)]

assigns = ""

def strok_line(line):

	line1 = line.strip().split()
	if len(line1) <= 1:
		return line1
	sObj1 = re.search(r'(\+|\:)*=', line1[0])
	if sObj1 == None:
		sObj2 = re.search(r'(\+|\:)*=', line1[1])
		if sObj2 == None or sObj2.span()[0] != 0:
			return line1
		else:
			tok = sObj2.group(0)
			ret = [ line1[0],tok ]
			ret.append(line1[1][sObj2.span()[1]:])
			if len(line1) > 2:
				ret = ret + line1[2:]
			return ret
	else:
		if sObj1.span()[0] == 0:
			return line1
		index1 = sObj1.span()[0]
		index2 = sObj1.span()[1]
		if index2 == len(line1[0]):
			ret = [line1[0][0:index1] , line1[0][index1:]]
			ret = ret + line1[1:]
			return ret
		else:
			ret = [line1[0][0:index1] , line1[0][index1:index2], line1[0][index2:]]
			ret = ret + line1[1:]
			return ret

def process_working_lines(working_lines):
	ret = working_lines
	firstline_splits =  strok_line(working_lines[0])
	if len(firstline_splits) < 3:
		return ret
	tok = firstline_splits[0]
	signs = firstline_splits[1]
	if signs.find("=") >= 0:
		if assigns.has(tok):
			if assigns.operation_of(tok) == "=":
				ret = []
				ret.append(tok + " = " + assigns.value_of(tok))
			elif assigns.operation_of(tok) == "+=":
				ret[0]= tok + signs + " " + assigns.value_of(tok)+" " + ' '.join(firstline_splits[2:])
			else:
				print("ERROR")
	return ret

def main():
	global assigns
	if len(sys.argv) < 4:
		print("Invalid Input")
		print("Usage: "+sys.argv[0] + " [input_file] [output_file] [sequence_of_assignments]")
		return
	assigns = Assignments(sys.argv[3:])

	working_lines = [] # Actually one line, but may be seperated by "\" signs.
	with open(sys.argv[1]) as f1 , open(sys.argv[2],'w') as f2:
		for line in f1:
			line = line.strip("\n")
			if len(line.strip()) <= 0: #empty line
				if len(working_lines) > 0:
					for l in process_working_lines(working_lines):
						f2.write(l+"\n")
					working_lines = []
				f2.write(line+"\n")
				continue;

			working_lines.append(line)
			if line[-1] != '\\':
				for l in process_working_lines(working_lines):
					f2.write(l+"\n")
				working_lines = []

main()


n = 5
lost = [2, 4]
reserve = [1,3,5]

def solution(n,lost,reserve):
    inclass = n - len(lost)
    return inclass

print(solution(n,lost,reserve))

# # 방법 2
def solution2(n, lost, reserve):
    s= set(lost) & set(reserve) #두 집합의 교집합을 s에 담는다.
    l = set(lost) - s # 체육복을 빌려야 하는 학생들
    r = set(reserve) - s # 체육복을 빌려 줄 수 있는 학생들
    for x in sorted(r):
        if x - 1 in l:
            l.remove(x - 1)
        elif x + 1 in l:
            l.remove(x + 1)
    return n - len(l)
#
print(solution2(n,lost,reserve))
#
# # 방법1
# def solution(n, lost, reserve):
#     u = [1] * (n + 1) # 1번과 n번 뒤에도 1을 한개씩 넣어주기에 +2를 해준다.
#     for i in reserve:
#         u[i] += 1 #체육복 가져온 친구들 +1 씩 한다.
#     for i in lost:
#         u[i] -= 1 #체육복을 가져오지 않은 친구들은 -1 씩 하여서, 0 이 된다.
#     for i in range(1, n + 1):
#         if u[i - 1] == 0 and u[i] == 2:
#             # u[i] -= 1
#             # u[i - 1] += 1
#             u[i - 1:i + 1] = [1, 1]
#         elif u[i] == 2 and u[i + 1] == 0:
#             u[i:i + 2] = [1, 1]
#     return len([x for x in u[1:-1] if x > 0])


# variable reward plot if using a timing strategy

import matplotlib.pyplot as plt
import numpy as np

class v:
    pass   #make a struct

v.randReqHoldMaxMs = 900
v.fixedReqHoldTimeMs = 100
v.tooFastTimeMs = 1
v.fixedEarlyTimeMs = 150
v.earlyRewardUs = 3000
v.minRewardUs = 30000
v.maxRewardUs = 45000
v.minAgainRewardUs = 3000

v.varRewActualMinMs = 100
v.varRewActualMaxMs = 250
v.varRewActualMinAgainMs = 700
v.reactTimeMs = 3000

#figH = plt.figure()

nRuns = 2000

def doSim(nRuns, doVis, v):

    nPts = 4000
    allVR = np.zeros((nPts, nRuns))

    for iR in range(0,nRuns):
        # simulate nRuns trials
        tVarRew = np.zeros((nPts,))

        if doVis:
            tHoldTime = (v.randReqHoldMaxMs*np.random.random_sample(1)
                         + v.fixedReqHoldTimeMs)
            t = np.asarray(np.round(tHoldTime), dtype='int64')
        else:
            error()

        tVarRew[0:v.fixedEarlyTimeMs] = v.earlyRewardUs
        tVarRew[v.fixedEarlyTimeMs:t] = v.earlyRewardUs
        tVarRew[t:t+v.varRewActualMinMs] = v.minRewardUs
        tVarRew[t+v.varRewActualMinMs:t+v.varRewActualMaxMs] \
            = np.linspace(v.minRewardUs, v.maxRewardUs,
                          v.varRewActualMaxMs-v.varRewActualMinMs)
        tVarRew[t+v.varRewActualMaxMs:t+v.varRewActualMinAgainMs] \
            = np.linspace(v.maxRewardUs, v.minAgainRewardUs,
                          v.varRewActualMinAgainMs-v.varRewActualMaxMs)
        tVarRew[t+v.varRewActualMinAgainMs:t+v.reactTimeMs] = v.minAgainRewardUs
        tVarRew[t:t+v.tooFastTimeMs] = v.earlyRewardUs

       #else not written code yet
        allVR[:,iR] = tVarRew

    return allVR

allVR = doSim(nRuns, 1, v)
meanVR = np.mean(allVR, axis=1)

plt.plot(meanVR)

t1 = np.round(v.randReqHoldMaxMs/2 + v.fixedReqHoldTimeMs)
plt.plot((0,t1,t1, t1+v.reactTimeMs), (0, 0, v.maxRewardUs, v.maxRewardUs))

plt.gca().set_xlim(0,2500)

plt.title('Max %d ms' % np.argmax(meanVR))

# wait when run from command line
#canvas = plt.gcf().canvas
#canvas.start_event_loop(timeout=0)


from time import sleep
import bluetooth

bd_addr = "98:D3:31:F5:B9:E7"
port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr,port))
print('Ready!')
print('Press 1 to switch on LED, 0 to switch off')

while 1:
    data = ''
    tosend = input()
    if not len(tosend) > 0:
        continue
    elif tosend != 'q':
            sock.send(tosend)
    else:
            break
    sleep(0.1)
    data = str(sock.recv(1024))
    if data.find('on'):
        print('LED turned ON!')
        print(data)
    elif data.find('off'):
        print('LED turned OFF!')

sock.close()


from langchain.agents import Tool
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.memory import ConversationBufferMemory
from dotenv import load_dotenv
import os.path
from llama_index import (
    GPTSimpleVectorIndex,
    LLMPredictor,
    PromptHelper,
    ServiceContext,
)
from firebase_utils import bucket

load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
os.environ["OPENAI_API_KEY"] = api_key

def chatbot_fn(input_text, index_name="index.json"):
    # Defining the parameters for the index
    max_input_size = 4096
    num_outputs = 1024
    max_chunk_overlap = 20

    prompt_helper = PromptHelper(
        max_input_size,
        num_outputs,
        max_chunk_overlap,
    )

    llm_predictor = LLMPredictor(
        llm=ChatOpenAI(
            temperature=0.2, model_name="gpt-3.5-turbo", max_tokens=num_outputs
        )
    )

    service_context = ServiceContext.from_defaults(
        llm_predictor=llm_predictor, prompt_helper=prompt_helper
    )

    try:
        # Download the index.json file from Firebase Storage
        blob = bucket.blob(f"gptIndices/{index_name}")
        index_json_data = blob.download_as_text()

        index = GPTSimpleVectorIndex.load_from_string(
            index_json_data, service_context=service_context
        )
        print(f"{index_name} has been loaded successfully.")

        # Optimiser reduced time and token usage
        # Tools for langchain agent
        # tools = [
        #     Tool(
        #         name="Custom GPT Index",
        #         func=lambda q: str(index.query(q)),
        #         description="useful for when you want to answer questions about projects "
        #         "and information from the documents. "
        #         "Input to this should be tell me about or summarise something",
        #         return_direct=True,  # return the direct response (observation) from the tool
        #     ),
        # ]

        # memory = ConversationBufferMemory(
        #     memory_key="chat_history", return_messages=True
        # )

        # llm = ChatOpenAI(temperature=0.4, model_name="gpt-3.5-turbo")

        # agent = initialize_agent(
        #     tools,
        #     llm,
        #     agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,
        #     verbose=True,
        #     memory=memory,
        # )

        response = index.query(input_text, service_context=service_context)
        print("response: ", response.response)

        return response.response

    except Exception as e:
        print("Error loading index.json:", e)
        return f"Error loading index. Inform your developer, {e}"


# Import for making json
import json
from collections import OrderedDict

# CONFIG
# acceptance_score : 합격 기준 (%)
# subject_fail_score : 과락 기준 (%)
# 아래의 값을 변경 후 현재 파일(set_config.py)을 실행하면 변경된 값이 config.json 파일로 저장됩니다.
acceptance_score: int = 60
subject_fail_score: int = 40

# Make config.json
config_data = OrderedDict()
config_data["acceptance_score"] = acceptance_score
config_data["subject_fail_score"] = subject_fail_score

with open('config.json', 'w', encoding="utf-8") as make_file:
    json.dump(config_data, make_file, ensure_ascii=False, indent="\t")


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

"""
@author: Li Tian
@contact: 694317828@qq.com
@software: pycharm
@file: no_populations.py
@time: 2018/9/10 10:03
@desc: 在世界地图上呈现数字数据
"""

import pygal

wm = pygal.maps.world.World()
wm.title = 'Population of Countries in North America'
wm.add('North America', {'ca': 34126000, 'us':309349000, 'mx': 113423000})

wm.render_to_file('na_populations.svg')


from common import *
from Tkinter import *
from ..config import Configuration

from functools import partial

class GuiSettingsUI(UserControl):

    def __init__(self, vision_wrapper, parent=None):
        UserControl.__init__(self, parent, title="GUI Settings")
        self.vision = vision_wrapper

        if parent is not None:
            Button(self, text="Detach", command=self.on_detach,
                   padx=2, pady=2, width=8).pack(anchor=NE)
        else:
            Button(self, text="Re-attach", command=self.on_deattach,
                   padx=2, pady=2, width=8).pack(anchor=NE)

        self.show_contours_var = UserVariable(self, int, True, self.on_show_contours_changed, 500)
        self.show_ball_var = UserVariable(self, int, True, self.on_show_ball_changed, 500)
        self.show_ballv_var = UserVariable(self, int, True, self.on_show_ballv_changed, 500)
        self.show_robots_var = UserVariable(self, int, True, self.on_show_robots_changed, 500)
        self.show_correct_var = UserVariable(self, int, False, self.on_show_correct_changed, 500)
        self.show_raw_var = UserVariable(self, int, False, self.on_show_raw_changed, 500)

        opts_frame = LabelFrame(self, text="Video Feed Options")
        opts_frame.pack()

        Checkbutton(opts_frame, text="Show Ball", variable=self.show_ball_var)\
            .pack(side=LEFT, padx=10, pady=10, anchor=N)
        Checkbutton(opts_frame, text="Show Velocity", variable=self.show_ballv_var)\
            .pack(side=LEFT, padx=10, pady=10, anchor=N)
        Checkbutton(opts_frame, text="Show Robots", variable=self.show_robots_var)\
            .pack(side=LEFT, padx=10, pady=10, anchor=N)
        # Checkbutton(opts_frame, text="Show Corrections", variable=self.show_correct_var)\
        #     .pack(side=LEFT, padx=10, pady=10, anchor=N)
        Checkbutton(opts_frame, text="Show Contours", variable=self.show_contours_var)\
            .pack(side=LEFT, padx=10, pady=10, anchor=N)
        Checkbutton(opts_frame, text="Enable Raw Video", variable=self.show_raw_var)\
            .pack(side=LEFT, padx=10, pady=10, anchor=N)

        self.selector_frame = LabelFrame(self, text="Camera Settings")
        self.selector_frame.pack(padx=5, ipadx=5, pady=5, ipady=5)

        self._vars = list()

        max_values = Configuration.video_settings_max['small'] \
                        if self.vision.color_settings in [0, "small"] \
                        else Configuration.video_settings_max['big']

        for att in self.vision.video_settings:
            if att not in max_values: continue

            var = UserVariable(self, int, 0, partial(self.on_video_att_changed, att), 500)
            var.attribute = att
            self._vars.append(var)

            Scale(self.selector_frame, variable=var, to=max_values[att],
                  orient=HORIZONTAL, label=att.title(), length=300).pack(anchor=W, padx=5, pady=5)

        self.button_frame = Frame(self)
        self.button_frame.pack(padx=5, ipadx=5, pady=5, ipady=5)

        Button(self.button_frame, text="Write Video Settings", command=self.commit_settings,
               padx=10, pady=10, width=15).pack(side=LEFT)

        Button(self.button_frame, text="Reload from File", command=self.reload_config,
                padx=10, pady=10, width=15).pack(side=LEFT)

        Button(self.button_frame, text="Quit", command=self.close,
                padx=10, pady=10, width=15).pack(side=RIGHT)

        self.reload_config()

        self.is_recording = False

        video_frame = LabelFrame(self, text="Record Video")

        self.vid_start_btn = Button(video_frame, text="Begin Record", command=self.on_begin_record,
               padx=10, pady=10, width=15)
        self.vid_start_btn.pack(side=LEFT)

        self.vid_end_btn = Button(video_frame, text="End Record", command=self.on_end_record,
               padx=10, pady=10, width=15)
        self.vid_end_btn.pack(side=LEFT)

        self.title_var = UserVariable(self, str, self._get_default_title())
        self.video_entry = Entry(video_frame, textvariable=self.title_var, width=30)
        self.video_entry.pack(padx=10, pady=10)

        video_frame.pack(padx=5, ipadx=5, pady=5, ipady=5)

    def _get_default_title(self):
        from time import localtime, strftime
        return strftime("%Y_%m_%d %H:%M:%S", localtime())

    def on_show_contours_changed(self, var):
        self.vision.gui.draw_contours = bool(var.value)

    def on_show_ball_changed(self, var):
        self.vision.gui.draw_ball = bool(var.value)

    def on_show_ballv_changed(self, var):
        self.vision.gui.draw_ball_velocity = bool(var.value)

    def on_show_robots_changed(self, var):
        self.vision.gui.draw_robots = bool(var.value)

    def on_show_correct_changed(self, var):
        self.vision.gui.draw_correction = bool(var.value)

    def on_show_raw_changed(self, var):
        self.vision.camera.raw_output_mode = bool(var.value)

    def on_video_att_changed(self, att, var):
        self.vision.video_settings[att] = var.value
        self.vision.video_settings.commit()

    def reload_config(self):
        video_settings = Configuration.read_video_config(
            self.vision.video_settings.machine_name)

        for var in self._vars:
            var.value = video_settings[var.attribute]

    def commit_settings(self):
        for var in self._vars:
            self.vision.video_settings[var.attribute] = var.value

        Configuration.write_video_config(self.vision.video_settings,
                                         self.vision.video_settings.machine_name)

    def on_detach(self):
        self.disintegrate(self.vision)

    def on_deattach(self):
        self.reintegrate(self.vision)

    def on_begin_record(self, *args):
        self.video_entry['state']   = DISABLED
        self.vid_start_btn['state'] = DISABLED
        self.vid_end_btn['state']   = NORMAL

        self.vision.start_video(self.title_var.value)

    def on_end_record(self, *args):
        self.vision.end_video()

        self.title_var.value = self._get_default_title()

        self.vid_end_btn['state']   = DISABLED
        self.video_entry['state']   = NORMAL
        self.vid_start_btn['state'] = NORMAL


from time import time
from copy import copy
from threading import Lock, Timer
from rospy import Publisher, SubscribeListener
from rospy import logwarn
from rostopic import get_topic_type
from rosbridge_library.internal import ros_loader, message_conversion
from rosbridge_library.internal.topics import TopicNotEstablishedException, TypeConflictException

class PublisherConsistencyListener(SubscribeListener):
    """ This class is used to solve the problem that sometimes we create a
    publisher and then immediately publish a message, before the subscribers
    have set up their connections.

    Call attach() to attach the listener to a publisher.  It sets up a buffer
    of outgoing messages, then when a new connection occurs, sends the messages
    in the buffer.

    Call detach() to detach the listener from the publisher and restore the
    original publish methods.

    After some particular timeout (default to 1 second), the listener stops
    buffering messages as it is assumed by this point all subscribers will have
    successfully set up their connections."""

    timeout = 1  # Timeout in seconds to wait for new subscribers
    attached = False

    def attach(self, publisher):
        """ Overrides the publisher's publish method, and attaches a subscribe
        listener to the publisher, effectively routing incoming connections
        and outgoing publish requests through this class instance """
        # Do the attaching
        self.publisher = publisher
        publisher.impl.add_subscriber_listener(self)
        self.publish = publisher.publish
        publisher.publish = self.publish_override

        # Set state variables
        self.lock = Lock()
        self.established_time = time()
        self.msg_buffer = []
        self.attached = True

    def detach(self):
        """ Restores the publisher's original publish method and unhooks the
        subscribe listeners, effectively finishing with this object """
        self.publisher.publish = self.publish
        if self in self.publisher.impl.subscriber_listeners:
            self.publisher.impl.subscriber_listeners.remove(self)
        self.attached = False

    def peer_subscribe(self, topic_name, topic_publish, peer_publish):
        """ Called whenever there's a new subscription.

        If we're still inside the subscription setup window, then we publish
        any buffered messages to the peer.

        We also check if we're timed out, but if we are we don't detach (due
        to threading complications), we just don't propagate buffered messages
        """
        if not self.timed_out():
            with self.lock:
                msgs = copy(self.msg_buffer)
            for msg in msgs:
                peer_publish(msg)

    def timed_out(self):
        """ Checks to see how much time has elapsed since the publisher was
        created """
        return time() - self.established_time > self.timeout

    def publish_override(self, message):
        """ The publisher's publish method is replaced with this publish method
        which checks for timeout and if we haven't timed out, buffers outgoing
        messages in preparation for new subscriptions """
        if not self.timed_out():
            with self.lock:
                self.msg_buffer.append(message)
        self.publish(message)

class MultiPublisher():
    """ Keeps track of the clients that are using a particular publisher.

    Provides an API to publish messages and register clients that are using
    this publisher """

    def __init__(self, topic, msg_type=None, latched_client_id=None, queue_size=100):
        """ Register a publisher on the specified topic.

        Keyword arguments:
        topic    -- the name of the topic to register the publisher to
        msg_type -- (optional) the type to register the publisher as.  If not
        provided, an attempt will be made to infer the topic type
        latch    -- (optional) if a client requested this publisher to be latched,
                    provide the client_id of that client here

        Throws:
        TopicNotEstablishedException -- if no msg_type was specified by the
        caller and the topic is not yet established, so a topic type cannot
        be inferred
        TypeConflictException        -- if the msg_type was specified by the
        caller and the topic is established, and the established type is
        different to the user-specified msg_type

        """
        # First check to see if the topic is already established
        topic_type = get_topic_type(topic)[0]

        # If it's not established and no type was specified, exception
        if msg_type is None and topic_type is None:
            raise TopicNotEstablishedException(topic)

        # Use the established topic type if none was specified
        if msg_type is None:
            msg_type = topic_type

        # Load the message class, propagating any exceptions from bad msg types
        msg_class = ros_loader.get_message_class(msg_type)

        # Make sure the specified msg type and established msg type are same
        if topic_type is not None and topic_type != msg_class._type:
            raise TypeConflictException(topic, topic_type, msg_class._type)

        # Create the publisher and associated member variables
        self.clients = {}
        self.latched_client_id = latched_client_id
        self.topic = topic
        self.msg_class = msg_class
        self.publisher = Publisher(topic, msg_class, latch=(latched_client_id!=None), queue_size=queue_size)
        self.listener = PublisherConsistencyListener()
        self.listener.attach(self.publisher)

    def unregister(self):
        """ Unregisters the publisher and clears the clients """
        self.publisher.unregister()
        self.clients.clear()

    def verify_type(self, msg_type):
        """ Verify that the publisher publishes messages of the specified type.

        Keyword arguments:
        msg_type -- the type to check this publisher against

        Throws:
        Exception -- if ros_loader cannot load the specified msg type
        TypeConflictException -- if the msg_type is different than the type of
        this publisher

        """
        if not ros_loader.get_message_class(msg_type) is self.msg_class:
            raise TypeConflictException(self.topic,
                                        self.msg_class._type, msg_type)
        return

    def publish(self, msg):
        """ Publish a message using this publisher.

        Keyword arguments:
        msg -- the dict (json) message to publish

        Throws:
        Exception -- propagates exceptions from message conversion if the
        provided msg does not properly conform to the message type of this
        publisher

        """
        # First, check the publisher consistency listener to see if it's done
        if self.listener.attached and self.listener.timed_out():
            self.listener.detach()

        # Create a message instance
        inst = self.msg_class()

        # Populate the instance, propagating any exceptions that may be thrown
        message_conversion.populate_instance(msg, inst)

        # Publish the message
        self.publisher.publish(inst)

    def register_client(self, client_id):
        """ Register the specified client as a client of this publisher.

        Keyword arguments:
        client_id -- the ID of the client using the publisher

        """
        self.clients[client_id] = True

    def unregister_client(self, client_id):
        """ Unregister the specified client from this publisher.

        If the specified client_id is not a client of this publisher, nothing
        happens.

        Keyword arguments:
        client_id -- the ID of the client to remove

        """
        if client_id in self.clients:
            del self.clients[client_id]

    def has_clients(self):
        """ Return true if there are clients to this publisher. """
        return len(self.clients) != 0

class PublisherManager():
    """ The PublisherManager keeps track of ROS publishers

    It maintains a MultiPublisher instance for each registered topic

    When unregistering a client, if there are no more clients for a publisher,
    then that publisher is unregistered from the ROS Master
    """

    def __init__(self):
        self._publishers = {}
        self.unregister_timers = {}
        self.unregister_timeout = 10.0

    def register(self, client_id, topic, msg_type=None, latch=False, queue_size=100):
        """ Register a publisher on the specified topic.

        Publishers are shared between clients, so a single MultiPublisher
        instance is created per topic, even if multiple clients register.

        Keyword arguments:
        client_id  -- the ID of the client making this request
        topic      -- the name of the topic to publish on
        msg_type   -- (optional) the type to publish
        latch      -- (optional) whether to make this publisher latched
        queue_size -- (optional) rospy publisher queue_size to use

        Throws:
        Exception -- exceptions are propagated from the MultiPublisher if
        there is a problem loading the specified msg class or establishing
        the publisher

        """
        latched_client_id = client_id if latch else None
        if not topic in self._publishers:
            self._publishers[topic] = MultiPublisher(topic, msg_type, latched_client_id,
             queue_size=queue_size)
        elif latch and self._publishers[topic].latched_client_id != client_id:
            logwarn("Client ID %s attempted to register topic [%s] as latched " +
                    "but this topic was previously registered.", client_id, topic)
            logwarn("Only a single registered latched publisher is supported at the time")
        elif not latch and self._publishers[topic].latched_client_id:
            logwarn("New non-latched publisher registration for topic [%s] which is " +
                    "already registered as latched. but this topic was previously " +
                    "registered.", topic)
            logwarn("Only a single registered latched publisher is supported at the time")

        if msg_type is not None:
            self._publishers[topic].verify_type(msg_type)

        self._publishers[topic].register_client(client_id)

    def unregister(self, client_id, topic):
        """ Unregister a client from the publisher for the given topic.
            Will wait some time before actually unregistering, it is done in
            _unregister_impl

        If there are no clients remaining for that publisher, then the
        publisher is unregistered from the ROS Master

        Keyword arguments:
        client_id -- the ID of the client making this request
        topic     -- the topic to unregister the publisher for

        """
        if not topic in self._publishers:
            return

        self._publishers[topic].unregister_client(client_id)
        if topic in self.unregister_timers:
            self.unregister_timers[topic].cancel()
            del self.unregister_timers[topic]
        self.unregister_timers[topic] = Timer(self.unregister_timeout, self._unregister_impl,
                                              [topic])
        self.unregister_timers[topic].start()

    def _unregister_impl(self, topic):
        if not self._publishers[topic].has_clients():
            self._publishers[topic].unregister()
            del self._publishers[topic]
        del self.unregister_timers[topic]

    def unregister_all(self, client_id):
        """ Unregisters a client from all publishers that they are registered
        to.

        Keyword arguments:
        client_id -- the ID of the client making this request """
        for topic in self._publishers.keys():
            self.unregister(client_id, topic)

    def publish(self, client_id, topic, msg, latch=False, queue_size=100):
        """ Publish a message on the given topic.

        Tries to create a publisher on the topic if one does not already exist.

        Keyword arguments:
        client_id -- the ID of the client making this request
        topic     -- the topic to publish the message on
        msg       -- a JSON-like dict of fields and values
        latch     -- (optional) whether to make this publisher latched
        queue_size -- (optional) rospy publisher queue_size to use

        Throws:
        Exception -- a variety of exceptions are propagated.  They can be
        thrown if there is a problem setting up or getting the publisher,
        or if the provided msg does not map to the msg class of the publisher.

        """
        self.register(client_id, topic, latch=latch, queue_size=queue_size)

        self._publishers[topic].publish(msg)

manager = PublisherManager()


"""REST API for querying user information."""
from flask import Blueprint, abort, jsonify, request

from upload_rest_api.authentication import current_user
from upload_rest_api.models.user import User

USERS_API_V1 = Blueprint("users_v1", __name__, url_prefix="/v1/users")

@USERS_API_V1.route("/projects", methods=["GET"])
def list_user_projects():
    """
    Endpoint for retrieving all projects accessible to the currently
    authenticated user or the specific user.

    If the "username" parameter is determined, the authenticated user
    has to be an administrator to view the details.
    """
    if request.args.get("username", None):
        # If specific username is provided, retrieve the projects for that
        # user, if we have the permission
        username = request.args["username"]

        if not current_user.admin:
            abort(403, "User does not have permission to list projects")

        projects = User.get(username=username).projects
    else:
        # If 'username' is not provided, retrieve projects accessible
        # to the current session
        projects = current_user.projects

    result = {"projects": []}
    for project in projects:
        result["projects"].append({
            "identifier": project.id,
            "used_quota": project.used_quota,
            "quota": project.quota
        })

    return jsonify(result)


# Automation of last cells of create_input/number.ipynb.
# Take all_match_info.csv, add player name to column and hold only league matches

import os
import pandas as pd

# assign directory
directory = '/.../data/players'

league_names = ['premier-league', 'laliga','ligue-1','serie-a','bundesliga','eliteserien','eredivisie','liga-profesional-de-futbol','brasileiro-serie-a','primeira-liga','super-league', 'Süper Lig', 'LaLiga 2']

# iterate over files in that directory
for foldername in sorted(os.listdir(directory)):
    f = os.path.join(directory, foldername)
    csv_path = directory+'/'+foldername+'/all_match_info.csv'

    # Read csv and hold only rows of league games
    all_data = pd.read_csv(csv_path)

    # RUN ONLY ONE TIME
    # player = foldername.split("_")[1] # get player name from folder.
    # all_data.insert(loc=0, column='player_name', value=player)
    # all_data.insert(loc=1, column='player_position', value='')
    # all_data.insert(loc=2, column='player_nationality', value='')
    # all_data.insert(loc=3, column='player_birth', value='')
    # all_data.insert(loc=4, column='player_foot', value='')
    # all_data.insert(loc=5, column='player_height', value='')

    print(all_data.head())

    # all_data.to_csv(csv_path, index=False)

    league_data = all_data[all_data['tournament.uniqueTournament.slug'].isin(league_names)]
    league_data.to_csv(directory+'/'+foldername+'/match_info.csv', index=False)


import pytest

from exercises.models import Textbook, Professor, Subject
from exercises.exercise_1.use_cases import get_textbook_subject

@pytest.fixture
def subject():
    return Subject.objects.create(name="Chemistry")

@pytest.fixture
def textbook(subject) -> Textbook:
    prof = Professor.objects.create(first_name="Bhil", last_name="Isaac")
    textbook = Textbook.objects.create(title=f"General Chemistry", subject=subject)
    textbook.authors.add(prof)
    return textbook

@pytest.mark.django_db()
def test_get_textbook_subject(django_assert_num_queries, textbook, subject):
    with django_assert_num_queries(1):
        actual_subject = get_textbook_subject(textbook.id)
        assert actual_subject == subject.name


import discord
from discord.ext import commands

class Homework(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_member_join(self, member):
        embed = discord.Embed(
            color=discord.Color.blurple(),
            title="✨ Welcome to Future Sphere Academy ✨",
            description="Hello, this is the discord server for Future Sphere Academy. If you have any questions "\
                        "related to homework, please only send in <#858453343545327625>. Before you do this, please "\
                        "remember to read and follow the rules in <#921179091204440154>."
        )
        embed.set_thumbnail(
            url="https://cdn.discordapp.com/icons/690739145101803521/a7ec96a51e34df6d16472980c31fca31.webp?size=96"
        )

        await member.send(embed=embed)

def setup(client):
    client.add_cog(Homework(client))


from itertools import permutations

def findPermutation(number):
    return [''.join(p) for p in permutations(str(number))]

def isPrime(x):
    if x > 1:
        for i in range(2, x + 1):
            if x % i == 0 and i != x and i != 1:
                return False
        else:
            return True
    else:
        return False

if __name__ == '__main__':
    threePrimes = []
    # permutations = findPermutation(1235)
    # for el in permutations:
    #     print(isPrime(int(el)))

    for number in range(1488, 3000):
        threePrimes = []
        if isPrime(number):
            allPermutations = findPermutation(number)
            for element in allPermutations:
                if isPrime(int(element)):
                    threePrimes.append(element)
        if len(threePrimes) > 2:
            if str(number + 3330) in threePrimes and str(number + 6660) in threePrimes:
                print(f'12-digit number do you form by concatenating the three terms in this'
                      f' sequence is: {str(number) + str(number + 3330) + str(number + 6660)}')
                break


import os

from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory

def generate_launch_description():
    # Get the launch directory
    my_dir = get_package_share_directory('gmrf_gas_mapping')

    # common variables
    use_sim_time = True
    remappings=[]
    params_yaml_file = os.path.join(my_dir, 'launch', 'gmrf_params.yaml')
    map_file = os.path.join(my_dir, 'maps', 'empty_map.yaml')

    logger = LaunchConfiguration("log_level")

    return LaunchDescription([
        # Set env var to print messages to stdout immediately
        SetEnvironmentVariable('RCUTILS_LOGGING_BUFFERED_STREAM', '1'),

        DeclareLaunchArgument(
            "log_level",
            default_value=["info"],  #debug, info
            description="Logging level",
            ),

        # MAP_SERVER
        Node(
            package='nav2_map_server',
            executable='map_server',
            name='map_server',
            output='screen',
            parameters=[{'use_sim_time': use_sim_time},
                        {'yaml_filename' : map_file}],
            remappings=remappings
            ),

        # GMRF
        Node(
            package='gmrf_gas_mapping',
            executable='gmrf_node',
            name='gmrf_node',
            output='screen',
            parameters=[params_yaml_file],
            remappings=remappings
            ),

        # Simple publisher (from CSV file)
        Node(
            package='gmrf_gas_mapping',
            executable='gmrf_simple_publisher',
            name='gmrf_pub',
            output='screen',
            parameters=[params_yaml_file],
            remappings=remappings
            ),

        # LIFECYCLE MANAGER
        Node(
            package='nav2_lifecycle_manager',
            executable='lifecycle_manager',
            name='lifecycle_manager_localization',
            output='screen',
            parameters=[{'use_sim_time': use_sim_time},
                        {'autostart': True},
                        {'node_names': ['map_server']}
                       ]
            )
    ])


"""Add difficuly of the session

Revision ID: 5fb8a7c20d00
Revises: b56e2d396ba1
Create Date: 2021-11-18 17:15:44.114176

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '5fb8a7c20d00'
down_revision = 'b56e2d396ba1'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('session', sa.Column('difficulty', sa.Integer(), nullable=False))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('session', 'difficulty')
    # ### end Alembic commands ###


from django.conf.urls import url

from meilihuiapp import views

urlpatterns=[
    url(r'^$',views.index,name='index'),
    url(r'^index/$',views.index,name='index'),
    url(r'^regsiter/$',views.regsiter,name='regsiter'),
    url(r'^logout/$',views.logout,name='logout'),
    url(r'^login/$',views.login,name='login'),
    url(r'^cart/$',views.cart,name='cart'),
    url(r'^addcart/$',views.addcart,name='addcart'),
    url(r'^checkemail/$',views.checkemail,name='checkemail'),
    url(r'^men/$',views.men,name='men'),
    url(r'^detailed/(\d+)/$',views.detailed,name='detailed'),
    url(r'^cartaddgoods/$',views.cartaddgoods,name='cartaddgoods'),
    url(r'^cartsugoods/$',views.cartsugoods,name='cartsugoods'),
    url(r'^chakanstuats/$',views.chakanstuats,name='chakanstuats'),
    url(r'^chakanall/$',views.chakanall,name='chakanall'),
    url(r'^genratorder/$',views.genratorder,name='genratorder'),
    url(r'^orderdetail/(.+)/$',views.orderdetail, name='orderdetail'),
    url(r'^orderlist/(\d+)/$',views.orderlist,name='orderlist'),
]


import pygame
import random
class Object:

    def snake_display(self,snake_pstn,display, snake_color):
        self.snake_pstn = snake_pstn
        self.display = display
        self.snake_color = snake_color

        for pstn in self.snake_pstn:
            pygame.draw.rect(self.display, self.snake_color, pygame.Rect(pstn[0], pstn[1], 10, 10))

    def apple_display(self,apple_img, display, apple_pstn):
        self.apple_img = apple_img
        self.display = display
        self.apple_pstn = apple_pstn
        display.blit(self.apple_img, (self.apple_pstn[0], self.apple_pstn[1]))

class Action:

    def eat_apple(self,apple_pstn, score):
        self.apple_pstn = apple_pstn
        self.score = score
        self.apple_pstn = [random.randrange(1, 50) * 10, random.randrange(1, 50) * 10]
        self.score += 1
        return self.apple_pstn, self.score


# imports
from flask import Flask, render_template, request, redirect, url_for
import string
import random
from datetime import date

# Pagoda
class Pagoda:
    def __init__(self):
        self.towers = []

    def insert(self, x):
        # Check if x is already in the towers
        if any(x['expiry'] == person['expiry'] and x['item'] == person['item'] for tower in self.towers for person in tower):
            return x

        # Append element x to the leftmost empty tower
        i = 0
        while i < len(self.towers) and self.towers[i]:
            i += 1
        if i == len(self.towers):
            self.towers.append([x])
        else:
            self.towers[i].append(x)

        # Merge any two towers of equal size
        for j in range(i - 1, -1, -1):
            if len(self.towers[j]) == len(self.towers[j + 1]):
                self.towers[j] = self.merge(self.towers[j], self.towers[j + 1])
                self.towers[j + 1] = []

        # Propagate the smaller of x and the root of the rightmost nonempty tower
        for j in range(len(self.towers) - 1, -1, -1):
            if self.towers[j] and isinstance(self.towers[j][0], dict) and x['expiry'] < self.towers[j][0]['expiry']:
                x, self.towers[j][0] = self.towers[j][0], x
                if j == 0:
                    break
                if len(self.towers[j - 1]) < len(self.towers[j]):
                    self.towers[j - 1] = self.merge(self.towers[j - 1], self.towers[j])
                    self.towers[j] = []
        return x

   # Find the minimum value in the pagoda
    def find_min(self):
        # Check if the pagoda is empty
        if not self.towers:
            raise ValueError('Pagoda is empty')
        # Check if the first tower is empty
        elif not self.towers[0]:
            # Remove the empty tower from the pagoda and recursively find the minimum in the remaining towers
            del self.towers[0]
            return self.find_min()
        else:
            # Return the minimum value, which is the first element of the first tower
            return self.towers[0][0]

    # Merge two lists of items based on their 'expiry' and 'item' properties
    def merge(self, a, b):
        result = []  # Create an empty list to store the merged result

        while a and b:  # Continue while both lists have elements
            # Compare the expiry of the first elements in both lists
            if a[0]['expiry'] < b[0]['expiry']:
                # Append the element from list 'a' to the result and remove it from 'a'
                result.append(a.pop(0))
            elif a[0]['expiry'] > b[0]['expiry']:
                # Append the element from list 'b' to the result and remove it from 'b'
                result.append(b.pop(0))
            else:
                # If the expiry values are equal, compare the 'item' property
                if a[0]['item'] < b[0]['item']:
                    # Append the element from list 'a' to the result and remove it from 'a'
                    result.append(a.pop(0))
                else:
                    # Append the element from list 'b' to the result and remove it from 'b'
                    result.append(b.pop(0))

        # Append the remaining elements from either list 'a' or 'b' to the result
        result.extend(a)
        result.extend(b)

        # Return the merged result
        return result

# Creating app with Flask
app = Flask(__name__)

# Create an instance of the Pagoda class called warehouseIndex
warehouseIndex = Pagoda()

# Create another instance of the Pagoda class called warehouseIndex2
warehouseIndex2 = Pagoda()

# Insert items into warehouseIndex
warehouseIndex.insert({'item': 'A', 'expiry': date(2023, 4, 27), 'city': None})
warehouseIndex.insert({'item': 'B', 'expiry': date(2023, 4, 25), 'city': None})
warehouseIndex.insert({'item': 'C', 'expiry': date(2023, 4, 28), 'city': None})

# Create an empty dictionary called warehouse
warehouse = dict()

# Add items to the warehouse dictionary with item names as keys and item details as values
warehouse["A"] = {'name': 'A', 'description': 'A', 'price': 'A', 'quantity': 'A', 'expiry': date(2023, 4, 27)}
warehouse["B"] = {'name': 'B', 'description': 'B', 'price': 'B', 'quantity': 'B', 'expiry': date(2023, 4, 25)}
warehouse["C"] = {'name': 'C', 'description': 'C', 'price': 'C', 'quantity': 'C', 'expiry': date(2023, 4, 28)}

# Create an empty dictionary called warehouse2
warehouse2 = dict()

# helper function to convert pagoda to list
def getProducts(warehouseIndex):
    data = []
    while True:
        try:
            min_person = warehouseIndex.find_min()
        except ValueError:
            break
        data.append(min_person)
        warehouseIndex.towers[0].pop(0)
        if not warehouseIndex.towers[0]:
            del warehouseIndex.towers[0]
    return data

# index route
@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.htm')

# route to add products
@app.route('/products', methods=['GET'])
def products():
    data = getProducts(warehouseIndex)
    for item in data:
        print(item)
        warehouseIndex.insert(item)
    if len(data) > 0:
        print(data)
        return render_template('products.htm', data=(data), warehouse=warehouse, firstIndex=data[0] or None)
    return render_template('products.htm')

# route to send products
@app.route('/send-products/<path:sent>/<path:received>', methods=['GET', "POST"])
def sendProducts(sent, received):
    sent = int(sent)
    received = int(received)
    if request.method == "POST":
        if request.form['product'] == 'all':
            noOfProducts = len(warehouseIndex.towers[0])
        else:
            noOfProducts = int(request.form['product'])
        for i in range(1, noOfProducts+1):
            min_person = warehouseIndex.find_min()
            warehouseIndex.towers[0].pop(0)
            if not warehouseIndex.towers[0]:
                del warehouseIndex.towers[0]
            warehouseIndex2.insert(min_person)
            return redirect(url_for('sendProducts', sent=noOfProducts - i, received=i))

    if (sent != 0):
        min_person = warehouseIndex.find_min()
        warehouseIndex.towers[0].pop(0)
        if not warehouseIndex.towers[0]:
            del warehouseIndex.towers[0]
        warehouseIndex2.insert(min_person)
        sent -= 1
        received += 1
        return redirect(url_for('sendProducts', sent=sent, received=received))

    data = getProducts(warehouseIndex)
    data2 = getProducts(warehouseIndex2)
    for item in data:
        warehouseIndex.insert(item)
    for item in data2:
        warehouseIndex2.insert(item)
    return render_template('sendProducts.htm', data=(data), data2=data2,  warehouse=warehouse)

# route to add products
@app.route('/addProduct', methods=['GET', 'POST'])
def addProduct():
    if request.method == 'POST':
        print("Wow")
        item = request.form['item']
        name = request.form['title']
        description = request.form['description']
        price = request.form['price']
        quantity = request.form['quantity']
        expiry = request.form['expiry']

        data = {'item': item, 'expiry': date(int(expiry[0:4]), int(expiry[5:7]), int(expiry[8:10])), 'city': None}
        warehouse[item] = {'name': name, 'description': description, 'price': price, 'quantity': quantity, 'expiry': expiry}
        warehouseIndex.insert(data)

        return redirect(url_for('products'))

    if request.method == 'GET':
        # generte random id
        itemID = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
        return render_template('addProduct.htm', itemID=itemID)

    return render_template('addProduct.htm')

# route to delete product with min index
@app.route('/deleteProduct/<path:id>', methods=['GET', 'POST'])
def deleteProduct(id):
    print("working")
    if request.method == "GET":
        print(id)
        if (id in warehouse):
            del warehouse[id]
            warehouseIndex.towers[0].pop(0)
            if not warehouseIndex.towers[0]:
                del warehouseIndex.towers[0]
    return redirect(url_for('products'))


import cv2 as cv

capture = cv.VideoCapture('Video/A$AP Ferg - Floor Seats (Official Video).mp4')

running = True

def frame_resize(frame, scale=0.75):
    width = int(frame.shape[1] * scale)
    height = int(frame.shape[0] * scale)
    dimenstions = (width, height)

    return cv.resize(frame, dimenstions, interpolation=cv.INTER_AREA)

def change_resolution(width, height):
    capture.set(3, width)
    capture.set(4, height)

while running:
    is_true, frame = capture.read()
    frame_resized = frame_resize(frame, 2)
    # cv.imshow('Video', frame)
    cv.imshow('Video', frame_resized)

    if cv.waitKey(20) and 0xFF == ord('d'):
        break

capture.release()
cv.destroyAllWindows()

cv.waitKey(0)


import os
import sys
import time
import json
from simpleference.inference.inference import run_inference_n5
from simpleference.backends.gunpowder.tensorflow.backend import TensorflowPredict
from simpleference.backends.gunpowder.preprocess import preprocess

def single_gpu_inference(path, gpu, iteration):

    assert os.path.exists(path), path
    out_file = '/data/heinrichl/sample_E.n5'
    weight_meta_graph = '/nrs/saalfeld/heinrichl/synapses/cremi_all_0116_01/unet_checkpoint_%i' % iteration
    inference_meta_graph = '/nrs/saalfeld/heinrichl/synapses/cremi_all_0116_01/unet_inference'
    net_io_json = '/nrs/saalfeld/heinrichl/synapses/cremi_all_0116_01/net_io_names.json'

    with open(net_io_json, 'r') as f:
        net_io_names = json.load(f)

    offset_file = '/nrs/saalfeld/heinrichl/synapses/sampleE_DTU2_offsets_update/list_gpu_{0:}.json'.format(gpu)
    with open(offset_file, 'r') as f:
        offset_list = json.load(f)

    input_key = net_io_names["raw"]
    output_key = net_io_names["dist"]
    input_shape = (91, 862, 862)
    output_shape = (71, 650, 650)
    prediction = TensorflowPredict(weight_meta_graph,
                                   inference_meta_graph,
                                   input_key=input_key,
                                   output_key=output_key)
    t_predict = time.time()
    run_inference_n5(prediction,
                     preprocess,
                     path,
                     out_file,
                     offset_list,
                     input_shape=input_shape,
                     output_shape=output_shape,
                     target_keys='syncleft_dist_DTU-2_{0:}'.format(iteration),
                     input_key='volumes/raw/s0',
                     log_processed = '/nrs/saalfeld/heinrichl/synapses/sampleE_DTU2_offsets_update/list_gpu_{'
                                     '0:}_processed.txt'.format(gpu)
    )
    t_predict = time.time() - t_predict

    with open(os.path.join(out_file, 't-inf_gpu%i.txt' % gpu), 'w') as f:
        f.write("Inference with gpu %i in %f s" % (gpu, t_predict))

if __name__ == '__main__':
    sample = sys.argv[1]
    gpu = int(sys.argv[2])
    iteration = int(sys.argv[3])
    single_gpu_inference(sample, gpu, iteration)


from typing import Any, Dict

import numpy as np

from .._optional import import_optional_dependency

import_optional_dependency("sklearn", on_version="warn")

import sklearn
from sklearn.preprocessing import FunctionTransformer

class Tree:
    """Wrapper to create sklearn Tree objects from Elastic ML tree
    description in JSON format.
    """

    def __init__(
        self,
        json_tree: Dict[str, Any],
        feature_names_map: Dict[str, int],
    ):
        tree_leaf = -1

        node_count = len(json_tree["tree_structure"])
        children_left = np.ones((node_count,), dtype=int) * tree_leaf
        children_right = np.ones((node_count,), dtype=int) * tree_leaf
        feature = np.ones((node_count,), dtype=int) * -2
        threshold = np.ones((node_count,), dtype=float) * -2
        impurity = np.zeros((node_count,), dtype=float)
        # value works only for regression and binary classification
        value = np.zeros((node_count, 1, 1), dtype="<f8")
        n_node_samples = np.zeros((node_count,), dtype=int)

        # parse values from the JSON tree
        feature_names = json_tree["feature_names"]
        for json_node in json_tree["tree_structure"]:
            node_id = json_node["node_index"]
            if "number_samples" in json_node:
                n_node_samples[node_id] = json_node["number_samples"]
            else:
                n_node_samples[node_id] = 0

            if "leaf_value" not in json_node:
                children_left[node_id] = json_node["left_child"]
                children_right[node_id] = json_node["right_child"]
                feature[node_id] = feature_names_map[
                    feature_names[json_node["split_feature"]]
                ]
                threshold[node_id] = json_node["threshold"]
                if "split_gain" in json_node:
                    impurity[node_id] = json_node["split_gain"]
                else:
                    impurity[node_id] = -1
            else:
                value[node_id, 0, 0] = json_node["leaf_value"]

        # iterate through tree to get max depth and expected values
        weighted_n_node_samples = n_node_samples.copy()
        self.max_depth = Tree._compute_expectations(
            children_left=children_left,
            children_right=children_right,
            node_sample_weight=weighted_n_node_samples,
            values=value,
            node_index=0,
        )
        self.n_outputs = value.shape[-1]

        # initialize the sklearn tree
        self.tree = sklearn.tree._tree.Tree(
            len(feature_names), np.array([1], dtype=int), 1
        )
        node_state = np.array(
            [
                (
                    children_left[i],
                    children_right[i],
                    feature[i],
                    threshold[i],
                    impurity[i],
                    n_node_samples[i],
                    weighted_n_node_samples[i],
                    True,
                )
                for i in range(node_count)
            ],
            dtype={
                "names": [
                    "left_child",
                    "right_child",
                    "feature",
                    "threshold",
                    "impurity",
                    "n_node_samples",
                    "weighted_n_node_samples",
                    "missing_go_to_left",
                ],
                "formats": ["<i8", "<i8", "<i8", "<f8", "<f8", "<i8", "<f8", "u1"],
            },
        )
        state = {
            "max_depth": self.max_depth,
            "node_count": node_count,
            "nodes": node_state,
            "values": value,
        }
        self.tree.__setstate__(state)

    @staticmethod
    def _compute_expectations(
        children_left, children_right, node_sample_weight, values, node_index
    ) -> int:
        if children_right[node_index] == -1:
            return 0

        left_index = children_left[node_index]
        right_index = children_right[node_index]
        depth_left = Tree._compute_expectations(
            children_left, children_right, node_sample_weight, values, left_index
        )
        depth_right = Tree._compute_expectations(
            children_left, children_right, node_sample_weight, values, right_index
        )
        left_weight = node_sample_weight[left_index]
        right_weight = node_sample_weight[right_index]

        v = (
            (
                left_weight * values[left_index, :]
                + right_weight * values[right_index, :]
            )
            / (left_weight + right_weight)
            if left_weight + right_weight > 0
            else 0
        )
        values[node_index, :] = v
        return max(depth_left, depth_right) + 1

class TargetMeanEncoder(FunctionTransformer):
    """FunctionTransformer implementation of the target mean encoder, which is
    deserialized from the Elastic ML preprocessor description in JSON formats.
    """

    def __init__(self, preprocessor: Dict[str, Any]):
        self.preprocessor = preprocessor
        target_map = self.preprocessor["target_mean_encoding"]["target_map"]
        feature_name_out = self.preprocessor["target_mean_encoding"]["feature_name"]
        self.field_name_in = self.preprocessor["target_mean_encoding"]["field"]
        fallback_value = self.preprocessor["target_mean_encoding"]["default_value"]

        def func(column):
            return np.array(
                [
                    target_map[str(category)]
                    if category in target_map
                    else fallback_value
                    for category in column
                ]
            ).reshape(-1, 1)

        def feature_names_out(ft, carr):
            return [feature_name_out if c == self.field_name_in else c for c in carr]

        super().__init__(func=func, feature_names_out=feature_names_out)

class FrequencyEncoder(FunctionTransformer):
    """FunctionTransformer implementation of the frequency encoder, which is
    deserialized from the Elastic ML preprocessor description in JSON format.
    """

    def __init__(self, preprocessor: Dict[str, Any]):
        self.preprocessor = preprocessor
        frequency_map = self.preprocessor["frequency_encoding"]["frequency_map"]
        feature_name_out = self.preprocessor["frequency_encoding"]["feature_name"]
        self.field_name_in = self.preprocessor["frequency_encoding"]["field"]
        fallback_value = 0.0

        def func(column):
            return np.array(
                [
                    frequency_map[str(category)]
                    if category in frequency_map
                    else fallback_value
                    for category in column
                ]
            ).reshape(-1, 1)

        def feature_names_out(ft, carr):
            return [feature_name_out if c == self.field_name_in else c for c in carr]

        super().__init__(func=func, feature_names_out=feature_names_out)

class OneHotEncoder(sklearn.preprocessing.OneHotEncoder):
    """Wrapper for sklearn one-hot encoder, which is deserialized from the
    Elastic ML preprocessor description in JSON format.
    """

    def __init__(self, preprocessor: Dict[str, Any]):
        self.preprocessor = preprocessor
        self.field_name_in = self.preprocessor["one_hot_encoding"]["field"]
        self.cats = [list(self.preprocessor["one_hot_encoding"]["hot_map"].keys())]
        super().__init__(categories=self.cats, handle_unknown="ignore")


import cv2
import numpy as np

input_image = cv2.imread('./image/IMG.jpg')
gray_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
output_image = None

sift = cv2.xfeatures2d.SIFT_create()
keypoints = sift.detect(gray_image, None)

output_image = cv2.drawKeypoints(input_image, keypoints, output_image, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

cv2.imshow('SIFT features', output_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

######

# To detect and compute at the same time
keypoints, descriptors = sift.detectAndCompute(gray_image, None)
print(len(descriptors))
print(descriptors.shape)
print(descriptors[0])


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep  9 17:19:47 2020

@author: pierre
"""
import numpy as np
from egse.state import GlobalState
from egse.coordinates.point import Points

def is_avoidance_ok(hexusr,hexobj,setup=None,verbose=False):
    """
    is_avoidance_ok(hexusr,hexobj,setup=None)

    INPUT
    hexusr : ReferenceFrame
             xy plane = maximal height of the FPA_SEN
             z axis  pointing away from the FPA

    hexobj : ReferenceFrame
             xy plane = FPA_SEN
             z axis pointing towards L6

    setup  : GlobalSetup.setup, optional
             if not provided, GlobalState.setup is used

    OUTPUT :  Boolean indicating wheather or not the FPA is outside of the avoidance volume around L6
    """

    if setup is None:
        setup = GlobalState.setup

    """
    A. HORIZONTAL AVOIDANCE
    Ensure that the center of L6, materialised by HEX_USR (incl. z-direction security wrt TOU_L6)
    stays within a given radius of the origin of FPA_SEN
    """

    # Clearance = the tolerance in every horizontal direction (3 mm; PLATO-KUL-PL-ICD-0001 v1.2)
    clearance_xy = setup.camera.fpa.avoidance.clearance_xy

    # l6xy = the projection of the origin of HEX_USR on the X-Y plane of FPA_SEN
    l6xy = hexusr.getOrigin().expressIn(hexobj)[:2]

    # !! This is a verification of the current situation --> need to replace by a simulation of the forthcoming movement in the building block
    horizontal_check = ((l6xy[0]**2.+l6xy[1]**2.) < clearance_xy*clearance_xy)

    """
    B. VERTICAL AVOIDANCE
    Ensure that the CCD never hits L6.
    The definition of HEX_USR includes a tolerance below L6 (1.65 mm)
    We include a tolerance above FPA_SEN here (0.3 mm)
    We define a collection of points to act at the vertices of the avoidance volume above the FPA
    """

    # Clearance = vertical uncertainty on the CCD location (0.3 mm; PLATO-KUL-PL-ICD-0001 v1.2)
    clearance_z = setup.camera.fpa.avoidance.clearance_z

    # Vertices = Points representing the vertices of the avoidance volume above the FPA (60)
    vertices_nb     = setup.camera.fpa.avoidance.vertices_nb
    # All vertices are on a circle of radius 'vertices_radius' (100 mm)
    vertices_radius = setup.camera.fpa.avoidance.vertices_radius

    angles = np.linspace(0,np.pi * 2,vertices_nb,endpoint=False)
    vertices_x = np.cos(angles) * vertices_radius
    vertices_y = np.sin(angles) * vertices_radius
    vertices_z = np.ones_like(angles) * clearance_z

    # The collection of Points defining the avoidance volume around FPA_SEN
    vert_obj = Points(coordinates=np.array([vertices_x,vertices_y,vertices_z]),ref=hexobj,name="vert_obj")

    # Their coordinates in HEX_USR
    # NB: vert_obj is a Points, vert_usr is an array
    vert_usr = vert_obj.expressIn(hexusr)

    # !! Same as above : this is verifying the current situation, not the one after a planned movement
    # Verify that all vertices ("protecting" FPA_SEN) are below the x-y plane of HEX_USR ("protecting" L6)
    vertical_check = (np.all(vert_usr[2,:] < 0.))

    if verbose:
        printdict = {True:"OK", False:"NOT OK"}
        print(f"HORIZONTAL AVOIDANCE: {printdict[horizontal_check]}")
        print(f" VERTICAL  AVOIDANCE: {printdict[vertical_check]}")

    if verbose > 1:
        print(f"Points Coordinates")
        coobj = vert_obj.coordinates
        for i in range(vertices_nb):
            print(f"{i} OBJ {np.round(coobj[:3,i],6)} --> USR {np.round(vert_usr[:3,i],6)}")
        vert_z = vert_usr[2,:]
        vert_zi = np.where(vert_z==np.max(vert_z))
        print(f"#vertices at max z : {len(vert_zi[0])}")
        print(f"First one: vertex {vert_zi[0][0]} : {np.round(vert_usr[:3,vert_zi[0][0]],6)}")

    return horizontal_check and vertical_check


import pdb
from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import (Layer, Dense, Conv2D, MaxPool2D, Dropout, Flatten,
                                     GlobalAveragePooling2D, ZeroPadding2D)
import tensorflow as tf
import numpy as np

import yaml

class DeepCorrCNN(Model):
    def __init__(
        self,
        conv_filters,
        max_pool_sizes,
        strides,
        dense_layers,
        drop_p,
        debug=False,
    ):

        '''
        conv_filters: filters for the first two conv layers
        dense_layers: units for the last dense layers
        drop_p: dropout rate
        '''
        super().__init__(self)
        self.debug = debug
        # self.convs = Sequential(
        #     [
        #         Conv2D(conv_filters[0], [2, 20], strides=2, activation="relu"),
        #         MaxPool2D([1, 5]),
        #         Conv2D(conv_filters[1], [4, 10], strides=2, activation="relu"),
        #         MaxPool2D([1, 3]),
        #     ]
        # )

        layers = [x
            for (conv_filter, (kernel_win, kernel_size)), (stride1, stride2), maxpool_size in zip(
                    conv_filters, strides, max_pool_sizes
            )
            for x in (
                Conv2D(conv_filter, (kernel_win, kernel_size), strides=(stride1, stride2), activation="relu"),
                MaxPool2D((1, maxpool_size)),
            )]

        #print(layers)

        self.convs = Sequential(layers)

        self.flatten = Flatten()
        self.dense = Sequential()
        for i, units in enumerate(dense_layers):
            self.dense.add(
                Dense(units, activation=("relu" if i < len(dense_layers) - 1 else None))
            )
            if i < len(dense_layers) - 2:
                self.dense.add(Dropout(drop_p))
        self.dense.add(Dense(1, activation=None))

    def call(self, x):
        x = self.convs(x)
        x = self.flatten(x)
        y = self.dense(x)
        if self.debug:
            self.convs.summary()
            self.dense.summary()
        return y

    def get_activations(self, x, name, debug=False):
        y = self.convs.get_layer(name)(x)
        if debug:
            self.convs.summary()
            self.dense.summary()
        return y


import os

import numpy as np

cur_dir = os.path.dirname(__file__)

def load_data():
    def loadtxt(filepath):
        with open(filepath, 'r') as f:
            arr = np.loadtxt(f)
        x = arr[:, :-1]
        y = arr[:, -1].astype(np.int32)
        return x, y

    x_train, y_train = loadtxt(os.path.join(cur_dir, 'train.txt'))
    x_test, y_test = loadtxt(os.path.join(cur_dir, 'test.txt'))

    return (x_train, y_train), (x_test, y_test)


"""
	Modification of Ivmech's PID Controller (https://github.com/ivmech/ivPID) to fit my custom needs.
	File contains two classes:
	 - PID: Implements a basic PID loop, with added features like error bounding, output bounding, I_max,
		option for error sign inversion, option to treat the error in degrees (-180, 180]...
	 - PIDposAndVel: Implements a basic PIV loop (Proportional position loop + Integral and proportional Velocity loop).
		The idea is: a position PID reads current position and determines desired velocity to reach its set-point pos.
		Then, the output of that PID controller (desired velocity) is used as the set-point for the second PID loop,
		which looks at current velocity and acts upon it by providing a reaction acceleration.
"""

from datetime import datetime, timedelta

class PID:
	"""
		Simple PID Controller, with added features like error bounding, output bounding, I_max,
		option for error sign inversion, option to treat the error in degrees (-180, 180]...
	"""

	def __init__(self, P=0, I=0, D=0, set_point=0, offs=0, out_max=float('Inf'), I_max=float('Inf'), error_max=float('Inf'), invert_error=False, error_in_degrees=False, is_interval_const=False):
		self.clear()

		self.Kp = P
		self.Ki = I
		self.Kd = D

		self.SetPoint = set_point
		self.out_offs = self.output = offs
		self.out_max = out_max
		self.I_max = I_max
		self.error_max = error_max
		self.invert_error = invert_error
		self.error_in_degrees = error_in_degrees
		self.curr_input = self.last_input = 0

		self.sample_time = 0.0
		self.curr_time = self.last_time = datetime.now()
		self.is_interval_const = is_interval_const

		self.PTerm = self.ITerm = self.DTerm = 0.0
		self.curr_error = self.last_error = 0.0
		self.clearing = True

	def clear(self):
		"""Clears PID computations and coefficients"""
		self.PTerm = 0.0
		self.ITerm = 0.0
		self.DTerm = 0.0
		self.clearing = True

		self.output = 0.0

	def update(self, feedback_value, t=None):
		"""Calculates PID value for given reference feedback
			u(t) = K_p e(t) + K_i \int_{0}^{t} e(t)dt + K_d {de}/{dt}
		"""
		if t is None: t = datetime.now()

		self.last_time = self.curr_time
		self.last_input = self.curr_input
		self.last_error = self.curr_error
		self.curr_time = t
		self.curr_input = feedback_value
		self.curr_error = self.SetPoint - feedback_value

		if self.invert_error: self.curr_error = -self.curr_error
		if self.error_in_degrees:
			self.curr_error %= 360
			while self.curr_error < -180: self.curr_error += 360
			while self.curr_error > 180: self.curr_error -= 360  # Back to (-180, 180] range
		self.curr_error = min(self.error_max, max(-self.error_max, self.curr_error))

		if self.clearing:  # If the method clear() was just called, force delta_error=0 and delta_time=0 -> ITerm = DTerm = 0
			delta_time = 0
			delta_error = 0
			self.clearing = False
		else:
			if self.is_interval_const:
				self.curr_time = self.last_time + self.sample_time + timedelta(milliseconds=25)  # Add 25ms so delta_time is never 0 (not even if sample_time=0), so that D component is not always 0
			delta_time = (self.curr_time - self.last_time).total_seconds()
			delta_error = self.curr_error - self.last_error
		if delta_time < self.sample_time: return self.output

		self.PTerm = self.Kp * self.curr_error
		self.ITerm = min(self.I_max, max(-self.I_max, self.ITerm + self.curr_error*delta_time))
		self.DTerm = 0.0 if delta_time<=0 else delta_error/delta_time

		self.output = self.out_offs + min(self.out_max, max(-self.out_max, self.PTerm + (self.Ki*self.ITerm) + (self.Kd*self.DTerm)))
		return self.output

	def setKp(self, proportional_gain):
		"""Determines how aggressively the PID reacts to the current error with setting Proportional Gain"""
		self.Kp = proportional_gain

	def setKi(self, integral_gain):
		"""Determines how aggressively the PID reacts to the current error with setting Integral Gain"""
		self.Ki = integral_gain

	def setKd(self, derivative_gain):
		"""Determines how aggressively the PID reacts to the current error with setting Derivative Gain"""
		self.Kd = derivative_gain

	def setSetPoint(self, set_point, clearPID=False):
		"""Sets the desired value we want the process value (PV) to hold"""
		self.SetPoint = set_point
		if (clearPID): self.clear()

	def setOffset(self, offset):
		"""Determines the desired output value that holds the process value (PV) stable at the SetPoint (ie, error=0)"""
		self.out_offs = offset

	def setOutMax(self, out_max):
		"""Sets the maximum (and minimum) value of the Manipulated Variable (MV or output).
		If lower_bound is bool, the minimum value is set to -upper_bound.
		Otherwise, the value of lower_bound is taken as in (eg, float)"""
		self.out_max = out_max

	def setImax(self, I_max):
		"""
		Integral windup, also known as integrator windup or reset windup, refers to the situation in a PID feedback controller
		where a large change in setpoint occurs (say a positive change) and the integral terms accumulates a significant error
		during the rise (windup), thus overshooting and continuing to increase as this accumulated error is unwound
		(offset by errors in the other direction). The specific problem is the excess overshooting.
		"""
		self.I_max = I_max

	def setErrorMax(self, error_max):
		"""Determines the maximum (absolute value) error considered (ie, any error>error_max will be clipped to error=error_max)"""
		self.error_max = error_max

	def setSampleTime(self, sample_time):
		"""
		PID that should be updated at a regular interval.
		Based on a pre-determined sample time, the PID decides if it should compute or return immediately.
		"""
		self.sample_time = sample_time

class PIDposAndVel:
	"""
		Structure of 2 PID loops (PIV controller), where the output of one (position)
		is used as the set-point for the other (velocity)
	"""

	def __init__(self, posP=0, posI=0, posD=0, pos_set_point=0, pos_offs=0, pos_out_max=float('Inf'), pos_I_max=float('Inf'), pos_error_max=float('Inf'), pos_invert_error=False,
				 velP=0, velI=0, velD=0, vel_set_point=0, vel_offs=0, vel_out_max=float('Inf'), vel_I_max=float('Inf'), vel_error_max=float('Inf'), vel_invert_error=False, vel_invert_input=False, error_in_degrees=False, is_interval_const=False, max_vel=300):
		self.PIDpos = PID(posP, posI, posD, pos_set_point, pos_offs, pos_out_max, pos_I_max, pos_error_max, pos_invert_error, error_in_degrees, is_interval_const)
		self.PIDvel = PID(velP, velI, velD, vel_set_point, vel_offs, vel_out_max, vel_I_max, vel_error_max, vel_invert_error, error_in_degrees, is_interval_const)
		self.vel = 0
		self.invert_vel = vel_invert_input
		self.max_vel = max_vel

	def clear(self):
		self.PIDpos.clear()
		self.PIDvel.clear()

	def update(self, feedback_value, t=None):
		self.PIDpos.update(feedback_value, t)
		self.PIDvel.SetPoint = self.PIDpos.output
		self.PIDvel.update(self.getCurrVel(), t)

		return self.PIDvel.output

	def setSetPoint(self, set_point):
		self.PIDpos.SetPoint = set_point

	def getSetPoint(self):
		return self.PIDpos.SetPoint

	def getOutput(self):
		return self.PIDvel.output

	def getCurrPos(self):
		return self.PIDpos.curr_input

	def getLastPos(self):
		return self.PIDpos.last_input

	def getCurrVel(self):
		inv_factor = -1 if self.invert_vel else 1
		delta_time = (self.PIDpos.curr_time - self.PIDpos.last_time).total_seconds()

		if delta_time <= 0:
			self.vel = 0
		else:
			alpha = 0.5
			self.vel = (1-alpha)*self.vel + alpha*min(self.max_vel, max(-self.max_vel, inv_factor*(self.PIDpos.curr_input-self.PIDpos.last_input)/delta_time))

		return self.vel


from gevent import monkey
from flask import Flask, render_template, request
import random

monkey.patch_all()

app = Flask(__name__)

message_list = []
db = dict()
db['connected'] = 0
username = 'Unnamed User ' + str(random.randint(0, 123456))

@app.route('/')
def chat():
    return render_template('chat.html')

@app.route('/chat')
def ws_conn():
    db['connected'] = db['connected'] + 1
    c = db['connected']
    return c

@app.route('/getmessages')
def get_msg():
    global message_list
    response=''
    for iterator in message_list:
        response=response+'<h3>' + iterator + '<h3>'
    return response

@app.route('/postmessages',methods=['POST'])
def post_msg():
    global message_list
    message_list.append(username + ' : ' + request.get_json())
    return username + ' : ' + request.get_json()

@app.route('/setname',methods=['POST'])
def set_name():
    global username
    username = request.get_json()
    return username

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080, debug=True)


from sqlalchemy import text
from nltk.corpus import wordnet as wn
from nltk.stem import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
from portmanteau import Portmanteau
from rhyme import Rhyme
from app.models import FasttextNeighbor
from global_constants import GRAPHEME_BLACKLIST

def alternate_capitalizations(grapheme):
    '''
    For a given grapheme, returns a list containing:
    1) the grapheme as-is
    2) the grapheme all-lower-cased
    3) the grapheme all-lowercased except for the first letter, which is capitalized
    '''
    capitalization_alternatives = [grapheme]
    capitalization_alternatives.append(grapheme.lower())
    if len(grapheme) == 1:
        capitalization_alternatives.append(grapheme[0].upper())
    elif len(grapheme) > 1:
        capitalization_alternatives.append(grapheme[0].upper()+grapheme[1:].lower())
    return capitalization_alternatives

def get_shortest_lemma(grapheme, lemmatizer=WordNetLemmatizer(), stemmer=PorterStemmer()):
    '''
    Don't want to produce multiple portmanteaus/rhymes where one of the words differs only by its e.g. pluralization
    Therefore for each grapheme, identify its shortest lemma or stem (assuming that the stem is a valid word)

    Because WordNet classifies words by part-of-speech, we need to check check all possible POS's to make sure that
    the *shortest* lemma has been found. If we manually check all parts of speech, it defaults to using the lemmas
    associated with the first synset, which may not be what we want.

    The parts of speech recognized by WordNet are:
      n : NOUN
      v : VERB
      a : ADJECTIVE
      s : ADJECTIVE SATELLITE
      r : ADVERB

    Note: For efficiency, we instantiate the lemmatizer in advance, so that it doesn't need to be reinstantiated on each run
    '''

    shortest_lemma = grapheme

    # First attempt to trim using lemmatizer
    # Be sure to check all parts-of-speech for lemmas
    for pos in ['n','v','a','s','r']:
        lemma = lemmatizer.lemmatize(grapheme, pos)
        if len(lemma) < len(shortest_lemma):
            shortest_lemma = lemma

    # Next attempt to trim using stemmer; further trim down whatever was produced by the lemmatizer
    # Stems are not always valid words, so verify that the result is present in WordNet
    stem = stemmer.stem(shortest_lemma)
    if len(wn.synsets(stem)) >= 1 and len(stem) < len(shortest_lemma):
        shortest_lemma = stem

    return shortest_lemma

# TODO: refactor so this function is a classmethod of FasttextVector
def get_semantic_neighbor_graphemes(grapheme):
    '''
    Fetch the precomputed n=100 nearest neighbors to the given grapheme
    '''
    # Possible that the input was only allowed through because an ALTERNATE capitalization was valid, i.e. 'robocop' matched 'Robocop'
    grapheme_alternatives = alternate_capitalizations(grapheme)

    for this_grapheme in grapheme_alternatives:
        # Precomputed top-100 neighbors
        fasttext_neighbor_graphemes_row = FasttextNeighbor.query.filter_by(grapheme=this_grapheme).first()
        # If this capitalization variant matched, then keep it and move on
        if fasttext_neighbor_graphemes_row:
            fasttext_neighbor_graphemes = fasttext_neighbor_graphemes_row.neighbors
            break

    # FastText sometimes returns funky unicode characters like umlouts, so make sure to catch/discard these before continuing
    fasttext_neighbor_graphemes_clean = []
    for g in fasttext_neighbor_graphemes:
        try:
            fasttext_neighbor_graphemes_clean.append(str(g))
        except:
            pass

    # For each neighbor grapheme, perform the following operations:
    # 1) downcase
    # 2) find shortest lemma or valid stem
    # 3) deduplicate
    semantic_neighbor_graphemes = map(lambda g: get_shortest_lemma(g.lower()), fasttext_neighbor_graphemes_clean)
    semantic_neighbor_graphemes = set(semantic_neighbor_graphemes)

    return semantic_neighbor_graphemes

def get_portmanteaus(words1_neighbors, words2_neighbors):
    '''
    Given a two lists of words, attempt to construct portmanteaus out of each of the
    |words1_neighbors| x |words2_neighbors| many word pairs. Order the generated portmanteaus
    by quality before returning.
    '''
    # Store the results using a set to avoid duplicates in case the same words appears in both sets
    portmanteau_set = set()
    for neighbor1 in words1_neighbors:
        for neighbor2 in words2_neighbors:
            # If the words are identical, or one of the graphemes is black-listed, skip this word pair
            if neighbor1.grapheme == neighbor2.grapheme or neighbor1.grapheme.lower() in GRAPHEME_BLACKLIST or neighbor2.grapheme.lower() in GRAPHEME_BLACKLIST:
                continue
            # Generate forward-ordered portmanteau
            portmanteau, status, message = Portmanteau.get_pun(neighbor1, neighbor2)
            if status == 0 and portmanteau.ordering_criterion() < Portmanteau.ORDERING_CRITERION_CUTOFF:
                portmanteau_set.add(portmanteau)
            # Generate reverse-ordered portmanteau
            portmanteau, status, message = Portmanteau.get_pun(neighbor2, neighbor1)
            if status == 0 and portmanteau.ordering_criterion() < Portmanteau.ORDERING_CRITERION_CUTOFF:
                portmanteau_set.add(portmanteau)

    # Order the results in terms of portmanteau quality, with better portmanteaus appearing earlier
    portmanteau_list = list(portmanteau_set)
    portmanteau_list.sort(key=lambda x: x.ordering_criterion())

    return portmanteau_list

def get_rhymes(words1_neighbors, words2_neighbors):
    '''
    Given a two lists of words, attempt to construct rhyme out of each of the
    |words1_neighbors| x |words2_neighbors| many word pairs. Order the generated rhymes
    by quality before returning.
    '''
    # Store the results using a set to avoid duplicates in case the same words appears in both sets
    rhyme_set = set()
    for neighbor1 in words1_neighbors:
        for neighbor2 in words2_neighbors:
            # If the words are identical, or one of the graphemes is black-listed, skip this word pair
            if neighbor1.grapheme == neighbor2.grapheme or neighbor1.grapheme.lower() in GRAPHEME_BLACKLIST or neighbor2.grapheme.lower() in GRAPHEME_BLACKLIST:
                continue
            # Generate the rhyme for only a single ordering, if the words need to be flipped
            # for quality reasons, that's handled within the 'get_rhyme' function
            rhyme, status, message = Rhyme.get_pun(neighbor1, neighbor2)
            if status == 0:
                rhyme_set.add(rhyme)

    # Order the results in terms of rhyme quality, with better rhymes appearing earlier
    rhyme_list = list(rhyme_set)
    rhyme_list.sort(key=lambda x: x.ordering_criterion())

    return rhyme_list


# coding=utf-8

import xlrd
import pandas as pd
import numpy as np

df=pd.read_excel('a_2.xls')
height,width = df.shape
print(height,width,type(df))

x = np.zeros((height,width))
nameList = []
personIdList = []
phoneList = []
apptime = []
arrtime = []
enttime = []
sitId = []
for i in range(0,height):
    tpName = df.values[i][0]
    a1 = tpName.replace(tpName[0],'*')
    tpId = df.values[i][1]
    a2 = tpId.replace(tpId[14:18],'****')
    tpphone = str(df.values[i][2])
    a3 = tpphone.replace(tpphone[7:11],'****')
    tpapp = df.values[i][3]
    tparr = df.values[i][4]
    tpend = df.values[i][5]
    # tpsit = df.values[i][6]
    nameList.append(str(a1))
    personIdList.append(str(a2))
    phoneList.append(str(a3))
    apptime.append(str(tpapp))
    arrtime.append(str(tparr))
    enttime.append(str(tpend))
    # sitId.append(str(tpsit))
    print(i)

# name_to_list = {'姓名': nameList,'身份证':personIdList,'手机号':phoneList,
#                 '预约日期': apptime, '预约到馆时间':arrtime,'入馆时间':enttime,'座位号':sitId}
name_to_list = {'姓名': nameList,'身份证':personIdList,'手机号':phoneList,
                '预约日期': apptime, '预约到馆时间':arrtime,'入馆时间':enttime}
df = pd.DataFrame(data=name_to_list)
df.to_csv('sheet_2.csv', encoding='utf_8_sig')