from notion.client import NotionClient
from notion.space import Space
import os
import sys
import json

# Note that this token is the cookie token you can get from your browser. This is how you access the private API.
try:
    TOKEN = os.environ['NOTION_TOKEN_V2']
except Exception as err:
    raise RuntimeError(
        'NOTION_TOKEN_V2 environment variable must be defined.') from err

# instantiate new notion client
client = NotionClient(token_v2=TOKEN)
user_id = client.current_user.id

def sync_record_values(table, id):
    res = client.post('syncRecordValues', {
        'requests': [{
            "pointer": {
                "table": table,
                "id": id
            },
            "version": -1
        }]
    }).json()
    print(res)

# NOTE This is somewhat just for dev... it makes sense in prod but I have no
# tests, so no gaurantees that it will actually work as expected.
cache = {}

# Given that the root is such a grab back of stuff I suspect it is more likely to change than some of the other routes
def get_root(force=False):
    if 'getSpaces' in cache and not force:
        return cache['getSpaces']

    res = client.post('getSpaces', {}).json()
    root = res[user_id]
    cache['getSpaces'] = root

    return root

def get_pages(root):
    pages = [
        v['value'] for _, v in root['block'].items()
        if v['value']['type'] == 'page'
    ]
    return pages

def get_in(d, key_path, not_found=None):
    result = d

    for k in key_path:
        if k in result:
            result = result[k]
        else:
            return not_found

    return result

def format_page(page):
    try:
        title = page['properties']['title']
    except KeyError:
        title = None

    try:
        icon = page['format']['page_icon']
    except KeyError:
        icon = None

    try:
        last_edited_time = page['last_edited_time']
    except KeyError:
        last_edited_time = None

    return {'title': title, 'icon': icon, 'last_edited_time': last_edited_time}

def get_spaces(root, force=False):
    xs = root['user_root'][user_id]['value']['space_view_pointers']
    space_ids = [x['spaceId'] for x in xs]

    if 'getPublicSpaceData' in cache and not force:
        return cache['getPublicSpaceData']

    res = client.post('getPublicSpaceData', {
        'spaceIds': space_ids,
        'type': 'space-ids'
    }).json()
    xs = res['results']
    cache['getPublicSpaceData'] = xs
    return xs

# def get_space_ids():
#     res = client.post(
#         'syncRecordValues', {
#             'requests': [{
#                 "pointer": {
#                     "table": "user_root",
#                     "id": user_id
#                 },
#                 "version": -1
#             }]
#         }).json()
#     xs = res['recordMap']['user_root'][user_id]['value']['space_view_pointers']
#     space_ids = [x['spaceId'] for x in xs]
#     return space_ids

def main():
    print('Authenticated as:', client.current_user.email, file=sys.stderr)
    # sync_record_values("user_root", client.current_user.id)

    print('Spaces:')
    for x in get_spaces():
        print(x['id'], x['name'])

# if the module was called directly
if __name__ == '__main__':
    main()


# from sklearn.cluster import DBSCAN
# import numpy as np
# X = np.array([[1, 2,3], [2, 2,2], [2, 3,2],[8, 7,2], [8, 8,3], [25, 80,4]])
# clustering = DBSCAN(eps=3, min_samples=2).fit(X)
# print(clustering.labels_)

# def plot_tsne(array_to_plot, labels):
#     import pandas as pd
#     from sklearn.manifold import TSNE
#     import matplotlib.pyplot as plt
#     import seaborn as sns
#
#     feat_cols = ['pixel' + str(i) for i in range(len(array_to_plot))]
#     df = pd.DataFrame(array_to_plot, columns=feat_cols)
#     df['y'] = labels
#     df['label'] = df['y'].apply(lambda i: str(i))
#     tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=300)
#     tsne_results = tsne.fit_transform(df)
#     print('t-SNE done!')
#     map_to_pd = {'tsne-2d-one': tsne_results[:, 0], 'tsne-2d-two': tsne_results[:, 1]}
#     df = pd.DataFrame(map_to_pd)
#     plt.figure(figsize=(16, 10))
#     sns.scatterplot(
#         x="tsne-2d-one", y="tsne-2d-two",
#         hue="y",
#         palette=sns.color_palette("hls", 10),
#         data=df,
#         legend="full",
#         alpha=0.3
#     )
#
#
# plot_tsne([[1, 2, 3], [1, 2, 4], [10, 20, 30, 40, 50], [100, 200]], [1, 1, 2, 3])

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

X = np.array([[5, 3],
              [10, 15],
              [15, 12],
              [24, 10],
              [30, 30],
              [85, 70],
              [71, 80],
              [60, 78],
              [70, 55],
              [80, 91], ])

from sklearn.cluster import AgglomerativeClustering

cluster = AgglomerativeClustering(n_clusters= 2,  affinity='euclidean', linkage='ward')
cluster.fit_predict(X)
print(cluster.labels_)
plt.scatter(X[:, 0], X[:, 1], c=cluster.labels_, cmap='rainbow')
plt.show()

import scipy.cluster.hierarchy as shc

plt.figure(figsize=(10, 7))
plt.title("Customer Dendograms")
dend = shc.dendrogram(shc.linkage(X, method='ward'))
plt.show()


import math
from math import sqrt

class Complex(object):

    def __init__(self, real, imag=0.0):
        self.real = real
        self.imag = imag
        # Formats our results
        print(self.real + self.imag)

    def __add__(self, other):
        print('\nSum:')
        return Complex(self.real + other.real, self.imag + other.imag)

    def __sub__(self, other):
        print('\nDifference:')
        return Complex(self.real - other.real, self.imag - other.imag)

    def __mul__(self, other):
        print('\nProduct:')
        return Complex((self.real * other.real) - (self.imag * other.imag),
                       (self.imag * other.real) + (self.real * other.imag))

i = Complex(2, 10j)
k = Complex(3, 5j)
i + k
i - k
i * k


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

import sys, os
sys.path.append("/home/matt/git/tiers-lieux/code")
import utils
import geopandas as gpd
import pandas as pd
import router
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import yaml
import osmnx as ox

mpl.rcParams['figure.figsize'] = [15, 15]

conf_file = sys.argv[1]
with open(conf_file, "r") as yml_file:
        cfg = yaml.safe_load(yml_file)
data_path = os.path.abspath(cfg["data_path"])
processed_path = os.path.abspath(cfg["processed_path"])
departments = cfg["departments"]
iso = cfg["isochrone"]

presel_func = None
if "preselection" in cfg.keys():
    presel_func = cfg["preselection"]

sub_territories = cfg["sub_territories"]
sub_processed_paths = []
sub_muni_origs = []
for territories_conf in sub_territories:
        with open(territories_conf, "r") as yml_file:
            sub_cfg = yaml.safe_load(yml_file)
        sub_muni_origs.append(utils.load_muni_list(sub_cfg))
        sub_processed_paths.append(sub_cfg["processed_path"])

r = router.Router(cfg)
saved_df_w = r.get_saved_distance(presel_func)
saved_df = saved_df_w.drop("weight", axis=1)
weight = saved_df_w["weight"]
nb_persons = weight.sum()

municipalities = gpd.read_file(f"{processed_path}/communes.gpkg")
muni_orig = utils.load_muni_list(cfg)
if muni_orig:
    municipalities = municipalities[municipalities["commune_id"].isin(muni_orig)]

municipalities["department"] = municipalities["commune_id"].str[:2]
departments = municipalities.dissolve("department").reset_index()
dep_name = pd.read_csv(f"{data_path}/departements-france.csv")
departments = departments.merge(dep_name, left_on="department", right_on="code_departement", how="left")
departments.rename(columns={"nom_departement":"label"}, inplace=True)
departments = departments[["label", "department", "geometry"]]

persons_df = pd.read_feather(f"{processed_path}/persons.feather")
density_df = pd.DataFrame(persons_df.groupby("origin_id")["weight"].sum())
density_df = density_df.reset_index().rename(columns={"origin_id":"commune_id",
                                                      "weight":"density"})
municipalities = pd.merge(municipalities, density_df, on="commune_id",
                            how="left").fillna(0)
municipalities["density"] = municipalities["density"].astype(int)

solver_res_path = f"{processed_path}/solver_res_iso{iso}.txt"
with open(solver_res_path) as f:
    l = f.readline()
    res = eval(l.strip())

#base map
cmap = mpl.cm.Blues(np.linspace(0,1,20))
cmap = mpl.colors.ListedColormap(cmap[5:,:-1])
m = municipalities[municipalities["density"]!=0]
#ax = m.plot(column="density", cmap=cmap, legend=True, scheme='user_defined', classification_kwds={'bins':[10,100,500,2000]})
ax = m.plot(column="density", cmap=cmap, legend=True, scheme="JenksCaspall", k=6, zorder=1)
ax.get_legend().set_title("Population")
departments.plot(ax=ax, facecolor='none', edgecolor='black', linewidth=1, zorder=2)
for sub_muni_orig in sub_muni_origs:
    sub_municipalities = municipalities[municipalities["commune_id"].isin(sub_muni_orig)]
    sub_municipalities.dissolve().plot(ax=ax, facecolor='none', edgecolor='black', linewidth=2, zorder=3)

#road network
path = f"{processed_path}/graph.graphml"
if os.path.exists(path):
    print("Loading road network")
    graph = ox.load_graphml(path)
else:
    print("Downloading road network")
    area = m.dissolve().to_crs(4326)
    cf = '["highway"~"motorway|trunk|primary|secondary"]'
    graph = ox.graph_from_polygon(area.geometry[0], network_type="drive", retain_all=True, truncate_by_edge=True, clean_periphery=True, custom_filter=cf)
    graph = ox.projection.project_graph(graph, to_crs=2154)
    ox.save_graphml(graph, filepath=path)
nodes, roads = ox.graph_to_gdfs(graph)
roads[roads.highway!="secondary"].plot(ax=ax, color="white", linewidth=1, alpha=0.4, zorder=3)
roads[roads.highway=="secondary"].plot(ax=ax, color="white", linewidth=0.5, alpha=0.4, zorder=4)

#municipalities
chosen = res[1]
if presel_func:
    preselected_muni = municipalities[municipalities["commune_id"].isin(saved_df.columns
    )].copy()
    preselected_muni["geometry"] = preselected_muni.centroid
    preselected_muni.plot(ax=ax, color="orange", linewidth=3, zorder=10)
chosen_muni = municipalities[municipalities["commune_id"].isin(res[1])].copy()
chosen_muni["geometry"] = chosen_muni.centroid
chosen_muni.plot(ax=ax, color="red", linewidth=5, zorder=20)

sub_processed_chosen = []
for sub_processed_path in sub_processed_paths:
    solver_res_path = f"{sub_processed_path}/solver_res_iso{iso}.txt"
    with open(solver_res_path) as f:
        l = f.readline()
        res = eval(l.strip())
    sub_processed_chosen.extend(res[1])
    chosen_muni = municipalities[municipalities["commune_id"].isin(res[1])].copy()
    chosen_muni["geometry"] = chosen_muni.centroid
    chosen_muni.plot(ax=ax, color="yellow", linewidth=1, zorder=20)
plt.axis('off')
plt.savefig(f"{processed_path}/multi-scale-map_iso{iso}.png", bbox_inches='tight')


'''
* Author:  Dyuthi Pedaballi
'''
""" j is replaced by i, "X" is inserted between repeated
letters and also used for padding if the plaintext has an odd length"""

#remove spaces and duplictae letters from teh key
ikey = "first"
def removekeydups(ikey):
    ikey = ikey.replace(" ","")
    key = ""
    for letter in ikey:
        if letter not in key:
           key = key + letter
    return key

key = removekeydups(ikey)

def keytable(key):

    alphabet = "abcdefghijKLmnopqrstuvwxyz"
    alphabet = alphabet.lower()
    alphabet = alphabet.replace("j", "i")
    keytable = ""
    for letter in alphabet:
      if letter not in key:
          if letter not in keytable:
           keytable = keytable+letter
    keytable = key+keytable
    return(keytable)

#Creating a keymatrix, by including in it distinct letters in key and alphabet
def keysquare():

   keyref = keytable(key)
   keylist = []
   keylist1 = []
   keylist2 = []
   keylist3 = []
   keylist4 = []
   keylist5 = []

   row1 = keyref[0:5]
   for ch in row1:
     keylist1.append(ch)

   row2 = keyref[5:10]
   for ch in row2:
     keylist2.append(ch)

   row3 = keyref[10:15]
   for ch in row3:
     keylist3.append(ch)

   row4 = keyref[15:20]
   for ch in row4:
     keylist4.append(ch)

   row5 = keyref[20:25]
   for ch in row5:
     keylist5.append(ch)

   keylist.append(keylist1)
   keylist.append(keylist2)
   keylist.append(keylist3)
   keylist.append(keylist4)
   keylist.append(keylist5)

   return keylist
iplaintext = "hi there dyuthi"

"""Removing spaces from the plaintext and appending with "x"
in case of odd length plaintext"""

def cleanplaintext(iplaintext):
    if " " in iplaintext:
     iplaintext = iplaintext.replace(" ","")
    mplaintext = ""

    for letindex in range(len(iplaintext)-1):

         if iplaintext[letindex] == iplaintext[letindex+1]:
            mplaintext =  mplaintext+iplaintext[letindex]+"x"
         else:
            mplaintext = mplaintext+iplaintext[letindex]

    mplaintext = mplaintext+iplaintext[-1]
    return mplaintext

space = []
for index in range(len(iplaintext)):
    if iplaintext[index] == " ":
     space.append(index)

#Splitting the plaintext into pairs
def makedigraps():
    char = []
    mplaintext = cleanplaintext(iplaintext)
    plaintext = ""
    if len(mplaintext)%2 == 0:
        plaintext = mplaintext
    else:
        plaintext = mplaintext+"x"

    for ch in plaintext:
        char.append(ch)

    digraph = []

    for index in range(0,len(char),2):
      digraph.append(char[index:index+2])
    return digraph

#Encrypts message by using the three rules
def encrypttext():

    keymatrix = keysquare()
    char = makedigraps()
    ciphertext = []
    index1 = 0
    index2 = 0
    index3 = 0
    index4 = 0
    for ch in char:
        for i in range(len(keymatrix)):
            for j in range(len(keymatrix)):
              if ch[0] == keymatrix[i][j]:
                index1 = i
                index2 = j
                j =0
                i =0

        for i in range(len(keymatrix)):
            for j in range(len(keymatrix)):
               if ch[1] == keymatrix[i][j]:
                         index3 = i
                         index4 = j

        if index1==index3:

                 if index2 == 4:
                     index2= 0
                     ciphertext.append(keymatrix[index1][index2])
                     ciphertext.append(keymatrix[index3][index4+1])
                 elif index4 == 4:
                      index4 = 0

                      ciphertext.append(keymatrix[index1][index2+1])
                      ciphertext.append(keymatrix[index3][index4])
                 else:
                      ciphertext.append(keymatrix[index1][index2+1])
                      ciphertext.append(keymatrix[index3][index4+1])

        elif index2 == index4:
                    if index1 == 4:
                        index1 = 0
                        ciphertext.append(keymatrix[index1][index2])
                        ciphertext.append(keymatrix[index3+1][index4])
                    elif index3 == 4:
                        index3 = 0
                        ciphertext.append(keymatrix[index1][index2])
                        ciphertext.append(keymatrix[index3+1][index4])
                    else:
                        ciphertext.append(keymatrix[index1+1][index2])
                        ciphertext.append(keymatrix[index3+1][index4])
        else:
                     ciphertext.append(keymatrix[index1][index4])
                     ciphertext.append(keymatrix[index3][index2])
    if " " in iplaintext:
     for index in range(len(space)):
      ciphertext.insert(space[index]," ")

    cipherstr = "".join(ciphertext)

    print("The ciphertext for the given plaintext:",cipherstr)
    return cipherstr

#decrypts message by using the three rules
def decrypttext():
    cipher = encrypttext()
    cipheros = cipher.replace(" ","")
    cipherdi = []
    for index in range(0,len(cipheros),2):
        cipherdi.append(cipheros[index:index+2])

    keymatrix = keysquare()
    plaintextc = []
    index1 = 0
    index2 = 0
    index3 = 0
    index4 = 0
    for ch in cipherdi:
        for i in range(len(keymatrix)):
            for j in range(len(keymatrix)):
              if ch[0] == keymatrix[i][j]:
                index1 = i
                index2 = j
                j =0
                i =0
        for i in range(len(keymatrix)):
            for j in range(len(keymatrix)):
               if ch[1] == keymatrix[i][j]:
                         index3 = i
                         index4 = j

        if index1==index3:

                 if index2 == 0:
                     index2= 4
                     plaintextc.append(keymatrix[index1][index2])
                     plaintextc.append(keymatrix[index3][index4-1])
                 elif index4 == 0:
                      index4 = 4
                      plaintextc.append(keymatrix[index1][index2-1])
                      plaintextc.append(keymatrix[index3][index4])
                 else:
                      plaintextc.append(keymatrix[index1][index2-1])
                      plaintextc.append(keymatrix[index3][index4-1])

        elif index2 == index4:
                    if index1 == 0:
                        index1 = 4
                        plaintextc.append(keymatrix[index1][index2])
                        plaintextc.append(keymatrix[index3][index2])
                    elif index3 == 0:
                        index3 = 4
                        plaintextc.append(keymatrix[index1][index2])
                        plaintextc.append(keymatrix[index3-1][index4])
                    else:
                        plaintextc.append(keymatrix[index1-1][index2])
                        plaintextc.append(keymatrix[index3-1][index4])
        else:
                     plaintextc.append(keymatrix[index1][index4])
                     plaintextc.append(keymatrix[index3][index2])

    if "x" in plaintextc:
      plaintextc.remove("x")
    if " " in cipher:
        for index in range(len(space)):
           plaintextc.insert(space[index]," ")
    plainstr = "".join(plaintextc)

    print("The plaintext for the given ciphertext:",plainstr)

decrypttext()


"""
https://www.hackerrank.com/contests/projecteuler/challenges/euler016
Project Euler #16: Power digit sum
"""
#!/bin/python3

for _ in range(int(input())):
    num = list(str(2**int(input())))
    print(sum([int(x) for x in num]))


import cv2
import time

cap=cv2.VideoCapture(0)

start=0
fps=0

while True:
    rec,frame = cap.read()

    end=time.time()
    diff=end-start
    fps=1/diff
    start=end

    fps_text="pfs:{:.2f}".format(fps)
    cv2.putText(frame, fps_text, (5,30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255,255),1)

    cv2.imshow("webcam",frame)
    key=cv2.waitKey(1)

    if key == 81 or key == 113:   #q to quit
        break
cap.release()

print('complete')


import scrapy

from hello05.items import Hello05Item

class PCHomeSpider(scrapy.Spider):
    name = "hello05"

    def start_requests(self):
        urls = [
            'http://24h.pchome.com.tw/index/',
          ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self,response):
        item = Hello05Item()

        for i  in range(1,6):
            str_idx   = ''+('%s'%i)
            str_xpath = '//*[@id="hot_list"]/dl/dd[2]/ul/li['+str_idx+']/div/h5/a//text()'
            titleList = response.xpath(str_xpath).extract()
            strTitle  = ''.join(titleList)
            str_xpath = '//*[@id="hot_list"]/dl/dd[2]/ul/li['+str_idx+']/div/h5/a//@href'
            urlList   = response.xpath(str_xpath)[0].extract()
            strUrl    = ''.join(urlList)

            str_xpath = '//*[@id="hot_list"]/dl/dd[2]/ul/li['+str_idx+']/div/h6/strong/a//text()'
            priceList = response.xpath(str_xpath).extract()
            strPrice = ''.join(priceList)

            item['title'] = strTitle
            item['link']  = strUrl
            item['price'] = strPrice
            yield item


def computepay(h, r):
    if h<40:
        pay = h*r
    elif h>40:
        a = h*r
        b = (h - 40.0)*(r*0.5)
        pay=a +b
    return pay
ab= int(input('enter hours: '))
cd= float(input('enter rate: '))
z = computepay(ab,cd)
print('Pay', z)


from fvh import MyTurtle
masterHexSet=[]
masterHexList=[]
distanceBetweenLayers=None
points=["sw","se","e","ne","nw","w"]

def drawit(circleXfromCenter,rootHex):
    heading=90
    rootHex.turt.pu()
    rootHex.turt.seth(heading)
    rootHex.setDistanceBetweenLayers()
    rootHex.turt.fd(distanceBetweenLayers)
    newturt=Hex(rootHex.turt.pos(), rootHex.length)
    newturt.drawBlack()
    heading=heading-60
    for x in range(circleXfromCenter-1):
        rootHex.turt.seth(heading)
        rootHex.turt.fd(distanceBetweenLayers)
        newturt=Hex(rootHex.turt.pos(), rootHex.length)
        newturt.drawBlack()
    for x in range(5):
        heading=heading-60
        for y in range(circleXfromCenter):
            rootHex.turt.seth(heading)
            rootHex.turt.fd(distanceBetweenLayers)
            newturt=Hex(rootHex.turt.pos(), rootHex.length)
            newturt.drawBlack()

def drawsome(x):
    a=Hex((0,0),10)
    a.drawBlack()
    for circle in range(1,x):
        drawit(circle,a)
    counter=1
    for ahex in masterHexList:
        ahex.write(counter)
        counter+=1

def checkInMasterHexSet(point):
    tempx=round(point[0],-1)
    tempy=round(point[1],-1)
    temppos=(tempx,tempy)
    return temppos in masterHexSet

class Hex(object):

    def __init__(self, center, lengthperside):
        global masterHexSet
        global masterHexList

        self.center=center
        self.length=lengthperside
        tempx=round(center[0],-1)
        tempy=round(center[1],-1)
        temppos=(tempx,tempy)
        masterHexSet.append(temppos)
        masterHexList.append(self)
        self.turt=MyTurtle()
        self.turt.setup()
        self.turt.tracer(False)
        self.points={}

    def drawBlack(self):
        self.turt.pu()
        self.turt.pencolor('black')
        self.turt.goto(self.center)
        self.turt.seth(240)
        self.turt.fd(self.length)
        self.turt.seth(0)
        self.turt.pd()
        for eachpoint in points:
            self.points[eachpoint]=self.turt.pos()
            self.turt.fd(self.length)
            self.turt.lt(60)
        self.turt.pu()
        self.turt.goto(self.center)

    def drawRed(self):
        self.turt.pu()
        self.turt.pencolor('red')
        self.turt.goto(self.center)
        self.turt.seth(240)
        self.turt.fd(self.length)
        self.turt.seth(0)
        self.turt.pd()
        for eachpoint in points:
            self.points[eachpoint]=self.turt.pos()
            self.turt.fd(self.length)
            self.turt.lt(60)
        self.turt.pu()
        self.turt.goto(self.center)

    def setDistanceBetweenLayers(self):
        global distanceBetweenLayers
        distanceBetweenLayers=self.points['ne'][1]-self.points['se'][1]

    def createLayers(self,numberOfLayers):
        if not distanceBetweenLayers:
            self.setDistanceBetweenLayers()
        for x in range(1,numberOfLayers+1):
            for y in range(6):
                self.turt.pu()
                self.turt.goto(self.center)
                self.turt.seth(90-(y*60))
                self.turt.fd(x*distanceBetweenLayers)
                if not checkInMasterHexSet(self.turt.pos()):
                    tempHex=Hex(self.turt.pos(), self.length)
                    tempHex.drawBlack()
                    if (numberOfLayers-x>=1):
                        tempHex.createLayers(numberOfLayers-x)

    def colorBlack(self):
        self.turt.fillcolor('black')
        self.turt.fill(True)
        self.drawBlack()
        self.turt.fill(False)
        if self.something:
            self.turt.pencolor('white')
            self.turt.write(self.something)
            self.turt.pencolor('black')

    def colorWhite(self):
        self.turt.fillcolor('white')
        self.turt.fill(True)
        self.drawBlack()
        self.turt.fill(False)
        if self.something:
            self.turt.pencolor('black')
            self.turt.write(self.something)

    def write(self,something):
        self.something=something
        self.turt.goto(self.center)
        self.turt.write(something)


from django.urls import reverse
from django.utils.translation import ugettext_lazy as _

from menus.base import Menu, NavigationNode
from menus.menu_pool import menu_pool

from DSTBundesliga.apps.leagues.config import LEVEL_MAP
from DSTBundesliga.apps.leagues.models import League

class LeaguesMenu(Menu):
    def get_nodes(self, request):
        """
        This method is used to build the menu tree.
        """
        nodes = []
        counter = 1
        nodes.append(NavigationNode("Startseite", "/", counter))

        counter += 1
        nodes.append(
            NavigationNode("Champions League", reverse("champions-league"), counter)
        )
        all_leagues = League.objects.get_active()
        conferences = {}
        regions = {}

        for level, title in LEVEL_MAP.items():
            conference_id = None

            level_leagues = all_leagues.filter(level=level)

            for conference in (
                level_leagues.values_list("conference", flat=True)
                .distinct()
                .order_by("conference")
            ):
                if conference:
                    conference_node = conferences.get(conference)
                    if not conference_node:
                        counter += 1
                        conference_node = NavigationNode(
                            conference,
                            reverse(
                                "conference-overview", kwargs={"conference": conference}
                            ),
                            conference,
                            attr={"li_class": conference},
                        )
                        nodes.append(conference_node)
                        conferences[conference] = conference_node
                    conference_id = conference_node.id

                conference_leagues = level_leagues.filter(conference=conference)

                counter += 1
                kwargs = {"level": level}
                url = reverse("level-detail", kwargs=kwargs)
                if conference:
                    kwargs["conference"] = conference
                    url = reverse("conference-detail", kwargs=kwargs)

                node_id = "league-%i" % level
                if conference:
                    node_id = conference + "-" + node_id
                league_node = NavigationNode(
                    title,
                    url,
                    node_id,
                    parent_id=conference_id,
                    attr={"li_class": conference},
                )
                league_id = league_node.id
                nodes.append(league_node)

                for region in (
                    conference_leagues.values_list("region", flat=True)
                    .distinct()
                    .order_by("region")
                ):
                    if region:
                        if region == "Süd":
                            region = "Sued"
                        region_node = regions.get(conference, {}).get(region)
                        if not region_node:
                            counter += 1
                            region_node = NavigationNode(
                                region,
                                reverse(
                                    "region-detail",
                                    kwargs={
                                        "level": level,
                                        "conference": conference,
                                        "region": region,
                                    },
                                ),
                                node_id + "-" + region,
                                parent_id=league_id,
                                attr={"li_class": conference},
                            )
                            nodes.append(region_node)
                            if not regions.get(conference):
                                regions[conference] = {}
                            regions[conference][region] = region_node

                    counter += 1

        # Stats
        counter += 1
        nodes.append(
            NavigationNode("Stats", "#", counter, attr={"li_class": "stats-node"})
        )
        stats_parent = counter

        # counter += 1
        # nodes.append(NavigationNode("Facts & Figures", reverse('facts_and_figures'), counter, stats_parent))

        counter += 1
        nodes.append(
            NavigationNode("CL Quali", reverse("cl-quali"), counter, stats_parent)
        )

        counter += 1
        nodes.append(
            NavigationNode("Waiver", reverse("waiver_stats"), counter, stats_parent)
        )

        counter += 1
        nodes.append(
            NavigationNode("Draft", reverse("draft-stats"), counter, stats_parent)
        )

        # Hörerliga
        counter += 1
        nodes.append(NavigationNode("DST - Hörerliga", reverse("dst-league"), counter))

        counter += 1
        nodes.append(
            NavigationNode(
                "Deine Anmeldung",
                reverse("dstffbl:profile"),
                counter,
                attr={"visible_for_anonymous": False},
            )
        )

        return nodes

menu_pool.register_menu(LeaguesMenu)


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

name = str(input("Jak masz na imię? "))
lenName = len(name)
surname = str(input ("Jakie jest Twoje nazwisko? "))
lenSurname = len(surname)
if lenName == 0 and lenSurname == 0:
    print("Brak danych")
elif lenName == 0:
    print ("Nie wypełniono pola imię")
elif lenSurname == 0:
    print ("Nie wypełniono pola nazwisko")
else:
    print ("HELLO", name, surname)


from datetime import date, datetime, timedelta
from statistics import mode
from tkinter import CASCADE
from django.db import models
from django.contrib import admin
from sympy import false, true

# Create your models here.

class Ticket(models.Model):
    name = models.CharField(max_length=50)
    longDescription = models.TextField()
    shortDescription = models.CharField(max_length=200)
    creationDate = models.DateField()

    urlName = models.SlugField()
    dueDate = models.DateField(null=True)

    parentTicket = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='parent')

    #yeah these related names are dumb, but they work
    dependencies = models.ManyToManyField('self', blank=True, symmetrical=False, related_name="dependence")

    children = models.ManyToManyField('self', blank=True, symmetrical=False, related_name="childs")

    isComplete = models.BooleanField(default=False)

    previousParentTicket = None
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.previousParentTicket = self.parentTicket
        #print(self.parentTicket)
    def __str__(self):
        return self.name

    def save(self, force_insert=False, force_update=False, *args, **kwargs):

        super().save(force_insert, force_update, *args, **kwargs)

        if (self.previousParentTicket != self.parentTicket):

            if (self.previousParentTicket != None):
                self.previousParentTicket.children.remove(self)

            if (self.parentTicket != None):
                print(self.parentTicket)
                print(self.parentTicket.children.all())
                self.parentTicket.children.add(self)
                self.parentTicket.save()

                print(self.parentTicket.children.all())

                self.previousParentTicket = self.parentTicket

    def getWarningState(self):
        returnText = "neutral"
        if (datetime.now().date() > self.dueDate):
            returnText="bad"
        elif (datetime.now().date() + timedelta(weeks=2) > self.dueDate):
            returnText="mediocre"
        if (self.isComplete):
            returnText = "good"
        return returnText

    def addNodeToTree(self, connectionList: list):
        nodeDict = {
            "title" : self.name,
            "shortDescription": self.shortDescription,
            "longDescription": self.longDescription,
            "dueDate": self.dueDate.strftime("%m/%d/%Y"),
            "warningState" : self.getWarningState(),
            "slug" : self.urlName,
            "creationDate" : self.creationDate,
            "children": [],
            "isComplete": self.isComplete
        }
        for child in self.children.order_by('dueDate'):
            nodeDict["children"].append(child.addNodeToTree(connectionList))
            connectionList.append((self.urlName, child.urlName))
        return nodeDict
    def toggleComplete(self):
        self.isComplete = not self.isComplete
        self.save()

class TicketAdmin(admin.ModelAdmin):
    prepopulated_fields = {"urlName": ("name", )}


from nextcord.ext import commands
import nextcord
from src.utils import logger
import os

class Bot(commands.Bot):
    def __init__(self, cfg, db=None):
        super().__init__(
            command_prefix=cfg.prefixes,
            intents=nextcord.Intents.default()
        )
        self.cfg = cfg
        self.db = db

        self.load_cogs('./src/cogs')

    def load_cogs(self, path):
        for file in os.listdir(path):
            if not file.startswith('_') and file.endswith('.py'):
                super().load_extension(f'src.cogs.{file[:-3]}')
                logger.info(f'Loaded cog "{ file[:-3]}"')

    def run(self, token):
        super().run(token)


import os
join = os.path.join
import random
import numpy as np
from skimage import io
import SimpleITK as sitk

def dcm2nii(dcm_path, nii_path):
    """
    Convert dicom files to nii files
    """
    reader = sitk.ImageSeriesReader()
    dicom_names = reader.GetGDCMSeriesFileNames(dcm_path)
    reader.SetFileNames(dicom_names)
    image = reader.Execute()
    sitk.WriteImage(image, nii_path)

def mhd2nii(mhd_path, nii_path):
    """
    Convert mhd files to nii files
    """
    image = sitk.ReadImage(mhd_path)
    sitk.WriteImage(image, nii_path)

def nii2nii(nii_path, nii_gz_path):
    """
    Convert nii files to nii.gz files, which can reduce the file size
    """
    image = sitk.ReadImage(nii_path)
    sitk.WriteImage(image, nii_gz_path)

def nrrd2nii(nrrd_path, nii_path):
    """
    Convert nrrd files to nii files
    """
    image = sitk.ReadImage(nrrd_path)
    sitk.WriteImage(image, nii_path)

def jpg2png(jpg_path, png_path):
    """
    Convert jpg files to png files
    """
    image = io.imread(jpg_path)
    io.imsave(png_path, image)

def patchfy(img, mask, outpath, basename):
    """
    Patchfy the image and mask into 1024x1024 patches
    """
    image_patch_dir = join(outpath, "images")
    mask_patch_dir = join(outpath, "labels")
    os.makedirs(image_patch_dir, exist_ok=True)
    os.makedirs(mask_patch_dir, exist_ok=True)
    assert img.shape[:2] == mask.shape
    patch_height = 1024
    patch_width = 1024

    img_height, img_width = img.shape[:2]
    mask_height, mask_width = mask.shape

    if img_height % patch_height != 0:
        img = np.pad(img, ((0, patch_height - img_height % patch_height), (0, 0), (0, 0)), mode="constant")
    if img_width % patch_width != 0:
        img = np.pad(img, ((0, 0), (0, patch_width - img_width % patch_width), (0, 0)), mode="constant")
    if mask_height % patch_height != 0:
        mask = np.pad(mask, ((0, patch_height - mask_height % patch_height), (0, 0)), mode="constant")
    if mask_width % patch_width != 0:
        mask = np.pad(mask, ((0, 0), (0, patch_width - mask_width % patch_width)), mode="constant")

    assert img.shape[:2] == mask.shape
    assert img.shape[0] % patch_height == 0
    assert img.shape[1] % patch_width == 0
    assert mask.shape[0] % patch_height == 0
    assert mask.shape[1] % patch_width == 0

    height_steps = (img_height // patch_height) if img_height % patch_height == 0 else (img_height // patch_height + 1)
    width_steps = (img_width // patch_width) if img_width % patch_width == 0 else (img_width // patch_width + 1)

    for i in range(height_steps):
        for j in range(width_steps):
            img_patch = img[i * patch_height:(i + 1) * patch_height, j * patch_width:(j + 1) * patch_width, :]
            mask_patch = mask[i * patch_height:(i + 1) * patch_height, j * patch_width:(j + 1) * patch_width]
            assert img_patch.shape[:2] == mask_patch.shape
            assert img_patch.shape[0] == patch_height
            assert img_patch.shape[1] == patch_width
            print(f"img_patch.shape: {img_patch.shape}, mask_patch.shape: {mask_patch.shape}")
            img_patch_path = join(image_patch_dir, f"{basename}_{i}_{j}.png")
            mask_patch_path = join(mask_patch_dir, f"{basename}_{i}_{j}.png")
            io.imsave(img_patch_path, img_patch)
            io.imsave(mask_patch_path, mask_patch)

def rle_decode(mask_rle, img_shape):
    """
    #functions to convert encoding to mask and mask to encoding
    mask_rle: run-length as string formated (start length)
    shape: (height,width) of array to return
    Returns numpy array, 1 - mask, 0 - background
    """
    seq = mask_rle.split()
    starts = np.array(list(map(int, seq[0::2])))
    lengths = np.array(list(map(int, seq[1::2])))
    assert len(starts) == len(lengths)
    ends = starts + lengths
    img = np.zeros((np.product(img_shape),), dtype=np.uint8)
    for begin, end in zip(starts, ends):
        img[begin:end] = 255
    # https://stackoverflow.com/a/46574906/4521646
    img.shape = img_shape
    return img.T


#!/usr/bin/python3

import sys

class WarningFilter:
  def __init__(self, insequence):
    self.insequence = insequence

  def __iter__(self):
    return self

  def __next__(self):
    l = self.insequence.readline()
    while l and "WARNING" not in l:
      l = self.insequence.readline()
    if not l:
      raise StopIteration
    return l.replace(' WARNING', '')

if __name__ == "__main__":
  inname, outname = sys.argv[1:]
  with open(inname) as infile:
    with open(outname, "w") as outfile:
      filter = WarningFilter(infile)
      for l in filter:
        outfile.write(l)


def HigestAltitude(gain):
    max = gain[0] if gain[0] > 0 else 0
    for i in range(1,len(gain)):
        gain[i] = gain[i]+gain[i-1]
        max = gain[i] if max < gain[i] else max
    return max

result = HigestAltitude([52,-91,72])
print(result)

Array/1732. Find the Highest Altitude.py


import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import web_server_base
from esphome.components.web_server_base import CONF_WEB_SERVER_BASE_ID
from esphome.const import CONF_ID
from esphome.core import coroutine_with_priority

AUTO_LOAD = ['web_server_base']
DEPENDENCIES = ['wifi']

captive_portal_ns = cg.esphome_ns.namespace('captive_portal')
CaptivePortal = captive_portal_ns.class_('CaptivePortal', cg.Component)

CONFIG_SCHEMA = cv.Schema({
    cv.GenerateID(): cv.declare_id(CaptivePortal),
    cv.GenerateID(CONF_WEB_SERVER_BASE_ID): cv.use_id(web_server_base.WebServerBase),
}).extend(cv.COMPONENT_SCHEMA)

@coroutine_with_priority(64.0)
def to_code(config):
    paren = yield cg.get_variable(config[CONF_WEB_SERVER_BASE_ID])

    var = cg.new_Pvariable(config[CONF_ID], paren)
    yield cg.register_component(var, config)
    cg.add_define('USE_CAPTIVE_PORTAL')


from fixedint import*
import itertools
from enum import Enum
import random as rnd

import cocotb
from cocotb.triggers import Timer
from cocotb_coverage.coverage import CoverPoint, CoverCross, coverage_db

N_TEST = 1_000_000
SEED = 2023

SCR1_XLEN = 32

class Cmd(Enum):
	ADD = 4 	 # SCR1_IALU_CMD_ADD
	SUB = 5 	 # SCR1_IALU_CMD_SUB

MAX_IN = 2**(SCR1_XLEN-1)-1
MIN_IN = -2**(SCR1_XLEN-1)

VALUES_OF_INTEREST = (MAX_IN, MIN_IN, 0, -1, 1)
COVERAGE_LABELS = ['MAX', 'MIN', '0', '-1', '1']

@cocotb.test()
async def addition(dut):
	rnd.seed(SEED)
	operands = []
	for i in range(N_TEST):
		op1 = rnd.randint(MIN_IN, MAX_IN)
		op2 = rnd.randint(MIN_IN, MAX_IN)
		operands += (op1, op2, ),

	await run_test(dut, operands, Cmd.ADD)

@cocotb.test()
async def add_edge_cases(dut):
	# get all possible pairs of VALUES_OF_INTEREST
	operands = list(itertools.product(VALUES_OF_INTEREST, repeat = 2))
	await run_test(dut, operands, Cmd.ADD)

@cocotb.test()
async def subtraction(dut):
	rnd.seed(SEED)
	operands = []
	for i in range(N_TEST):
		op1 = rnd.randint(MIN_IN, MAX_IN)
		op2 = rnd.randint(MIN_IN, MAX_IN)
		operands += (op1, op2, ),

	await run_test(dut, operands, Cmd.SUB)

@cocotb.test()
async def sub_edge_cases(dut):
	# get all possible pairs of VALUES_OF_INTEREST
	operands = list(itertools.product(VALUES_OF_INTEREST, repeat = 2))
	await run_test(dut, operands, Cmd.SUB)
	coverage_db.export_to_xml(filename="coverage.xml")

@CoverPoint("top.op1", vname="op1",
			bins = list(VALUES_OF_INTEREST), bins_labels = COVERAGE_LABELS)
@CoverPoint("top.op2", vname="op2",
			bins = list(VALUES_OF_INTEREST), bins_labels = COVERAGE_LABELS)
@CoverPoint("top.cmd", vname = "cmd", bins = [Cmd.ADD.name, Cmd.SUB.name])
@CoverCross("top.edge_cases", items = ["top.op1", "top.op2", "top.cmd"])

def sample(op1, op2, cmd):
    pass

async def run_test(dut, operands, cmd):

	dut.exu2ialu_cmd_i.value = cmd.value

	for ops in operands:

		op1, op2 = Int32(ops[0]), Int32(ops[1])

		sample(op1, op2, cmd.name)

		dut.exu2ialu_main_op1_i.value = op1
		dut.exu2ialu_main_op2_i.value = op2

		await Timer(1, units="step")
		res = Int32(dut.ialu2exu_main_res_o.value)

		assert check_result(cmd, op1, op2, res), \
				'Failed test #' + str(i) + ': output is incorrect!'

def check_result(cmd, op1, op2, res):
	if (cmd == Cmd.ADD):
		correct = (res == op1+op2)
	elif (cmd == Cmd.SUB):
		correct = (res == op1-op2)
	else:
		assert False

	return correct


# Python script for generating sample data
# so you can see/test how the R scripts work

# This sample data won't be very realistic --
# responses are completely randomly assigned.
# It's mostly just to test that the code works!

import random
import csv
import os

resDir = "sample_results/"
numParticipantsPerStimulus = 30

# slider
# participantIDs
# posthoc
# demographics
# debriefing

# Check if results directories exist, if not create
if os.path.exists(resDir) == False:
	os.mkdir(resDir)
for subDir in ["participantIDs", "slider", "posthoc", "demographics", "debriefing"]:
	if os.path.exists(resDir + subDir) == False:
		os.mkdir(resDir + subDir)

for n in range(numParticipantsPerStimulus):
	for stimulus in ["robert_all_ING", "robert_all_IN", "robert_all_ING-IN-ING-IN", "robert_all_IN-ING-IN-ING", "robert_reverse_ING-IN-ING-IN", "robert_reverse_IN-ING-IN-ING"]:
		participantID = hex(random.randint(500000000000,1000000000000))[2:]

		# participantID file
		with open(resDir + "participantIDs/" + participantID, 'w') as participantFile:
			writer = csv.writer(participantFile, delimiter='\t')
			writer.writerow(['prolificID', 'x'])
			participantFile.write(hex(random.randint(500000000000,1000000000000))[2:] + '\t') # generate a different random ID to pretend it's the prolific ID
			# (Formatting is funny because actual webcode output is funny, this is to match it)

		# slider file
		with open(resDir + "slider/" + stimulus + '_' + participantID + '.csv', 'w') as sliderFile:
			writer = csv.writer(sliderFile, delimiter='\t')
			writer.writerow(['time', 'rating', 'timestamp', 'x'])
			# Pick a random number of timepoints to respond to
			numTimepoints = random.randint(1,25)
			# Then randomly choose what those timepoints are, and sort in order
			timepoints = random.sample(range(1,int(70.897*1000)), numTimepoints) # multiply by 1000 and then divide to get three decimal places
			timepoints = [float(x)/1000 for x in timepoints]
			timepoints.sort()
			ratings = random.sample(range(100), numTimepoints)
			for count in range(len(timepoints)):
				writer.writerow([timepoints[count], ratings[count], timepoints[count] * 1000 + 1590158167635, ''])

		# posthoc file
		with open(resDir + "posthoc/" + participantID, 'w') as posthocFile:
			writer = csv.writer(posthocFile, delimiter='\t')
			writer.writerow(['posthoc', 'x'])
			posthocFile.write(str(random.randint(1,10)) + '\t')

		# demographics file
		with open(resDir + "demographics/" + participantID, 'w') as demographicsFile:
			writer = csv.writer(demographicsFile, delimiter='\t')
			writer.writerow(['nativeLanguages', 'hearingDisorder', 'gender', 'gender_text', 'race_white', 'race_black', 'race_latinx', 'race_asian', 'race_american_indian', 'race_pacific_islander', 'race_other', 'race_text', 'birth-year', 'occupation', 'degree', 'experiment_purpose', 'comments', 'x'])
			demographicsFile.write('English' + '\t' + random.choice(['yes', 'no']) + '\t' + random.choice(['male', 'female', 'other']) + '\t' + '' + '\t' + random.choice(['x', '']) + '\t' + random.choice(['x', '']) + '\t' + random.choice(['x', '']) + '\t' + random.choice(['x', '']) + '\t' + random.choice(['x', '']) + '\t' + random.choice(['x', '']) + '\t' + random.choice(['x', '']) + '\t' + '' + '\t' + str(random.randint(1920,2005)) + '\t' + random.choice(['doctor', 'lawyer', 'priest', 'janitor']) + '\t' + random.choice(['some_hs', 'some_college', 'masters']) + '\t' + random.choice(['accents', 'language']) + '\t' + random.choice(['no comments', 'cool study!']) + '\t')

		# debriefing file
		debriefingChoices = ['', 'Great debriefing!', 'I didnt notice ING at all', '', '']
		with open(resDir + "debriefing/" + participantID, 'w') as debriefingFile:
			writer = csv.writer(debriefingFile, delimiter='\t')
			writer.writerow(['comments', 'x'])
			debriefingFile.write(random.choice(debriefingChoices) + '\t')


import sqlite3
import alpaca_trade_api as tradeapi

connection = sqlite3.connect("/Users/user/Dev/Sigma-Terminal/database.db")
connection.row_factory = sqlite3.Row
##############################################
## GETTING THE SYMBOL DATA
##############################################
cursor = connection.cursor()

cursor.execute("""
    SELECT symbol, name FROM stock
""")

rows = cursor.fetchall()

symbols = [row['symbol'] for row in rows] # list comprehension

api = tradeapi.REST('YOURKEY', 'YOURKEY',
base_url='https://paper-api.alpaca.markets')
assets = api.list_assets()

for asset in assets:
    try:
        if asset.status == 'active' and asset.tradable and asset.symbol not in symbols:
            print(f"Added a new stock {asset.symbol} {asset.name}")
            cursor.execute("INSERT INTO stock (symbol, name) VALUES (?, ?)", (asset.symbol, asset.name))
    except Exception as e:
        print(asset.symbol)
        print(e)

connection.commit()


import numpy as np
import xarray as xr

from hidenseek.util.postproc.misc import contingency_xr

from hidenseek.globals import (
        behavioral_state_names_seek,
        behavioral_state_names_hide,
        behavioral_state_names_extra,
        behavioral_state_dict,
        inverse_behavioral_state_dict,
        behavioral_state_plot_dict
)

def to_plot_df(cont_mx_xr, rename=False):
    """
    Turn contingency matrix stored as an xarray.DataArray into a
    wide-form pandas.DataFrame that is nice to plot with seaborn.heatmap

    Parameters
    ----------
    cont_mx_xr : xr.DataArray
        contingency matrix with dims behavioral_states and hmm_state
    rename : bool, default False
        rename behavioral states to their pretty version with spaces

    Returns
    -------
    cont_mx_df : pd.DataFrame
        contingency matrix as a wide dataframe
    """
    cont_mx_xr = cont_mx_xr.assign_coords({'behavioral_state' : [inverse_behavioral_state_dict[i] for i in cont_mx_xr.behavioral_state.values]})
    cont_mx_df = cont_mx_xr.to_dataframe('contingency').reset_index().pivot_table(index = 'behavioral_state', columns = 'hmm_state').contingency

    if rename:
        cont_mx_df = cont_mx_df.rename(behavioral_state_plot_dict)
        cont_mx_df = cont_mx_df.rename_axis(columns = {'hmm_state' : 'HMM state'}, index = {'behavioral_state' : 'Behavioral state'})

    return cont_mx_df

from statsmodels.stats.multitest import multipletests

def make_signif_cont_df(p_cont_df, target_p_value, method):
    """
    Make dataframe that shows if a pair is significant or not

    Parameters
    ----------
    p_cont_df : pd.DataFrame
        dataframe with the pseudo p-values
    target_p_value : float
        target p-value we aim for
    method : str
        method for correcting for multiple comparisons
        if None, no correction is applied

    Returns
    -------
    signif_cont_df : pd.DataFrame
        boolean dataframe that is True
        for significant state pairs
    """
    if method is None:
        signif_cont_df = p_cont_df < target_p_value
    else:
        vals =  (multipletests(p_cont_df.values.flatten(),
                              method = method,
                              alpha = target_p_value)[0]
                 .reshape(-1, p_cont_df.shape[1]))

        signif_cont_df = p_cont_df.copy(deep=True)
        signif_cont_df.loc[:] = vals

    return signif_cont_df

def make_cont_dfs(session, trials_to_use, behavior_type, p_value, rename=False, correction=None):
    """
    Make contingency dataframes for session

    Parameters
    ----------
    trials_to_use : str
        observing, playing or both
    behavior_type : str
        observing, playing or both
        if you want to use it on the original dataset, set both to playing
    p_value : float
        p-value used for thresholding the significance matrices
    rename : bool, default False
        rename underscored names to prettier ones with spaces
    correction : str, default None
        method to use for correcting for multiple comparisons
        None means no correction

    Returns
    -------
    cont_df, cont_df_hmm, cont_df_beh, signif_cont_df, signif_cont_df_hmm, signif_cont_df_beh
    """
    if trials_to_use in ['playing', 'both'] and behavior_type == 'observing':
        raise ValueError
    used_trials = [trial for trial in session.trials if trials_to_use in ('both', trial.observing_role)]

    N_vals = {len(trial.fake_states_list) for trial in used_trials}
    assert len(N_vals) == 1
    N = list(N_vals)[0]

    # include trial's states if we're looking at all trials or the trial's type
    hmm_states = np.concatenate([trial.states for trial in used_trials])

    if behavior_type == 'both':
        # the behavior state is playing_states in playing trials and observing_states in observing trials
        behavior_states = np.concatenate([getattr(trial, f"{trial.observing_role}_states") for trial in used_trials])
    else:
        behavior_states = np.concatenate([getattr(trial, f"{behavior_type}_states") for trial in used_trials])

    fake_states_list = [np.concatenate([trial.fake_states_list[i] for trial in used_trials])
                        for i in range(N)]

    # contingencies of the real states and behavirs
    real_cont_mx = contingency_xr(behavior_states, hmm_states)
    real_cont_mx_hmm = (real_cont_mx / real_cont_mx.sum('behavioral_state'))
    real_cont_mx_beh = (real_cont_mx / real_cont_mx.sum('hmm_state'))

    # contingencies in every repetition of the fake state generation
    fake_cont_matrices = []
    fake_cont_matrices_hmm = []
    fake_cont_matrices_beh = []
    for fake_states in fake_states_list:
        fake_cont_mx = contingency_xr(behavior_states, fake_states)

        fake_cont_matrices.append(fake_cont_mx)
        fake_cont_matrices_hmm.append(fake_cont_mx / fake_cont_mx.sum('behavioral_state'))
        fake_cont_matrices_beh.append(fake_cont_mx / fake_cont_mx.sum('hmm_state'))

    # combine them into a 3D tensor
    fake_cont_mx = xr.concat(fake_cont_matrices, dim = 'repetition')
    fake_cont_mx_hmm = xr.concat(fake_cont_matrices_hmm, dim = 'repetition')
    fake_cont_mx_beh = xr.concat(fake_cont_matrices_beh, dim = 'repetition')

    # (fake_cont_mx > real_cont_mx).mean('repetition') is the
    # ratio of repetitions with a higher score than the real score
    p_cont_mx = ((fake_cont_mx >= real_cont_mx).mean('repetition'))
    p_cont_mx_hmm = ((fake_cont_mx_hmm >= real_cont_mx_hmm).mean('repetition'))
    p_cont_mx_beh = ((fake_cont_mx_beh >= real_cont_mx_beh).mean('repetition'))

    # turn each array into a nicely plotted dataframe
    cont_df = to_plot_df(real_cont_mx, rename)
    cont_df_hmm = to_plot_df(real_cont_mx_hmm, rename)
    cont_df_beh = to_plot_df(real_cont_mx_beh, rename)

    p_cont_df = to_plot_df(p_cont_mx, rename)
    p_cont_df_hmm = to_plot_df(p_cont_mx_hmm, rename)
    p_cont_df_beh = to_plot_df(p_cont_mx_beh, rename)

    # correct for multiple comparisons and make a mask signaling significance
    signif_cont_df = make_signif_cont_df(p_cont_df, p_value, correction)
    signif_cont_df_hmm = make_signif_cont_df(p_cont_df_hmm, p_value, correction)
    signif_cont_df_beh = make_signif_cont_df(p_cont_df_beh, p_value, correction)

    return cont_df, cont_df_hmm, cont_df_beh, signif_cont_df, signif_cont_df_hmm, signif_cont_df_beh


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

import sys
import os
import nltk
import json
from nlp_process import varparse
from nlp_process import AddTimesSignAndBrackets
import unicodedata
from pyltp import Segmentor, NamedEntityRecognizer, Postagger, SentenceSplitter, Parser
from nltk.tree import Tree    #导入nltk tree结构
from nltk.grammar import DependencyGrammar  #导入依存句法包
from nltk.parse import *
from nlp_process.AnalyzedifSign import replace
import gc

mw =["m","w","ws","wp"]
import copy

tagcansave=['ws','n','nd','nz','a']

def isnot_Chinese(word):
    for ch in word:
        if '\u4e00' <= ch <= '\u9fff':
            return False
    return True

#后序遍历conlltree
def postOrderTraverse(conlltree,num,head_num):
    questionOrothers=[]
    if conlltree.nodes[num]["deps"]:
        for i in conlltree.nodes[num]["deps"]:
            for j in conlltree.nodes[num]["deps"][i]:
                questionOrothers.extend(postOrderTraverse(conlltree,j,num))
    if conlltree.nodes[num]['word'] is not None:
        if isnot_Chinese(conlltree.nodes[num]['word']):
            questionOrothers.append(conlltree.nodes[num]['word'])
        else:
            if conlltree.nodes[num]['rel']!='ROOT' and conlltree.nodes[num]['tag']in tagcansave and (conlltree.nodes[head_num]['rel']=='ROOT'or not conlltree.nodes[num]['deps']):
                 questionOrothers.append(conlltree.nodes[num]['word'])
    return questionOrothers
from nlp_process import SplitSentence

def testparse(sentence):
    sentence=replace(sentence)
    finalsentenceList =SplitSentence.splitbysymbol(SplitSentence.splitbynum(sentence))
    tmpsentenceList=copy.deepcopy(finalsentenceList)
    postaggerList = []

    model_path = "/usr/local/pyltp/ltp_data_v3.4.0/cws.model"
    userdict_path ='userdict.txt'
    segmentor =Segmentor()#实力化分词模块
    segmentor.load_with_lexicon(model_path,userdict_path)
    for sentenceList in finalsentenceList:
        tmpPostaggerList = []
        for index_one,sents in enumerate(sentenceList):
            sent = segmentor.segment(sents)
            # print('|'.join(sent))

            postagger =Postagger()
            postagger.load_with_lexicon("/usr/local/pyltp/ltp_data_v3.4.0/pos.model",userdict_path)  # 导入词性标注模块
            sent =list(sent)
            postags = list(postagger.postag(sent))
            # print(type(postags))
            # print(postags)
            postagger.release()
            # recognizer = NamedEntityRecognizer()
            # recognizer.load("/usr/local/pyltp/ltp_data_v3.4.0/ner.model")  # 导入命名实体识别模块
            # netags = recognizer.recognize(sent, postags)

            sentandpostags=list(zip(sent,postags))
            splist=[]
            for sp in sentandpostags:
                splist.append(list(sp))
            #整合词性
            for index,sp in enumerate(splist):
                while(index<len(splist)-1 and splist[index][1]in mw and splist[index+1][1]in mw ):
                    splist[index][0]=splist[index][0]+splist[index+1][0]
                    splist[index][1]="ws"
                    splist.pop(index+1)

            sents=[]
            postags=[]
            for sp in splist:
                sents.append(sp[0])
                postags.append(sp[1])
            sentenceList[index_one]=sents
            tmpPostaggerList.append(postags)
        # print(sentenceList,tmpPostaggerList)
        postaggerList.append(tmpPostaggerList)
    # print(finalsentenceList)
    # print(postaggerList)
    final_result_dict={}
    tmplist=[] #构造句子的结构，判断是否已取出有用数据
    #取出已知条件的等式
    for index in range(len(finalsentenceList)):
        num=len(finalsentenceList[index])
        tmpnum = list(range(num))
        #有用信息添加到输出结果
        result_dict={}
        for i in range(num):
            for j in range(len(finalsentenceList[index][i])):
                #将等式加入result
                if ('=' in finalsentenceList[index][i][j] and postaggerList[index][i][j]=='ws'and finalsentenceList[index][i][j][-1]!='='):
                    equal_dic ={}

                    equal_dic["equalExpresion"]=AddTimesSignAndBrackets.AddTimesSignAndBrackets(finalsentenceList[index][i][j])
                    equal_dic["vars"]=varparse.equalparse(finalsentenceList[index][i][j])
                    if 'equals' in result_dict:
                        result_dict['equals'].append(equal_dic)
                    else:
                        result_dict['equals']=[equal_dic]

                    if i in tmpnum:
                        tmpnum.remove(i)
        final_result_dict[index]=result_dict
        tmplist.append(tmpnum)

    #取出问题
    for index in range(len(tmplist)):
        if len(tmplist[index])!=0:
            tmpnum=[]
            if(index==0 and len(tmplist)==1)or(len(tmplist)>1 and index >0):
                for i,value in enumerate(tmplist[index]):
                    if(i==len(tmplist[index])-1):
                        # for j,value_1 in enumerate(postaggerList[index][value]):
                        #
                        #     if postaggerList[index][value][j] in mw:
                        #         postaggerList[index][value][j]='n'
                        #         #去除英文名词前后的中文名词
                                # if 'n' in postaggerList[index][value][j+1]:
                                #     postaggerList[index][value].pop(j+1)
                                #     finalsentenceList[index][value].pop(j+1)
                                # if 'n' in postaggerList[index][value][j-1]:
                                #     postaggerList[index][value].pop(j-1)
                                #     finalsentenceList[index][value].pop(j-1)

                        #进行取问题操作
                        parser = Parser()      #句法解析
                        parser.load("/usr/local/pyltp/ltp_data_v3.4.0/parser.model")
                        arcs = parser.parse(finalsentenceList[index][value], postaggerList[index][value])
                        parser.release()
                        # print(arcs)
                        arclen = len(arcs)
                        conll = ""
                        # relation_list=[[],[],[]]
                        for j in range(arclen):  # 构建Conll标准的数据结构
                            # print(arcs[j].head,arcs[j].relation)
                            if arcs[j].head == 0:
                                arcs[j].relation = "ROOT"
                            conll += "\t" + finalsentenceList[index][value][j] + "\t" + postaggerList[index][value][j] + "\t" + str(arcs[j].head) +"\t" +arcs[j].relation+"\t"  "\n"
                            # relation_list[0].append(finalsentenceList[index][value][j])
                            # relation_list[1].append(postaggerList[index][value][j])
                            # relation_list[2].append(arcs[j].head)
                        # print(conll)
                        # print(relation_list)
                        conlltree = DependencyGraph(conll)  # 转换为依存句法图
                        # print(conlltree)

                        #判断宽度是否为1
                        question_list=[]
                        # #宽度不为1
                        # if len(relation_list[2])!=len(set(relation_list[2])):
                        #     if(relation_list[1][relation_list[2].index(0)]=='v'):
                        #         for j,k in enumerate(relation_list[2]):
                        #             if(k==1 and relation_list[1][j]=='n'):
                        #                 question_list.append(relation_list[0][j])
                        # #宽度为1
                        # else:
                        #     if (relation_list[1][relation_list[2].index(0)] == 'v'):
                        #         for j, k in enumerate(relation_list[2]):
                        #             if (k == 1 and relation_list[1][j] == 'n'):
                        #                 question_list.append(relation_list[0][j])
                        # # print(question_list)
                        question_list=postOrderTraverse(conlltree,0,0)
                        # print(question_list)
                        if question_list:
                            relationslist = []
                            conditionslist = []
                            otherlist = []
                            if len(question_list) > 2:
                                if len(question_list)==3:
                                    conditionslist.append(question_list[:2])
                                    if not isnot_Chinese(conditionslist[0][0]) and isnot_Chinese(conditionslist[0][1]):
                                        tmp = conditionslist[0][0]
                                        conditionslist[0][0] = conditionslist[0][1]
                                        conditionslist[0][1] = tmp
                                elif len(question_list)==4:
                                    relationslist.append(question_list[:3])
                                    if isnot_Chinese(relationslist[0][0]) and not isnot_Chinese(relationslist[0][1]) and isnot_Chinese(relationslist[0][2]):
                                        tmp =relationslist[0][0]
                                        relationslist[0][0]=relationslist[0][2]
                                        relationslist[0][2]=relationslist[0][1]
                                        relationslist[0][1]=tmp

                                else:
                                    otherlist.append(question_list[:-2])
                                question_list=question_list[-2:]
                            if 'problems' in final_result_dict[index]:
                                final_result_dict[index]['problems'].append(question_list)
                            else:
                                final_result_dict[index]['problems']=[question_list]
                            tmpnum.append(value)
                            if otherlist:

                                if 'other' in final_result_dict[index]:
                                    final_result_dict[index]['others'].append(otherlist)
                                else:
                                    final_result_dict[index]['others'] = otherlist
                            if relationslist:

                                if 'other' in final_result_dict[index]:
                                    final_result_dict[index]['relations'].append(relationslist)
                                else:
                                    final_result_dict[index]['relations'] = relationslist
                            if conditionslist:

                                if 'other' in final_result_dict[index]:
                                    final_result_dict[index]['conditions'].append(conditionslist)
                                else:
                                    final_result_dict[index]['conditions'] = conditionslist
                if tmpnum:
                    for j in tmpnum:
                        tmplist[index].remove(j)

    # print(tmplist)
    #其他情况
    for index in range(len(tmplist)):
        relationslist=[]
        conditionslist=[]
        otherlist=[]
        if(tmplist[index]):
            for i in tmplist[index]:
                parser = Parser()  # 句法解析
                parser.load("/usr/local/pyltp/ltp_data_v3.4.0/parser.model")
                arcs = parser.parse(finalsentenceList[index][i], postaggerList[index][i])
                parser.release()
                # print(arcs)
                arclen = len(arcs)
                conll = ""
                # relation_list=[[],[],[]]
                for j in range(arclen):  # 构建Conll标准的数据结构
                    if arcs[j].head == 0:
                        arcs[j].relation = "ROOT"
                    conll += "\t" + finalsentenceList[index][i][j] + "\t" + postaggerList[index][i][j] + "\t" + str(arcs[j].head) + "\t" + arcs[j].relation + "\t"  "\n"

                # print(conll)
                # print(relation_list)
                conlltree = DependencyGraph(conll)  # 转换为依存句法图
                other_list = postOrderTraverse(conlltree, 0, 0)
                if other_list:
                    if len(other_list)==2:
                        if not isnot_Chinese(other_list[0])and isnot_Chinese(other_list[1]):
                            tmp = other_list[0]
                            other_list[0]=other_list[1]
                            other_list[1]=tmp
                        conditionslist.append(other_list)
                    elif len(other_list)==3:
                        relationslist.append(other_list)
                    else:
                        otherlist.append(tmpsentenceList[index][i])
        if otherlist:

            if 'other' in final_result_dict[index]:
                final_result_dict[index]['others'].append(otherlist)
            else:
                final_result_dict[index]['others'] = otherlist
        if relationslist:

            if 'other' in final_result_dict[index]:
                final_result_dict[index]['relations'].append(relationslist)
            else:
                final_result_dict[index]['relations'] = relationslist
        if conditionslist:

            if 'other' in final_result_dict[index]:
                final_result_dict[index]['conditions'].append(conditionslist)
            else:
                final_result_dict[index]['conditions'] = conditionslist

    deliver_dict={}
    deliver_dict["num"]=len(finalsentenceList)
    deliver_dict["problemEntity"]=[]
    for i in range(len(finalsentenceList)):
        deliver_dict["problemEntity"].append(final_result_dict[i])

    #转成json
    result_json =json.dumps(deliver_dict, ensure_ascii=False)
    # print(final_result_dict)
    # print(tmplist)
    for x in locals().keys():
        # print(locals()[x])
        del locals()[x]
    gc.collect()
    return result_json
# s1="已知函数f(x)=lnx-x+1/2a(x-1)^2+1。(1)讨论f(x)的单调性；(2)若x>=1,f(x)>=0恒成立，求实数a的取值范围."
# s1="已知sin(A)=1,sin(B+A)=0,求B的值"
# s1='已知在△ABC中，AB=√(3)，∠ABC=2*pi/3,BD是AC边上的高，AC=2√(3)BD.(1)求BC边的长;（2）求BC边中线AE的长'
# # #s1='∠ABC=120°，求BC边的长'
# s2 = testparse(s1)
# print(s2)


fib = [0 , 1]

n = int(input('Enter the length of the trail: '))

for i in range(2,n):
    x = fib[i-2] + fib[i-1]
    fib.append(x)

print ('fibonacci : ', fib)


import boto3
import logging
import json
import os
import requests

from datetime import datetime, timezone

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    endpoint = os.environ.get('API_ENDPOINT', None)

    response = requests.get(endpoint)
    json_object = response.json()
    stats = json_object['stats']

    cloudwatch = boto3.client('cloudwatch')

    for env in stats.keys():
        env_stats = stats[env]
        for repo in env_stats.keys():
            count = env_stats[repo]
            metric_data = [
                {
                    'MetricName': 'doc_count',
                    'Dimensions': [
                        {
                            'Name': 'EMMA_SERVICE',
                            'Value': 'ElasticSearch'
                        },
                        {
                            'Name': 'ENVIRONMENT',
                            'Value': env
                        },
                        {
                            'Name': 'REPOSITORY',
                            'Value': repo
                        },
                    ],
                    'Unit': 'None',
                    'Timestamp': datetime.now(timezone.utc),
                    'Value': count
                },
            ]
            print(env + ' ' + repo + ' ' + str(count))
            response = cloudwatch.put_metric_data(
                MetricData=metric_data,
                Namespace='emma-federated-search'
            )
    print ("Lambda function call completed.")


a=[]
k=0
for n in range(int(input())):
        name = input()
        score = float(input())
        a.append([score,name])
a.sort()
b=[]
while k < len(a):
    b.append(a[k][0])
    k+=1
b.sort()
names=[]
control=[]
# задаване на конролни точки за проверка (пример:37.21)
j=0
for i in b:
    if b[j-1] < b[j]:
        control.append(b[j])
        break
    j+=1
j=0
while j <= len(a)-1:
    if a[j][0] == control[0]:
        names.append(a[j][1])
        j+=1
    else:
        j+=1
names.sort()
for i in names:
    print(i)

# Input:

# 5
# Harry
# 37.21
# Berry
# 37.21
# Tina
# 37.2
# Akriti
# 41
# Harsh
# 39

# Ouput:

# Berry
# Harry


from .sc import Soundcloud
import json, json_config, requests
from urllib.parse import quote

sc = Soundcloud()
config = json_config.connect('./config/config.json')

class SoundcloudSearcher:
    def __init__(self) -> None:
        pass

    def request_tracks(self, track_name: str, offset: int = 0):
        limit = 20
        track_name_quotes = quote(track_name)
        href_track = f'https://api-v2.soundcloud.com/search?q={track_name_quotes}&facet=model&client_id={config["sc_client_id"]}&limit={limit}&offset={offset}&linked_partitioning=1&app_version=1633082668&app_locale=en'
        try:
            r = requests.get(href_track)
            responses = json.loads(r.text)
            info = []
            for response in responses['collection']:
                if response['kind'] == 'track':
                    uri = response['uri']
                    title = response['title']
                    username = response['user']['username']
                    info.append(
                        {
                            "username": username,
                            "title": title,
                            "uri": uri
                        }
                    )
            info_json = json.dumps(info, indent=4, ensure_ascii=False)
            return info_json
        except:
            print('error')
            return 0

    def request_playlists(self, playlist_name: str, offset: int = 0):
        limit = 20
        playlist_name_quotes = quote(playlist_name)
        href_playlist = f'https://api-v2.soundcloud.com/search/playlists_without_albums?q={playlist_name_quotes}&client_id={config["sc_client_id"]}&limit={limit}&offset={offset}app_version=1633082668&app_locale=en'
        try:
            r = requests.get(href_playlist)
            responses = json.loads(r.text)
            info = []
            for response in responses['collection']:
                uri = response['uri']
                title = response['title']
                username = response['user']['username']
                track_count = response['track_count']
                link = response['permalink_url']
                info.append(
                    {
                        "username": username,
                        "title": title,
                        "track_count": track_count,
                        "link": link,
                        "uri": uri
                    }
                )
            info_json = json.dumps(info, indent=4, ensure_ascii=False)
            return info_json
        except:
            print('error')
            return 0


class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        # base cases
        if n == 0:
            return True
        if len(flowerbed) == 0:
            return False
        if len(flowerbed) == 1:
            return n <= 1 and flowerbed[0] == 0

        print("before", flowerbed)

        # first
        if flowerbed[0] != 1 and flowerbed[1] != 1:
            n -= 1
            flowerbed[0] = 1

        for i in range(1, len(flowerbed)-1):
            if flowerbed[i] != 1 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
                n -= 1
                flowerbed[i] = 1

        # last
        if flowerbed[-1] != 1 and flowerbed[-2] != 1:
            n -= 1
            flowerbed[-1] = 1

        print("after", flowerbed)

        return n <= 0


import socket
import selectors
from selectors import SelectorKey
from typing import List, Tuple

selector = selectors.DefaultSelector()

def server() -> None:
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('localhost', 5000))
    server_socket.listen()

    selector.register(fileobj=server_socket, events=selectors.EVENT_READ, data=accept_connection)

def accept_connection(_server_socket: socket) -> None:
    client_socket, addr = _server_socket.accept()
    print("Connection from: ", addr)

    selector.register(fileobj=client_socket, events=selectors.EVENT_READ, data=send_message)

def send_message(_client_socket: socket) -> None:
    request = _client_socket.recv(4096)

    if request:
        response = "Hello world\n".encode()
        _client_socket.send(response)
    else:
        selector.unregister(_client_socket)
        _client_socket.close()

def event_loop() -> None:
    while True:

        events: List[Tuple[SelectorKey, int]] = selector.select()  # return tuple (key, events)

        for key, _ in events:
            callback = key.data
            callback(key.fileobj)

if __name__ == "__main__":
    server()
    event_loop()


"""QGIS Unit tests for QgsLayoutItemPage.

.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = '(C) 2017 by Nyall Dawson'
__date__ = '23/10/2017'
__copyright__ = 'Copyright 2017, The QGIS Project'

from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtXml import QDomDocument
from qgis.core import (
    QgsFillSymbol,
    QgsLayout,
    QgsLayoutItemPage,
    QgsProject,
    QgsReadWriteContext,
    QgsSimpleFillSymbolLayer,
)
import unittest
from qgis.testing import start_app, QgisTestCase

from test_qgslayoutitem import LayoutItemTestCase

start_app()

class TestQgsLayoutPage(QgisTestCase, LayoutItemTestCase):

    @classmethod
    def setUpClass(cls):
        super(TestQgsLayoutPage, cls).setUpClass()
        cls.item_class = QgsLayoutItemPage

    def testDefaults(self):
        p = QgsProject()
        l = QgsLayout(p)
        p = QgsLayoutItemPage(l)
        self.assertTrue(p.pageStyleSymbol())

        fill = QgsSimpleFillSymbolLayer()
        fill_symbol = QgsFillSymbol()
        fill_symbol.changeSymbolLayer(0, fill)
        fill.setColor(Qt.green)
        fill.setStrokeColor(Qt.red)
        fill.setStrokeWidth(6)
        p.setPageStyleSymbol(fill_symbol)

        self.assertEqual(p.pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00')
        self.assertEqual(p.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')

    def testReadWriteSettings(self):
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        fill = QgsSimpleFillSymbolLayer()
        fill_symbol = QgsFillSymbol()
        fill_symbol.changeSymbolLayer(0, fill)
        fill.setColor(Qt.green)
        fill.setStrokeColor(Qt.red)
        fill.setStrokeWidth(6)

        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        page.setPageStyleSymbol(fill_symbol.clone())
        self.assertEqual(collection.pageNumber(page), -1)
        collection.addPage(page)

        # add a second page
        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        fill_symbol.setColor(Qt.blue)
        page2.setPageStyleSymbol(fill_symbol.clone())
        collection.addPage(page2)

        doc = QDomDocument("testdoc")
        elem = doc.createElement("test")
        self.assertTrue(collection.writeXml(elem, doc, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        collection2 = l2.pageCollection()

        self.assertTrue(collection2.readXml(elem.firstChildElement(), doc, QgsReadWriteContext()))

        self.assertEqual(collection2.pageCount(), 2)

        self.assertEqual(collection2.page(0).pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00')
        self.assertEqual(collection2.page(0).pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')

        self.assertEqual(collection2.page(1).pageStyleSymbol().symbolLayer(0).color().name(), '#0000ff')
        self.assertEqual(collection2.page(1).pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')

if __name__ == '__main__':
    unittest.main()


import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import numpy as np
from statistics import mean

# We read our data file using pandas and bind it to 'df'
df = pd.read_csv("Raw data/Berkshire_vs_500.csv", index_col="date")
# We set our index to the year, instead of an incremented integer for easier sorting
df.index = pd.to_datetime(df.index, format="%Y-%m-%d").year

# We will be analyzing years 2010 - 2018
# For that we filter out the years that we will not be looking at
df = df.loc["2010":"2018"]
df.loc[2010] = np.nan

df["Berkshire Hathaway"] = (
    df[["low_BRK", "high_BRK"]].pct_change(axis=1)["high_BRK"].mul(10)
)
df["S&P 500"] = df[["low_SP500", "high_SP500"]].pct_change(axis=1)["high_SP500"].mul(10)

df_cleared = (
    df.groupby([df.index])
    .mean()
    .fillna(0)
    .drop(
        columns=[
            "open_BRK",
            "open_SP500",
            "close_BRK",
            "close_SP500",
            "high_BRK",
            "high_SP500",
            "low_BRK",
            "low_SP500",
        ]
    )
)

# We create a line plot showing cumulative percentage changes from 2010 through 2017
plot = df_cleared.plot.line(grid=True)
plot.set_title(
    "Cumulative percentage change year to year from a 2010 baseline through 2017",
    fontsize=10,
)
loc = plticker.MultipleLocator(base=2.0)
plot.xaxis.set_major_locator(loc)
plot.set_xlabel("Year", fontsize=9)
vals = plot.get_yticks()
plot.set_yticklabels(["{:,.0%}".format(x) for x in vals])
plt.show()


def zen_expand(zen):
    import re
    def recurse(zen, multi):
        tag = zen[0]
        open = "<" + tag + ">"
        close = "</" + tag + ">"
        if len(zen) == 1:
            return multi * (open + close)
        op = zen[1]
        if op == '+':
            zen = zen[2:]
            return multi * (open + close) + recurse(zen, 1)
        if op == '*':
            multi = int(zen[2])
            del zen[1:3]
            return recurse(zen, multi)
        if op == ">":
            zen = zen[2:]
            return multi*(open + recurse(zen, 1) + close)
    ans = re.split('(>|\+|\*)', zen)
    return recurse(ans, 1)


from django.core.management.base import BaseCommand, CommandError
from core import models as cm

import argparse
import datetime
import sys

class Command(BaseCommand):
    help = """
    A DANGEROUS utility for editing the DB to fix known issues due to botched migrations, etc.
    ALWAYS run in display mode before running in fix mode
    Display or repair depending on mode
    usage: python manage.py fix_db -t <trouble type> -m <mode>
    """

    def handle(self, *args, **options):
        trouble_type = options["troubletype"]
        mode = options["mode"]

        if mode == "fix":
            if trouble_type=="abstract_items":
                for o in cm.ParticipationItem.objects.all():
                    try:
                        i = o.get_inherited_instance()
                    except:
                        sys.stdout.write("participation item found whose inherited instance can't be determined:{}".format(o.name)+"\n")
                        sys.stdout.flush()
                        sys.stdout.write("deleting item\n")
                        o.delete()
                        sys.stdout.write("object deleted\n")

            elif trouble_type=="abstract_projects":
                num = 0
                for o in cm.ParticipationProject.objects.all():
                    num += 1
                    if num % 1000 == 0:
                        sys.stdout.write("{}\n".format(num))
                    try:
                        i = o.get_inherited_instance()
                    except:
                        sys.stdout.write("participation project found whose inherited instance can't be determined:{}".format(o.name)+"\n")
                        sys.stdout.flush()
                        sys.stdout.write("deleting project\n")
                        o.delete()
                        sys.stdout.write("object deleted\n")

            elif trouble_type=="clear_inactive":
                items_deleted = cm.ParticipationItem.objects.filter(is_active=False).delete()
                projects_deleted = cm.ParticipationProject.objects.filter(is_active=False).delete()
                sys.stdout.write("Number of items deleted:{}, number of projects deleted: {}\n".format(items_deleted, projects_deleted))
                sys.stdout.flush()

            else:
                raise Exception("unknown trouble type:"+str(trouble_type))
        elif mode == "display":
            if trouble_type=="abstract_items":
                for o in cm.ParticipationItem.objects.all():
                    try:
                        i = o.get_inherited_instance()
                    except:
                        sys.stdout.write("participation item found whose inherited instance can't be determined:{}".format(o.name)+"\n")
                        sys.stdout.flush()

            elif trouble_type=="abstract_projects":
                num = 0
                for o in cm.ParticipationProject.objects.all().iterator():
                    num += 1
                    if num % 1000 == 0:
                        sys.stdout.write("{}\n".format(num))
                    try:
                        i = o.get_inherited_instance()
                    except:
                        sys.stdout.write("participation project found whose inherited instance can't be determined:{}".format(o.name)+"\n")
                        sys.stdout.flush()

            elif trouble_type=="clear_inactive":
                items_deleted = cm.ParticipationItem.objects.filter(is_active=False).count()
                projects_deleted = cm.ParticipationProject.objects.filter(is_active=False).count()
                sys.stdout.write("Number of inactive items to delete:{}, number of inactive projects to delete: {}\n".format(items_deleted, projects_deleted))
                sys.stdout.flush()

            else:
                raise Exception("unknown trouble type:"+str(trouble_type))
        else:
            raise Exception("unknown mode:"+str(mode))
        sys.stdout.write("DONE\n")
        sys.stdout.flush()

    def add_arguments(self, parser):
        parser.add_argument('-m', '--mode', required=True, type=str, help="mode", action='store')
        parser.add_argument('-t', '--troubletype', required=True, type=str, help="trouble type", action='store')


from typing import Optional
from django.core.management.base import BaseCommand, CommandParser
from datetime import datetime, timezone
import json
from pathlib import Path

from replays import constant_helpers
from replays import replay_parsing
from replays import create_replay
from replays import limits
from replays import models

ROYALFLARE_JSON_DIRECTORY_PATH = Path(__file__).parent / "resources" / "royalflare"

class Command(BaseCommand):
    help = """Import royalflare replays. To use this, you must first download and
    extract royalflare replays from https://maribelhearn.com/mirror/royalflare.zip.
    Then, run this command with an argument pointing to the /replays folder you just
    made. The script imports those replays, using additional data from jsons that
    were downloaded from
    https://github.com/MaribelHearn/maribelhearn.com/tree/master/assets/games/royalflare/json
    """

    def add_arguments(self, parser: CommandParser) -> None:
        super().add_arguments(parser)

        parser.add_argument(
            "replay_dir",
            help="The directory containing the replays. Should end in /replays.",
        )

        parser.add_argument(
            "--json",
            help="A path to royalflare json file containing info for replays to "
            + "import.\nIf not set, all jsons will be used.",
        )

    def handle(self, *args, **options):
        main(options["replay_dir"], options["json"])

def main(replay_dir: str, json_file_arg: Optional[str]) -> None:
    if json_file_arg is not None:
        json_files = [json_file_arg]
    else:
        json_files = ROYALFLARE_JSON_DIRECTORY_PATH.glob("**/*.json")

    for json_file in json_files:
        with open(json_file, encoding="utf-8") as f:
            all_replay_infos_from_json = json.load(f)
            for info_from_json in all_replay_infos_from_json:
                import_royalflare(info_from_json, Path(replay_dir))

def import_royalflare(info_from_json: dict, replay_dir: Path) -> None:
    comment = info_from_json["comment"]
    replay_path = parse_replay_path_from_json(replay_dir, info_from_json["replay"])
    if "uploaded" in info_from_json:
        created_timestamp = parse_timestamp_from_json(info_from_json["uploaded"])
    else:
        # The first 3 replays ever uploaded on rf do not have an 'uploaded' timestamp.
        # They can be found at the bottom of th08.json
        created_timestamp = parse_timestamp_from_json(info_from_json["date"])
    imported_username = info_from_json["player"]

    try:
        if replay_path.stat().st_size > limits.MAX_REPLAY_SIZE:
            raise limits.FileTooBigError()
        replay_bytes = replay_path.read_bytes()
        duplicate = constant_helpers.GetReplayFileWithSameHash(replay_bytes)
        if duplicate is not None:
            raise Exception("This replay already exists")
        replay_info = replay_parsing.Parse(replay_bytes)
        temp_replay = models.TemporaryReplayFile(user=None, replay=replay_bytes)
        temp_replay.save()

        create_replay.PublishNewReplay(
            user=None,
            difficulty=replay_info.difficulty,
            score=replay_info.score,
            category=1,
            comment=comment,
            is_good=True,
            is_clear=True,
            no_bomb=False,
            miss_count=None,
            video_link="",
            temp_replay_instance=temp_replay,
            replay_info=replay_info,
            created_timestamp=created_timestamp,
            imported_username=imported_username,
        )
    except Exception as e:
        if str(e) != "This replay already exists":
            print(f"Failed to import {replay_path}")
            print(e)

def parse_replay_path_from_json(replay_directory: Path, replay_location: str) -> Path:
    path_including_top_level_dir = Path(replay_location.lstrip("/"))
    path = Path(*path_including_top_level_dir.parts[1:])
    return replay_directory / path

def parse_timestamp_from_json(timestamp: str) -> datetime:
    if ":" in timestamp:
        unaware_datetime = datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S")
    else:
        unaware_datetime = datetime.strptime(timestamp, "%Y/%m/%d")
    aware_datetime = unaware_datetime.replace(tzinfo=timezone.utc)
    return aware_datetime


from flask import request, Blueprint
from flask_pymongo import ObjectId
from project.db import mongo
from project.models.dto import WynikOperacji
from flask_jwt_extended import jwt_required, get_jwt_identity
from project.utils import response, now

users_blueprint = Blueprint(
    'users',
    __name__
)

@users_blueprint.route('/profil', methods=["POST"])
@jwt_required
def aktualizujProfil():
    daneProfilu = request.json #dane typu waga, wzrost itp
    print('dane profilu' + str(daneProfilu))
    daneProfilu['data_aktualizacji'] = now()
    print('dane profilu' + str(daneProfilu))
    res = mongo.db.uzytkownicy.update_one({'_id': ObjectId(get_jwt_identity())}, {'$set': daneProfilu})
    print('wynik update: ' + str(res))
    return response(WynikOperacji("ustawProfil", True))

@users_blueprint.route('/profil', methods=["GET"])
@jwt_required
def podajDaneProfilu():
    user_id = ObjectId(get_jwt_identity())
    dane_z_bazy = mongo.db.uzytkownicy.find_one({'_id': user_id})
    return response(dane_z_bazy)


import cv2
import numpy as np
import face_recognition
import os
from handle_sheet_index import update_col_index, get_current_index
# from PIL import ImageGrab
from google_sheet import invoke_present, get_sheet_name
import sys

# Finding the current sheet column index
# current_index = get_current_index()

def prepare_images(section):
    path = f'images/{section}'
    images = []
    classNames = []
    myList = os.listdir(path)
    print(myList)
    for cl in myList:
        curImg = cv2.imread(f'{path}/{cl}')
        images.append(curImg)
        classNames.append(tuple(os.path.splitext(cl)[0].split(" ")))
        print(classNames)
    return images,classNames

def findEncodings(images):
    encodeList = []
    for img in images:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        encode = face_recognition.face_encodings(img)[0]
        encodeList.append(encode)
    return encodeList

def markAttendance(student_id,current_index):
    invoke_present(student_id,current_index)

def attendence_process(instruct,section,subject,col_idx):
    get_sheet_name(subject) #set the sheet name
    print("starting attendence process")
    cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
    print("yeea",section)

    if instruct==None:

        print("inside if")
        images, classNames = prepare_images(section)
        encodeListKnown = findEncodings(images)
        attended_student = []

        while True:
            success, img = cap.read()
            #img = captureScreen()
            imgS = cv2.resize(img,(0,0),None,0.25,0.25)
            imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)

            facesCurFrame = face_recognition.face_locations(imgS)
            encodesCurFrame = face_recognition.face_encodings(imgS,facesCurFrame)

            for encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):
                matches = face_recognition.compare_faces(encodeListKnown,encodeFace)
                # print(f"matches: {matches}")
                faceDis = face_recognition.face_distance(encodeListKnown,encodeFace)
                # print("facedistance",faceDis)
                matchIndex = np.argmin(faceDis)
                # print("distance value",faceDis[matchIndex])
                if faceDis[matchIndex] < 0.35:

                    print("inside first if")
                    print("distance value",faceDis[matchIndex])
                    # print(f"matchIndex: {matchIndex}")

                    if matches[matchIndex]:
                        student_info = classNames[matchIndex]
                        student_id = student_info[1]
                        student_name = student_info[0]
                        y1,x2,y2,x1 = faceLoc
                        y1, x2, y2, x1 = y1*4,x2*4,y2*4,x1*4
                        cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)
                        cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)
                        cv2.putText(img,student_name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
                        if student_id not in attended_student:
                            cv2.putText(img,student_name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
                            attended_student.append(student_id)
                            print(f"attendence of student {student_name} is going to happen")
                            markAttendance(student_id, col_idx)

                        else:
                            cv2.putText(img,"Present",(x1+6,y1+5),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
            cv2.imshow('Webcam',img)
            cv2.waitKey(1)

    elif instruct=="Next":
        print("inside Next section")
        cap.release()
        cv2.destroyAllWindows()
        update_col_index(subject, section)
        return
    else:
        print("inside stop section")
        cap.release()
        cv2.destroyAllWindows()
        update_col_index()
        sys.exit()


from typing import List

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        n = len(s)
        res = []
        if n > 12:
            return res

        def trace_back(start, path):
            # 四段ip
            if len(path) == 4:
                if start == n:  # 遍历完则加入结果，否则直接回溯
                    res.append(".".join(path))
                return

            for i in range(start, n):
                temp = s[start:i + 1]
                # 含有前导0
                if temp != "0" and temp.startswith("0"):
                    return
                # 如果满足0-255之间
                if int(temp) < 0 or int(temp) > 255:
                    return
                trace_back(i + 1, path + [temp])

        trace_back(0, [])
        return res


import unittest
from Ugly_Number_263 import Solution

"""
Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

Example 1:

Input: n = 6
Output: true
Explanation: 6 = 2 × 3

Example 2:

Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

Example 3:

Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.
"""

class Test_Case(unittest.TestCase):
    def test_answer_01(self):
        n = 6
        result = True
        self.assertEqual(Solution().isUgly(n), result)

    def test_answer_02(self):
        n = 1
        result = True
        self.assertEqual(Solution().isUgly(n), result)

    def test_answer_03(self):
        n = 14
        result = False
        self.assertEqual(Solution().isUgly(n), result)

    def test_answer_03(self):
        n = 0
        result = False
        self.assertEqual(Solution().isUgly(n), result)

if __name__ == "__main__":
    unittest.main()


import typing as tp

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm.notebook import tqdm

import dataset
from utils import Settings
from vit import ViT as SubOptimalViT

def get_vit_model() -> torch.nn.Module:
    model = SubOptimalViT(
        dim=128,
        mlp_dim=128,
        depth=12,
        heads=8,
        image_size=224,
        patch_size=32,
        num_classes=2,
        channels=3,
    ).to(Settings.device)
    return model

def get_train_loader() -> torch.utils.data.DataLoader:
    train_list = dataset.extract_dataset_globs(half=False)
    print(f"Train Data: {len(train_list)}")
    train_transforms = dataset.get_train_transforms()
    train_data = dataset.CatsDogsDataset(train_list, transform=train_transforms)
    train_loader = DataLoader(dataset=train_data, batch_size=Settings.batch_size, shuffle=True)

    return train_loader

def run_epoch(model, train_loader, criterion, optimizer) -> tp.Tuple[float, float]:
    epoch_loss, epoch_accuracy = 0, 0
    for i, (data, label) in tqdm(enumerate(train_loader), desc=f"[Train]"):
        data = data.to(Settings.device)
        label = label.to(Settings.device)
        output = model(data)
        loss = criterion(output, label)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        acc = (output.argmax(dim=1) == label).float().mean()
        epoch_accuracy += acc / len(train_loader)
        epoch_loss += loss / len(train_loader)
    return epoch_loss, epoch_accuracy

def main():
    model = get_vit_model()
    train_loader = get_train_loader()
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=Settings.lr)

    run_epoch(model, train_loader, criterion, optimizer)

if __name__ == "__main__":
    main()