from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractUser

# custom user model

class User(AbstractUser):
    first_name = models.CharField(
        _("first name"),
        max_length=30,
    )
    last_name = models.CharField(
        _("last name"),
        max_length=150,
    )
    username = models.EmailField(
        _("email address"),
        unique=True,
        error_messages={
            "unique": _("A user with that username already exists."),
        },
    )

    EMAIL_FIELD = "username"

    def __str__(self):
        return self.username

class Child_care_facility(models.Model):
    name = models.CharField("Nom de la structure", max_length=50, unique=True)
    max_child_number = models.IntegerField(
        "Places maximum",
    )
    type_of_facility = models.CharField(
        "Type de structure",
        max_length=50,
        choices=[
            ("MC", "Micro-Crèche"),
            ("C", "Crèche"),
            ("MAM", "MAM"),
            ("MC", "Crèche-Parentale"),
            ("MC", "Crèche-Municipale"),
            ("MC", "Crèche d'entreprise"),
            ("MC", "Crèche associative"),
        ],
    )
    status = models.CharField(
        "Statut",
        max_length=50,
        choices=[
            ("A", "Active"),
            ("NA", "Non Active"),
            ("EC", "En cours de création"),
        ],
    )
    address = models.ForeignKey(
        "auth_access_admin.Address",
        on_delete=models.CASCADE,
        verbose_name="Adresse",
    )
    phone = models.CharField("Téléphone", max_length=14)
    email = models.EmailField("Adresse Email")

    class Meta:
        verbose_name = "Structure de Garde"
        verbose_name_plural = "Structures de Garde"

    def __str__(self):
        return self.name

class New(models.Model):
    date_time = models.DateTimeField(
        "Horodatage",
        auto_now_add=True,
    )
    title = models.CharField(
        "Titre",
        max_length=50,
    )
    content = models.CharField(
        "Contenu texte",
        max_length=200,
        blank=True,
    )
    img_url = models.ImageField("image", upload_to="news_img")
    cc_facility = models.ForeignKey(
        Child_care_facility,
        on_delete=models.CASCADE,
        verbose_name="Structure de Garde",
    )

    class Meta:
        verbose_name = "News"
        verbose_name_plural = "News"

    def __str__(self):
        return self.title


import warnings
import numpy
from ..utilities.extractParams import *
from datetime import datetime

def getSampleMetadataFromWatersRawFiles(rawDataPath):
	"""
	Get acquisition metadata from Waters RAW files and returns them as a dataframe

	:param str rawDataPath: Path to folder of raw data
	"""

	# Get the paramters as a table
	instrumentParams = extractParams(rawDataPath, 'Waters .raw')

	# Strip any whitespace from 'Sample File Name'
	instrumentParams['Sample File Name'] = instrumentParams['Sample File Name'].str.strip()

	# Parse acqustion times
	instrumentParams['Acquired Time'] = numpy.nan
	for i in range(instrumentParams.shape[0]):
		try:
			instrumentParams.loc[i, 'Acquired Time'] = datetime.strptime(str(instrumentParams.loc[i, '$$ Acquired Date:']) + " " + str(instrumentParams.loc[i,'$$ Acquired Time:']), '%d-%b-%Y %H:%M:%S')
		except ValueError:
			pass

	# Rename '$$ Acquired Time' and '$$ Acquired Date to avoid confusion
	instrumentParams.rename(columns={'$$ Acquired Time:': 'Measurement Time'}, inplace=True)
	instrumentParams.rename(columns={'$$ Acquired Date:': 'Measurement Date'}, inplace=True)

	##
	# Detect duplicate experiment filenames
	##
	duplicateSamples = instrumentParams.loc[instrumentParams['Sample File Name'].duplicated(keep=False)]
	if duplicateSamples.size > 0:
		warnings.warn('Duplicate raw data loaded, discarding duplicates.', UserWarning)
		# Drop duplicate files
		instrumentParams = instrumentParams.loc[instrumentParams['Sample File Name'].duplicated(keep='first')==False]

	return instrumentParams


import csv

count = 0

with open("gcore_result_all.csv", "a+") as f:
	writer = csv.writer(f, delimiter=",")
	writer.writerow(["No.", "time", "likes", "comments", "title", "subtitle"])
	for i in range (0, 9):
		with open('gcore_result_{}.csv'.format(i), 'rb') as csvfile:
			spamreader = csv.reader(csvfile, delimiter=',')
			for row in spamreader:
				count += 1
				article = ', '.join(row[1:])
				writer.writerow([count, row[1], row[4], row[5], row[2], row[3]])


#!/usr/bin/python3
import glob, hashlib, json, yaml

bishop_working_dict = {"all": []}
wordlist_working_dict = {"all": []}

files = glob.glob("./sources/**/*.yml", recursive=True)

def bishop_append(title, entry, source_class):
    global bishop_working_dict

    # allow for unvalidate-able sources to be added to wordlists, but not bishop
    if "validation" not in entry.keys() or "path" not in entry.keys():
        return

    bishop_working_entry = {
        "description": entry["description"],
        "enabled": True,
        "name": title,
        "risk": "low",
        "searchString": entry["validation"],
        "url": entry["path"],
    }

    m = hashlib.md5()
    m.update(json.dumps(bishop_working_entry).encode("utf-8"))
    bishop_working_entry["uid"] = m.hexdigest()

    if source_class not in bishop_working_dict.keys():
        bishop_class_tmp = []
    else:
        bishop_class_tmp = bishop_working_dict[source_class]

    bishop_class_tmp.append(bishop_working_entry)
    bishop_working_dict[source_class] = bishop_class_tmp

def wordlist_append(title, entry, source_class):
    global wordlist_working_dict

    if "path" not in entry.keys():
        return

    if source_class not in wordlist_working_dict.keys():
        wordlist_class_tmp = []
    else:
        wordlist_class_tmp = wordlist_working_dict[source_class]

    wordlist_class_tmp.append(entry["path"])
    wordlist_working_dict[source_class] = wordlist_class_tmp

def add_to_multi_dict(title, entry, source_class):
    bishop_append(title, entry, "all")
    bishop_append(title, entry, source_class)

    wordlist_append(title, entry, "all")
    wordlist_append(title, entry, source_class)

for file_path in files:
    file_components = file_path.split("/")
    source_class = file_components[-2]

    with open(file_path, "r") as stream:
        data_loaded = yaml.safe_load(stream)

        for recon_title, recon_dict in data_loaded.items():
            add_to_multi_dict(recon_title, recon_dict, source_class)

for bishop_class, bishop_data in bishop_working_dict.items():
    out_file = f"./bishop/{bishop_class}.json"
    with open(out_file, "w") as json_target:
        json.dump(bishop_data, json_target, indent=4)

for wordlist_class, wordlist_data in wordlist_working_dict.items():
    out_file = f"./wordlists/{wordlist_class}.txt"
    wordlist = ""
    for word in wordlist_data:
        wordlist = f"{wordlist}{word}\n"
    wordlist.strip("\n")
    with open(out_file, "w") as wordlist_target:
        wordlist_target.write(wordlist)


import  re

pattern = r"([@|#]+(?P<color>[a-z]{3,})[@|#]+)([^\w])*(?P<surr>/+)(?P<amount>\d+)(?P<surr_2>/+)"

eggs = input()

valid_eggs = re.finditer(pattern, eggs)

for egg in valid_eggs:
    color = egg.group("color")
    amount = egg.group("amount")
    print(f"You found {amount} {color} eggs!")


#inbuilt max function
def compare (numb1,numb2,numb3):
    print(max(numb1,numb2,numb3))

compare(10,20,50)

def get_the_lager_number (number1,number2):
    """This function checks the larger number"""
    if number1 > number2:
        print(number1)
    elif number1 == number2:
        print("equal")

    else:
        print(number2)

get_the_lager_number(230,20)


try:
    import os
    import json
    import glob
    import argparse
    import random

    import numpy as np
    from scipy import signal as sg
    from scipy.ndimage.filters import maximum_filter
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    import scipy.misc
    from PIL import Image

    import matplotlib.pyplot as plt
except ImportError:
    print("Need to fix the installation")
    raise

K = 3

def pick_k_coordinates(lst, k):
    return None if not len(lst) else tuple(lst[i] for i in range(0, len(lst), len(lst) // k))

def pick_k_random_coordinates(lst, k):
    return None if not len(lst) else tuple(lst[i] for i in random.sample(range(0, len(lst)), k))

def find_pixels(img, real_image):
    lights = np.where(img == 19)
    lights = list(zip(lights[0], lights[1]))
    non_lights = np.where(img != 19)
    non_lights = list(zip(non_lights[0], non_lights[1]))
    coordinates_lights = pick_k_coordinates(lights, K)
    if coordinates_lights:
        cut_image(real_image, [coordinates_lights, pick_k_random_coordinates(non_lights, K)])
    # return [coordinates_lights, pick_k_random_coordinates(non_lights, K)] if coordinates_lights else []

def get_files_from_base(path, file_suffix):
    print(path, file_suffix)
    s = glob.glob(os.path.join(path, file_suffix))
    print(s)
    return s

def write_to_bin_file(value, filename):
    with open(f"./data_bin/{filename}.bin", 'wb') as file:
        file.write((value).to_bytes(24, byteorder='big', signed=False))

def write_image_to_bin_file(image, filename):
    image.astype('uint8').tofile(f"./data_bin/{filename}.bin")

def cut_image(img, pixels):
    bord_img = add_border(img)
    for coordinate in pixels[0]:
        x = coordinate[0]
        y = coordinate[1]
        write_to_bin_file(1, 'aachen_val')
        write_image_to_bin_file(bord_img[x - 40:x + 40, y - 40:y + 40, :], 'aachen_img')

    for coordinate in pixels[1]:
        x = coordinate[0]
        y = coordinate[1]
        write_to_bin_file(0, 'aachen_val')
        write_image_to_bin_file(bord_img[x - 40:x + 40, y - 40:y + 40, :], 'aachen_img')

def add_border(image):
    length, width, layers = image.shape
    length_array, width_array = np.zeros((length + 80) * 40 * 3).reshape((length + 80, 40, 3)), np.zeros(
        40 * width * 3).reshape((40, width, 3))
    image_full = np.vstack([image, width_array])
    image_full = np.vstack([width_array, image_full])
    image_full = np.hstack([length_array, image_full])
    image_full = np.hstack([image_full, length_array])
    return image_full

def main(argv=None):
    label_bases = [('./gtFine/train/aachen', '*_labelIds.png'), ('./gtFine/val', '*_labelIds.png')]
    img_bases = [('./leftImg8bit/train/aachen', '*_leftImg8bit.png'), ('./leftImg8bit/val', '*_leftImg8bit.png')]
    for i, path in enumerate(label_bases[0:1]):
        flist_1 = get_files_from_base(path[0], path[1])

    for i, path in enumerate(img_bases[0:1]):
        flist_2 = get_files_from_base(path[0], path[1])

    for index, image in enumerate(flist_1[:2]):
        print("f", flist_1)
        img_1 = np.array(Image.open(image)).astype('uint8')
        img_2 = np.array(Image.open(flist_2[index])).astype('uint8')
        find_pixels(img_1, img_2)
        plt.figure().clf()
        plt.imshow(img_1)
        plt.show(block=True)

def read_files(root_dir):

    files = glob.glob(root_dir + '/**/*.json', recursive=True)
    return files

if __name__ == '__main__':
    read_files('gtFine')


# vizualizace vzorkovaci frekvence
import numpy as np
import matplotlib.pyplot as plt

# vytvoreni datovych vektoru
x = np.linspace(0, 10 * np.pi, 1000)
y = np.sin(x)

# pole nasobku pi pro upraveni f_vz
consts = [2.1, 1, 0.2]

# smycka pro vypocet a vykresleni 3 datovych rad
for i in range(3):
    f_x = []
    f_y = []
    idx = 1
    f = 1

    # vypocet dilcich vektoru pro vzorkovani
    while f < np.max(x):
        f_x.append(f)
        f_y.append(np.sin(f))
        f += consts[i] * np.pi
        idx += 1

    # vykresleni grafu
    plt.subplot(3, 1, i + 1)
    plt.plot(x, y)
    plt.scatter(f_x, f_y, color='red')
    plt.plot(f_x, f_y)
    comment = ''
    if consts[i] == 1:
        comment = ' ... Nyquistova frekvence'
    plt.title(f'f_max = {consts[i] / 2} * f_vz{comment}', fontsize=15)
    plt.grid()

    if i == 2:
        plt.xlabel('Čas [s]')

    plt.ylabel('Amplituda [-]')

plt.subplots_adjust(hspace=0.37)
plt.show()


# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?

def prime_factor():

    factors=[2,3]
    i=1
    target=600851475143

    while True:
        nums = [6 * i - 1, 6 * i + 1]
        if nums[1] >= (target**0.5)+1:
            break
        for n in nums:
            flag = 0
            for div in range(5, int(n ** 0.5) + 1, 6):
                if n % div == 0 or n % (div + 2) == 0:
                    flag = 1
                    break
            if flag == 0 and target%n==0:
                factors.append(n)
        i += 1

    return factors[-1]

print(prime_factor())


from flask import Flask,redirect,url_for,render_template,request
import numpy as np
import pickle
import sklearn
import os

file_path = 'amit.pkl'

if os.path.isfile(file_path):
    print("File exists")
else:
    print("File does not exist")

model = pickle.load(open('amit.pkl', 'rb'))

app = Flask(__name__)

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

@app.route('/predict',methods = ["POST"])
def home():
    sy1 = request.form['s1']
    sy2 = request.form['s2']
    sy3 = request.form['s3']
    sy4 = request.form['s4']
    sy5 = request.form['s5']
    sy6 = request.form['s6']
    sy7 = request.form['s7']
    sy8 = request.form['s8']
    sy9 = request.form['s9']
    sy10 = request.form['s10']

    arr = np.array([[sy1,sy2,sy3,sy4,sy5,sy6,sy7, sy8, sy9,sy10]])
    pred = model.predict(arr)
    return render_template('result.html',data=pred)
if __name__ == '__main__':
    app.run(debug=True)


import requests
import json

def scrape_func(term,offset,limit):
    api_url = f"https://api.yelp.com/v3/businesses/search?term={term}&location=manhattan&limit={limit}&offset={offset}"
    payload={}
    headers = {
    'Authorization': '<api-key>'
    }

    response = requests.request("GET", api_url, headers=headers, data=payload)
    restaurant_list = json.loads(response.text)["businesses"]
    return restaurant_list

def append_to_file(term,new_data):
    filename = f"{'_'.join(term.lower().split())}.json"
    try:
        file = open(filename,'x+')
        file_data = {}
        file_data["restaurants"] = []
    except:
        file = open(filename,'r+')
        file_data = json.load(file)

    for row in new_data:
        file_data["restaurants"].append(row)
    file.seek(0)
    json.dump(file_data, file, indent = 4)

def search_for(term):
    totalLimit = 1000
    limit = 50
    offset = 0
    while limit+offset <= totalLimit:
        output = scrape_func(term,offset,limit)
        append_to_file(term,output)
        offset += limit

if __name__ == "__main__":
    terms = ["Italian restaurants","Chinese Restaurants","Indian restaurants","Mexican restaurants", "Japanese restaurants"]
    for term in terms:
        search_for(term)


import os
import shutil
import unittest
from http.server import HTTPServer
from threading import Thread

from tests.sandbox_server import RequestHandler

from sitemap_generator.crawler import SitemapGenerator
from tests.variables import host, port, expected_sitemap

class TestCase(unittest.TestCase):

    def setUp(self):
        self.background_server = Thread(target=self.server, daemon=True)
        self.background_server.start()
        self.url = 'http://{}:{}'.format(host, port)
        self.output_dir = os.path.join(os.getcwd(), 'tmp')
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)

    def test_crawler(self):
        generator = SitemapGenerator(self.url, path=self.output_dir, timeout=None)
        generator.generate()

        with open(os.path.join(self.output_dir, '{}:{}.xml').format(host, port)) as sitemap:
            assert sitemap.read() == expected_sitemap

    def tearDown(self):
        shutil.rmtree(self.output_dir)
        self.sandbox_server.server_close()

    def server(self):
        self.sandbox_server = HTTPServer((host, port), RequestHandler)
        self.sandbox_server.serve_forever()

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


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 28 10:53:13 2019

@author: dinesh
"""

arr = [1, 4, 5, 3, 2]

for i in arr:
    print(i)


#Problem H. Closest point

from math import sqrt
x, y = map(int, input().split())

def distance(num):
    return sqrt((x-num[0])**2 + (y-num[1]) **2)

n = int(input())
l = []
for i in range(n):
    x1, y1 = map(int, input().split())
    l.append((x1, y1))
#print(l)

arr = sorted(l, key = distance)
#print(arr)
for c in arr:
    print(c[0], c[1])

'''for i in range(n):
    x1, y1 = list(map(int, input().split()))
    d = sqrt((x1-x)**2 + (y1-y) **2)
    l.append(d)
    dic[d] = x1, y1
print(l)
print("-"*20)
for key, value in dic.items():
    print(*value)'''


#
# @lc app=leetcode.cn id=78 lang=python3
#
# [78] 子集
#

# @lc code=start
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        ## 递归
        # if nums==[]:
        #     return [[]]
        # n = len(nums)
        # def help(index):
        #     if index==0:
        #         return [[nums[index]], []]
        #     else:
        #         temp = help(index-1)
        #         ans = temp + [[nums[index]] + num for num in temp]
        #         return ans
        # ans = help(n-1)
        # print(ans)
        # return ans

        ## 迭代
        # ans = [[]]
        # for i in nums:
        #     ans = ans+[[i]+num for num in ans]
        # return ans

        ## 递归 回溯
        res = []
        n = len(nums)

        def helper(index, tmp):# 求取第index~n的元素为首的组合，因为去重，所以j in range(index,n)
            res.append(tmp) ### 每一次迭代的工作是将tmp+[nums[index]]加入数组
            for j in range(index,n):
                helper(j+1, tmp+[nums[j]])

        helper(0, [])
        return res
# @lc code=end


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the repeatedString function below.
def repeatedString(s, n):
    count = 0
    if s == 'a':
        return n
    elif n > 10000:
        half = n//len(s)
        remainder = n%len(s)
        for i in range(0, len(s)):
            if s[i%len(s)] == 'a':
                count+=1
        count*=half
        for i in range(0,remainder):
            if s[i%len(s)] == 'a':
                count+=1
        return count
    else:
        for i in range(0, n):
            if s[i%len(s)] == 'a':
                count+=1
        return count
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    n = int(input())

    result = repeatedString(s, n)

    fptr.write(str(result) + '\n')

    fptr.close()


import argparse
import cv2
from matplotlib import pyplot as plt

ap = argparse.ArgumentParser()

ap.add_argument("-i", "--image", required=True,
                help="input image's path")

args = vars(ap.parse_args())

# load the image
image = cv2.imread(args["image"])

# convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# blur, to remove sharp edges
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# adaptively thresholding to make binary
thresholded = cv2.adaptiveThreshold(
        blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

# OPTIONAL - use edge detection
edged = cv2.Canny(thresholded, 30, 200)

# find countours in the image
im2, contours, hierarchy = cv2.findContours(
    thresholded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

rects = []
peris = []

for c in contours:
    # approximating the contour
    peri = cv2.arcLength(c, True)
    peris.append(peri)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    # check if the approximated contour has four points
    # if so, it can be labelled as a rectangle
    if len(approx) == 4:
            rects.append(approx)

# drawing the countours
countered = cv2.drawContours(image.copy(), rects, -1, (255, 0, 0), 3)

# plotting the images
images = [image, thresholded, edged, countered]
titles = ["original", "thresholded", "edge detection", "result"]

for i in range(4):
    plt.subplot(2, 2, i+1)
    plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([])
    plt.yticks([])
plt.show()


import numpy as np
import pyaudio

# Set up the audio stream
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=44100,
                output=True)

# Define the pentatonic scale frequencies
pentatonic_scale = [261.63, 293.66, 329.63, 392.00, 440.00, 523.25]

# Generate and play the sine waves
for freq in pentatonic_scale:
    duration = 1.0  # Duration in seconds
    t = np.linspace(0, duration, int(duration * 44100), False)
    samples = np.sin(2 * np.pi * freq * t)
    stream.write(samples.astype(np.float32).tobytes())

# Clean up the audio stream and terminate PyAudio
stream.stop_stream()
stream.close()
p.terminate()


from typing import Dict, Optional, Tuple

import torch
from transformers import TransfoXLLMHeadModel

from archai.nlp.models.hf_transfo_xl.config_hf_transfo_xl import HfTransfoXLConfig
from archai.nlp.models.model_base import ArchaiModel

class HfTransfoXL(ArchaiModel):
    """Huggingface's Transformer-XL standard architecture.

    """

    def __init__(self, **kwargs) -> None:
        """Initializes the class by creating compatible configuration and model objects.

        """

        super().__init__()

        self.config = HfTransfoXLConfig(**kwargs)
        self.model = TransfoXLLMHeadModel(self.config)

        if self.config.tie_weight:
            self.model.tie_weights()

    def forward(self,
                input_ids: torch.Tensor,
                labels: Optional[torch.Tensor] = None,
                mems: Optional[torch.Tensor] = None,
                past_key_values: Optional[torch.Tensor] = None,
                output_loss: Optional[bool] = True,
                output_prediction_scores: Optional[bool] = False
                ) -> Tuple[torch.Tensor, ...]:
        # Labels are the same as input_ids because they will be shifted inside the model
        if output_loss:
            outputs = self.model(input_ids=input_ids,
                                 labels=input_ids,
                                 mems=mems)

            return (outputs.losses, None, outputs.mems, None)

        if output_prediction_scores:
            outputs = self.model(input_ids=input_ids,
                                 mems=mems)

            return (None, outputs.logits, outputs.mems, None)

    def get_params(self) -> Dict[str, int]:
        params = {}

        params['embedding'] = self.get_params_from_layer(['AdaptiveEmbedding'])
        params['softmax'] = self.get_params_from_layer(['ProjectedAdaptiveLogSoftmax'])
        params['attention'] = self.get_params_from_layer(['RelPartialLearnableMultiHeadAttn'])
        params['ff'] = self.get_params_from_layer(['PositionwiseFF'])

        params['non_embedding'] = params['softmax'] + params['attention'] + params['ff']
        params['total'] = params['non_embedding'] + params['embedding']

        return params

    def reset_length(self, tgt_len: int, ext_len: int, mem_len: int) -> None:
        if tgt_len < 1:
            raise ValueError(f'tgt_len: {tgt_len} should be >= 1.')
        if ext_len < 0:
            raise ValueError(f'ext_len: {ext_len} should be >= 0.')
        if mem_len < 0:
            raise ValueError(f'mem_len: {mem_len} should be >= 0.')

        self.model.config.tgt_len = tgt_len
        self.model.config.mem_len = mem_len
        self.model.config.ext_len = ext_len


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

LW = 3
MS = 8
FS = 22
lightGray = "#D0D0D0"
lightOrange = '#FFC29B'
matplotlib.rcParams['axes.linewidth'] = 3.5 #set the value globally

targ_dir = ['211123_lstm_tskone_direct_0_05hu_lr2.00e-2','211123_lstm_tskone_context_0_05hu_lr9.00e-4']
ccs = []
for dir_idx,dir in enumerate(targ_dir):
    ccs.append(np.load('./results/'+dir+'/cc.npy'))

for i in range(0,len(ccs)):
    plt.plot(np.mean(ccs[i],axis=1),'.-')
plt.savefig('cc.png')


from turtle import Turtle
from random import randint

class Car(Turtle):
    def __init__(self, current_level):
        super().__init__()
        self.shape('square')
        self.shapesize(stretch_wid=1, stretch_len=2)
        self.color((randint(0, 255), randint(0, 255), randint(0, 255)))
        self.penup()
        self.goto(320, randint(-250, 250))
        self.setheading(180)
        self.mph = 10 + 2*current_level
        self.dead = False

    def drive(self):
        self.forward(self.mph)

    def speed_up(self):
        if not self.dead:
            self.mph += 2

    def off_screen(self):
        self.mph = 0
        self.dead = True


import pdb
import shutil
import argparse
from glob import glob
from tqdm import tqdm
from typing import Tuple
from copy import deepcopy
from collections import OrderedDict
from multiprocessing.pool import Pool

import numpy as np
import nibabel as nib
import SimpleITK as sitk
import scipy.stats as ss
from skimage import transform
from medpy.metric import dc, hd95

from batchgenerators.utilities.file_and_folder_operations import *
from nnunet.dataset_conversion.utils import generate_dataset_json
from nnunet.paths import nnUNet_raw_data, preprocessing_output_dir
from nnunet.utilities.file_conversions import convert_2d_image_to_nifti

class ISLES22():
    def __init__(self, root):
        self.root  = root
        self.data_dict = {}

    def load_data(self):
        dwi_folder    = 'dwi-brain-mri'
        adc_folder    = 'adc-brain-mri'
        flair_folder  = 'flair-brain-mri'

        self.dwi_path   = glob(os.path.join(self.root, dwi_folder, '*.mha'))[0]
        self.adc_path   = glob(os.path.join(self.root, adc_folder, '*.mha'))[0]
        self.flair_path = glob(os.path.join(self.root, flair_folder, '*.mha'))[0]

def reimplement_resize(image_file, target_file, resample_method=sitk.sitkLinear):
    """
    Respacing file to target space size
    :param image_file: sitk.SimpleITK.Image
    :param target_spacing: np.array([H_space, W_space, D_space])
    :resample_method: SimpleITK resample method (e.g. SimpleITK.sitkLinear, SimpleITK.sitkNearestNeighbor)
    :return: resampled_image_file: sitk.SimpleITK.Image
    """
    if isinstance(image_file, str):
        image_file = sitk.ReadImage(image_file)
    elif isinstance(image_file, np.ndarray):
        image_file = sitk.GetImageFromArray(image_file)
    elif type(image_file) is not sitk.SimpleITK.Image:
        assert False, "Unknown data type to respaceing!"

    if isinstance(target_file, str):
        target_file = sitk.ReadImage(target_file)
    elif isinstance(target_file, np.ndarray):
        target_file = sitk.GetImageFromArray(target_file)
    elif type(target_file) is not sitk.SimpleITK.Image:
        assert False, "Unknown data type to respaceing!"

    # set target size
    target_origing   = image_file.GetOrigin()
    target_direction = image_file.GetDirection()
    target_spacing   = target_file.GetSpacing()
    target_size      = target_file.GetSize()

    # pdb.set_trace()
    # initialize resampler
    resampler_image = sitk.ResampleImageFilter()
    # set the parameters of image
    resampler_image.SetReferenceImage(image_file)  # set rasampled image meta data same to origin data
    resampler_image.SetOutputOrigin(target_origing)
    resampler_image.SetOutputDirection(target_direction)  # set target image space
    resampler_image.SetOutputSpacing(target_spacing)  # set target image space
    resampler_image.SetSize(target_size)  # set target image size
    if resample_method == sitk.sitkNearestNeighbor:
        resampler_image.SetOutputPixelType(sitk.sitkUInt8)
    else:
        resampler_image.SetOutputPixelType(sitk.sitkFloat32)
    resampler_image.SetTransform(sitk.Transform(3, sitk.sitkIdentity))
    resampler_image.SetInterpolator(resample_method)

    # launch the resampler
    resampled_image_file = resampler_image.Execute(image_file)
    resampled_image_file = sitk.GetArrayFromImage(resampled_image_file)

    return resampled_image_file

def load_pkl(pkl_path):
    with open(pkl_path, 'rb') as f:
        pkl_dict = pickle.load(f)
    return pkl_dict

if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input_folder', help="root_path of 5 folds", required=True)
    parser.add_argument('-o', "--output_folder", required=True, help="folder for saving evaluation csv")
    parser.add_argument('-m', '--model_type', help='model_type, required.', required=True)
    parser.add_argument('-f', '--fold_index', default=0, help='evaluation_fold, required.', required=True)
    args = parser.parse_args()

    input_folder   = args.input_folder
    output_folder  = args.output_folder
    model_type     = args.model_type
    fold_index     = args.fold_index

    raw_data_dir = 'input/images'
    dataset_ISLES22 = ISLES22(raw_data_dir)
    dataset_ISLES22.load_data()

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    files_npzs = sorted(glob(os.path.join(input_folder, model_type, fold_index, '*.npz')))

    for file_npz in tqdm(files_npzs):
        file_pkl = file_npz.replace('npz', 'pkl')

        predict_softmax = np.load(file_npz)['softmax']

        pkl_dict = load_pkl(file_pkl)
        origin_size = pkl_dict['original_size_of_raw_data']
        origin_bbox = pkl_dict['crop_bbox']
        origin_array = np.zeros((2, origin_size[0], origin_size[1], origin_size[2]), dtype=np.float32)
        origin_array[0] = 1.0

        origin_array[:,
                    origin_bbox[0][0]:origin_bbox[0][1],
                    origin_bbox[1][0]:origin_bbox[1][1],
                    origin_bbox[2][0]:origin_bbox[2][1]] = predict_softmax.astype(np.float32)

        target_array_shape = sitk.GetArrayFromImage(sitk.ReadImage(dataset_ISLES22.dwi_path)).shape
        target_array = np.zeros((2, target_array_shape[0], target_array_shape[1], target_array_shape[2]), dtype=np.float32)

        target_array[0] = reimplement_resize(origin_array[0], dataset_ISLES22.dwi_path)
        target_array[1] = reimplement_resize(origin_array[1], dataset_ISLES22.adc_path)

        target_file = os.path.join(output_folder, file_npz.split('/')[-1])

        np.savez(target_file, softmax=target_array)


from typing import List
import pdb

solution_json = {
    "date": "2021/5/4",
    "design": 10,
    "coding": 21,
    "runtime": "1608 ms",
    "memory": "518.2 MB"
}

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        d = False

        val_path = {}
        def go(n, path):

            if d:
                print(n.val, path)

            val_path[n.val] = path

            if n.left != None:
                left_path = path + [n.left.val]
                go(n.left, left_path)

            if n.right != None:
                right_path = path + [n.right.val]
                go(n.right, right_path)

        path = [root.val]
        go(root, path)

        p_path = val_path[p.val]
        q_path = val_path[q.val]

        if d:
            print(p_path)
            print(q_path)

        n = len(p_path)
        if n > len(q_path):
            n = len(q_path)

        count = 0
        for i in range(n):
            if p_path[i] != q_path[i]:
                break
            count += 1

        if d:
            print('i = %d, count = %d' % (i, count))

        out = TreeNode(p_path[count-1])
        #pdb.set_trace()
        return out


# two-pointer
# https://discuss.leetcode.com/topic/21800/python-different-solutions-two-pointer-dictionary-binary-search
# 二分法，哈希法，二分法
def twoSum1(self, numbers, target):
    l, r = 0, len(numbers)-1
    while l < r:
        s = numbers[l] + numbers[r]
        if s == target:
            return [l+1, r+1]
        elif s < target:
            l += 1
        else:
            r -= 1

# dictionary
def twoSum2(self, numbers, target):
    dic = {}
    for i, num in enumerate(numbers):
        if target-num in dic:
            return [dic[target-num]+1, i+1]
        dic[num] = i

# binary search
def twoSum(self, numbers, target):
    for i in xrange(len(numbers)):
        l, r = i+1, len(numbers)-1
        tmp = target - numbers[i]
        while l <= r:
            mid = l + (r-l)//2
            if numbers[mid] == tmp:
                return [i+1, mid+1]
            elif numbers[mid] < tmp:
                l = mid+1
            else:
                r = mid-1


import tensorflow as tf
from tensorflow.lite.testing.zip_test_utils import create_tensor_data
from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests
from tensorflow.lite.testing.zip_test_utils import register_make_test_function

def make_unsorted_segment_tests(options, unsorted_segment_op):
  """Make a set of tests for given unsorted_segment op."""
  test_parameters = [{
      "data_shape": [[5]],
      "segment_id": [[0, 1, 1, 0, 1]],
      "num_segments": [2],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }, {
      "data_shape": [[2, 3, 4], [2, 5, 2]],
      "segment_id": [[0, 1]],
      "num_segments": [2],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }, {
      "data_shape": [[4]],
      "segment_id": [[0, 0, 1, 8]],
      "num_segments": [9],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }, {
      "data_shape": [[3]],
      "segment_id": [[-1, -2, -1]],
      "num_segments": [1],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }, {
      "data_shape": [[3]],
      "segment_id": [[-1, 0, 1]],
      "num_segments": [2],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }, {
      "data_shape": [[3, 2]],
      "segment_id": [[-1, 0, 0]],
      "num_segments": [1],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }, {
      "data_shape": [[3, 2]],
      "segment_id": [[-1, -2, -1]],
      "num_segments": [1],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }, {
      "data_shape": [[4]],
      "segment_id_shape": [[4]],
      "segment_id_min": [0],
      "segment_id_max": [1],
      "num_segments": [2],
      "dtype": [tf.int32, tf.float32],
      "segment_id_2": [[0, 0]],
      "num_segments_2": [1],
      "multi_node": [1]
  }, {
      "data_shape": [[2, 2, 3]],
      "segment_id": [[[1, 2], [3, 4]], [4, 5],
                     [[[1, 2, 3], [3, 4, 5]], [[1, 2, 4], [0, 0, -1]]]],
      "num_segments": [10],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }, {
      "data_shape": [[2, 0, 3]],
      "segment_id": [[1, 1]],
      "num_segments": [2],
      "dtype": [tf.int32, tf.float32],
      "multi_node": [0]
  }]

  def build_graph_one_node(parameters):
    data_tensor = tf.compat.v1.placeholder(
        dtype=parameters["dtype"], name="data", shape=parameters["data_shape"])
    segment_ids_tensor = tf.constant(
        parameters["segment_id"], dtype=tf.int32, name="segment_ids")
    num_segments_tensor = tf.constant(
        parameters["num_segments"],
        dtype=tf.int32,
        shape=[],
        name="num_segments")
    output = unsorted_segment_op(data_tensor, segment_ids_tensor,
                                 num_segments_tensor)
    return [data_tensor], [output]

# test cases for handling dynamically shaped input tensor
  def build_graph_multi_node(parameters):
    data_tensor = tf.compat.v1.placeholder(
        dtype=parameters["dtype"], name="data", shape=parameters["data_shape"])
    segment_ids_tensor = tf.compat.v1.placeholder(
        dtype=tf.int32,
        name="segment_ids",
        shape=parameters["segment_id_shape"])
    num_segments_tensor = tf.constant(
        parameters["num_segments"],
        dtype=tf.int32,
        shape=[],
        name="num_segments")
    intermediate_tensor = unsorted_segment_op(data_tensor, segment_ids_tensor,
                                              num_segments_tensor)
    segment_ids_tensor_2 = tf.constant(
        parameters["segment_id_2"], dtype=tf.int32, name="segment_ids_2")
    num_segments_tensor_2 = tf.constant(
        parameters["num_segments_2"],
        dtype=tf.int32,
        shape=[],
        name="num_segments_2")
    output = unsorted_segment_op(intermediate_tensor, segment_ids_tensor_2,
                                 num_segments_tensor_2)
    return [data_tensor, segment_ids_tensor], [output]

  def build_graph(parameters):
    multi_node = parameters["multi_node"]
    if multi_node:
      return build_graph_multi_node(parameters)

    return build_graph_one_node(parameters)

  def build_inputs_one_node(parameters, sess, inputs, outputs):
    data_value = create_tensor_data(
        parameters["dtype"], shape=parameters["data_shape"])
    return [data_value], sess.run(
        outputs, feed_dict=dict(zip(inputs, [data_value])))

  def build_inputs_multi_node(parameters, sess, inputs, outputs):
    data_value = create_tensor_data(
        dtype=parameters["dtype"], shape=parameters["data_shape"])
    segment_id_value = create_tensor_data(
        dtype=tf.int32,
        shape=parameters["segment_id_shape"],
        min_value=parameters["segment_id_min"],
        max_value=parameters["segment_id_max"])
    return [data_value, segment_id_value], sess.run(
        outputs, feed_dict=dict(zip(inputs, [data_value, segment_id_value])))

  def build_inputs(parameters, sess, inputs, outputs):
    multi_node = parameters["multi_node"]
    if multi_node:
      return build_inputs_multi_node(parameters, sess, inputs, outputs)

    return build_inputs_one_node(parameters, sess, inputs, outputs)

  make_zip_of_tests(options, test_parameters, build_graph, build_inputs)

@register_make_test_function()
def make_unsorted_segment_prod_tests(options):
  make_unsorted_segment_tests(options, tf.math.unsorted_segment_prod)

@register_make_test_function()
def make_unsorted_segment_max_tests(options):
  make_unsorted_segment_tests(options, tf.math.unsorted_segment_max)

@register_make_test_function()
def make_unsorted_segment_min_tests(options):
  make_unsorted_segment_tests(options, tf.math.unsorted_segment_min)

@register_make_test_function()
def make_unsorted_segment_sum_tests(options):
  make_unsorted_segment_tests(options, tf.math.unsorted_segment_sum)


#!/usr/bin/env python

"""
    setup.py file for SWIG
"""
from setuptools import setup
from setuptools.command.build_ext import build_ext
from distutils.core import setup, Extension
class BuildExt(build_ext):
    def build_extensions(self):
        super(BuildExt, self).build_extensions()

test_module = Extension('_PPR',
                        sources=['precompute_wrap.cxx','precompute/Propagation.cpp'],
                        swig_opts=['-c++'],
                        extra_compile_args=['-std=c++11', '-O3','-pthread','-march=core2','-lcnpy','-lz'],
                        extra_link_args=['-std=c++11', '-O3','-pthread','-march=core2','-lcnpy','-lz'])

setup(name = 'PPR',
        version = '0.1',
        cmdclass={'build_ext': BuildExt},
        ext_modules = [test_module],
        py_modules = ['PPR'],)


import logging

__author__ = "Miguel Angel Muñoz González (magonzalez at fortinet.com)"
__copyright__ = "Copyright 2018, Fortinet, Inc."
__credits__ = "Miguel Angel Muñoz"
__license__ = "Apache 2.0"
__version__ = "0.6"
__maintainer__ = "Miguel Ángel Muñoz"
__email__ = "magonzalez at fortinet.com"
__status__ = "Development"

logger = logging.getLogger(__name__)  # pylint: disable=C0103

class YangUtil:

    @staticmethod
    def remove_urn(text):
        return text[text.find('}') + 1:]

    @staticmethod
    def contains_operation(netconf_data):
        # Checks if current tag contains an operation

        for attrib in netconf_data.attrib:
            if YangUtil.remove_urn(attrib) == "operation":
                return True
        return False

    @staticmethod
    def contains_mkey(netconf_data):
        # Checks if current tag contains mkey
        return 'mkey' in netconf_data.attrib

    @staticmethod
    def extract_operation(netconf_data):
        for elem in netconf_data.iter():
            for attrib in elem.attrib:
                if YangUtil.remove_urn(attrib) == "operation":
                    return elem.attrib[attrib]

        raise Exception("No operation found in netconf data")

    @staticmethod
    def extract_mkey(netconf_data):
        mkey = netconf_data.attrib['mkey']

        for elem in netconf_data:
            if YangUtil.remove_urn(elem.tag) == mkey:
                return elem.text

        raise Exception("Error, mkey: '{0}' not found in data: {1}", format(mkey), format(netconf_data))

    @staticmethod
    def extract_content_under_operation(netconf_data):
        # Algorithm to extract data will be: Get every content inside the tag
        # that contains 'operation' attribute

        content = {}

        for elem in netconf_data.iter():
            for attrib in elem.attrib:
                if YangUtil.remove_urn(attrib) == "operation":
                    for avp in elem:
                        content[YangUtil.remove_urn(avp.tag)] = avp.text
        return content

class Yang2RestConverter(object):

    def _extract_path_until_final_resource(self, netconf_data, add_deepest_key=False):
        # Algorithm to calculate the rest of the path consists on going down until
        # a tag with 'operation' attribute is found. That tag will
        # be the last one to be included in the final url
        path = ""
        while not YangUtil.contains_operation(netconf_data):
            path += "/" + YangUtil.remove_urn(netconf_data.tag)
            if YangUtil.contains_mkey(netconf_data):
                path += "/" + YangUtil.extract_mkey(netconf_data)
                if len(netconf_data)>1:
                    # In order to continue navigation down in the yang model,
                    # it is assumed that the mkey is in position 0 and the next
                    # tag in position 1
                    netconf_data = netconf_data[1]
                else:
                    break
            else:
                if len(netconf_data)>0:
                    netconf_data = netconf_data[0]
                else:
                    break

        if YangUtil.contains_operation(netconf_data):
            path += "/" + YangUtil.remove_urn(netconf_data.tag)
            return path
        else:
            return path

    def _extract_name_content_operation(self, netconf_data):

        name = YangUtil.remove_urn(netconf_data.tag)
        logger.debug("Name: %s", name)

        operation = None
        try:
            operation = YangUtil.extract_operation(netconf_data)
            logger.debug("Operation: %s", operation)
        except Exception:
            logger.debug("Operation not found, is this a 'get'?")

        is_a_modification = operation == "delete" or operation == "replace" or operation=="merge"

        remaining_path = self._extract_path_until_final_resource(netconf_data,
                                                                 add_deepest_key=is_a_modification)
        logger.debug("Remaining path: %s", remaining_path)

        content = YangUtil.extract_content_under_operation(netconf_data)
        logger.debug("Content: %s", content)

        return remaining_path, content, operation

    def _extract_path_content_operation(self, netconf_data):
        path = YangUtil.remove_urn(netconf_data.tag)
        logger.debug("Path: %s", path)

        (name, content, operation) = self._extract_name_content_operation(netconf_data[0])

        return path + name, content, operation

    def extract_url_content_operation(self, netconf_data):
        api_type = YangUtil.remove_urn(netconf_data.tag)

        logger.debug("Api Type: %s", api_type)

        if api_type == "cmdb" or api_type == "monitor":
            (path, content, operation) = self._extract_path_content_operation(netconf_data[0])
        else:
            raise Exception("Main tag is not cmdb or monitor. Cannot continue.")

        return api_type + "/" + path, content, operation


import csv

# creates file object
customers = open("customers.csv", "r")

outfile = open("customer_country.csv", "w")

# reads file object of customers, creates CSV object - delimiter seperates values by comma
customer_file = csv.reader(customers, delimiter=",")

# to skip a line if the file contains a header record
next(customer_file)

# advances through each line in file one at a time
count = 1
for record in customer_file:

    outfile.write(record[1] + "," + record[2] + "," + record[4] + "\n")
    count += 1
    # print(type(record))
    # causes pause until keystroke - input()

print("Number of customers:", count)

outfile.close()


import random as r
import math as m
T = 100
P = 86
print(T)

def f(S, Q):
    return 1 / (1 + m.exp(Q - S))

for t in range(T):
    print(P)
    Q = [r.random() * 6 - 3 for i in range(10000)]
    for i in range(100):
        S = r.random()
        print(''.join('1' if (i == 0 and r.random() > 0.5) or f(S, q) > 0.5 else '0' for q in Q))


from flask import Flask, render_template,request
import socket

app = Flask(__name__)

@app.route('/')
def mainfunc():

    hostName = socket.gethostname()
    return render_template('response.html', hostname=hostName, content_type='application/json')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)


import json

# define the username of the user whose visits we want to increment
def update_user_in_file(username):

    # read the data from the file
    with open('./data/users.json', 'r') as f:
        users = json.load(f)

    # find the user in the list
    for user in users:
        if user["username"] == username:
            # increment the user's visits
            user["visits"] += 1
            break

    # write the updated data back to the file
    with open('./data/users.json', 'w') as f:
        json.dump(users, f)

    # print a message to confirm that the file has been updated
    print("File has been updated!")


#!/usr/bin/env python
import os
import sys
import re
import optparse
import textwrap
import shutil
import time
from optparse import OptionParser

def main():
  parser = OptionParser()
  parser.add_option("-f", "--file", action="store", dest = "range_file", help = "input range file")
  parser.add_option("-o", "--output", action = "store", dest = "output", help = "output file")
  parser.add_option("-i", "--index", action="store", dest = "svr_idx", help = "server index (of current server [0, count-1]")
  parser.add_option("-c", "--count", action="store", dest = "svr_count", help="number of server in this cluster")
  (options,args) = parser.parse_args(sys.argv)

  if not options.range_file or not options.svr_idx or not options.svr_count or not options.output:
    parser.print_help()
    sys.exit(1)

  svr_count = int(options.svr_count)
  svr_idx = int(options.svr_idx)
  tablet_count = 0

  range_input = open(options.range_file, "r")

  for line in range_input:
    tablet_count += 1

  tablet_count_pern = tablet_count/svr_count

  tablet_beg = tablet_count_pern * svr_idx
  tablet_end = tablet_beg + tablet_count_pern
  if svr_idx == svr_count - 1:
    tablet_end = tablet_count

  range_input.seek(0)

  idx = 0
  output = open(options.output, "w")
  for line in range_input:
    if idx % svr_count == svr_idx:
      output.write(line)
    idx += 1

if __name__ == "__main__":
  main()


# -*- coding: utf-8 -*-
"""
Created on Wed Aug  5 16:29:29 2020

@author: kylab
"""

import pandas as pd
import numpy as np
from datetime import datetime

class SA_report():
    def __init__(self):
        self.Total_Record_time=0
        self.Record_start=''
        self.Record_end=''
        self.baseline=0
        self.meanSPO2=0
        self.LowestSPO2=0
        self.ratio_under90=0
        self.ODE = 0
        self.ODE4 = 0
        self.ODE_new = 0
        self.AHI = 0
        self.AHI_new =0
        self.osa_level=''

    def get_mode(self,arr):
        mode = []
        arr_appear = dict((a, arr.count(a)) for a in arr)
        if max(arr_appear.values()) == 1:  # 如果最大的出現為1
            return  # 則沒有眾數
        else:
            for k, v in arr_appear.items():  # 否則，出現次數最大的數字，就是眾數
                if v == max(arr_appear.values()):
                    mode.append(k)
        return mode

    def f_getSAReport(self,**kwargs):
        Threshold=3
        Activity_Threshold=2
        Duration_Time=75

        if '.xls' in kwargs['filename']:
            xls = pd.ExcelFile(kwargs['filename'])
            sheetname='SPO2'#input("Please enter sheetname: ")
            sheetX = xls.parse(sheetname)
            sheetkeys=sheetX.keys()
            sheetX=sheetX.set_index(sheetkeys[0])
            data_df=sheetX

        elif '.txt' in kwargs['filename']:
            with open(kwargs['filename'], 'r') as f:
                text = []
                data_dic={}
                for line in f:
                    text.append(line)
                for  i in range(len(text)):
                    text[i]=text[i].replace("\n","")
                    templist=text[i].split(",")
                    try:
                        timeformat='%Y-%m-%d %H:%M:%S'
                        datetime.strptime(templist[0],timeformat)
                        data_dic[templist[0]]={'O2':int(templist[1]),'HR':int(templist[2]),'ACT':float(templist[3])}
                    except:
                        continue
                data_df=pd.DataFrame.from_dict(data_dic).T
        elif kwargs['rawtxt']!='':
            rawtxt=kwargs['rawtxt'].replace("/","-")
            rawlist=rawtxt.split("\r\n")
            for  i in range(len(rawlist)):
                templist=rawlist[i].split(",")
                if templist[0]==";O2" and int(templist[2])>0 and int(templist[2])<100:
                    templist.remove(";O2")
                    data_dic[templist[0]]={'O2':int(templist[1]),'HR':int(templist[2]),'ACT':int(templist[3])/2}

            data_df=pd.DataFrame.from_dict(data_dic).T

        listdatakey=data_df.index
        TimeInBed = len(listdatakey)

        SPO2_denoise=[]
        SPO2_under90=[]
        SPO2_origin_loc=[]
        for i in range(TimeInBed):
            if data_df['O2'][listdatakey[i]]==0 or data_df['O2'][listdatakey[i]]==-1 or data_df['O2'][listdatakey[i]]>100 or data_df['O2'][listdatakey[i]]<70 or data_df['ACT'][listdatakey[i]]>Activity_Threshold:
                TimeInBed-=1
                continue
            SPO2_denoise.append(data_df['O2'][listdatakey[i]])
            SPO2_origin_loc.append(i)
            if data_df['O2'][listdatakey[i]]<90:
                SPO2_under90.append(data_df['O2'][listdatakey[i]])

        diffSPO2=np.diff(np.array(SPO2_denoise))#ISPO2 in Charlie thesis
        NPSPO2=[]
        RealIdx=[]

        for i in range(len(diffSPO2)):
            if diffSPO2[i]!=0:
                NPSPO2.append(SPO2_denoise[i+1])
                RealIdx.append(i+1)

        NPNPSPO2=np.diff(np.array(NPSPO2))
        IndMin=[]
        IndMax=[]
        SPO2_mark_location =[np.nan] * TimeInBed

#        for i in range(len(NPNPSPO2)-1):
#            if NPNPSPO2[i+1]*NPNPSPO2[i]>0:
#                IndMin.append(i+1)   #trough
#            else:
#                IndMax.append(i+1)   #peak

        for i in range(len(NPNPSPO2)-1):
            if np.sign(NPNPSPO2[i+1]) - np.sign(NPNPSPO2[i])>0:
                IndMin.append(i+1)   #trough
            elif np.sign(NPNPSPO2[i+1]) - np.sign(NPNPSPO2[i])<0:
                IndMax.append(i+1)   #peak

        peak_values=[]
        peak_values_idx=[]
        trough_values=[]
        trough_values_idx=[]

        for i in range(len(IndMax)):
            peak_values.append(NPSPO2[IndMax[i]])
            peak_values_idx.append(RealIdx[IndMax[i]])
            SPO2_mark_location[RealIdx[IndMax[i]]] = 'peak,' +str(SPO2_origin_loc[RealIdx[IndMax[i]]]) + ',' + str(NPSPO2[IndMax[i]])

        for i in range(len(IndMin)):
            trough_values.append(NPSPO2[IndMin[i]])
            trough_values_idx.append(RealIdx[IndMin[i]])
            SPO2_mark_location[RealIdx[IndMin[i]]] = 'trough,' + str(SPO2_origin_loc[RealIdx[IndMin[i]]]) + ',' + str(NPSPO2[IndMin[i]])

        peak_count=len(peak_values)
        trough_count=len(trough_values)
        count_diff=abs(peak_count-trough_count)

        SPO2_mark_location = [x for x in SPO2_mark_location if str(x) != 'nan']

        if NPNPSPO2[0]>0:
            if count_diff ==1:
                peak_values.pop()
                peak_values_idx.pop()
                SPO2_mark_location.pop();
        else:
            if count_diff == 1:
                trough_values.pop(0)
                trough_values_idx.pop(0)
                SPO2_mark_location.pop(0)
            else:
                peak_values.pop()
                peak_values_idx.pop()
                trough_values.pop(0)
                trough_values_idx.pop(0)
                SPO2_mark_location.pop();
                SPO2_mark_location.pop(0);

        amp=[]
        O2_delta=[]
        O2_delta_4=[]

        for i in range(len(peak_values)):
            if abs(peak_values_idx[i]-trough_values_idx[i]) <=Duration_Time:
                amp.append(peak_values[i]-trough_values[i])
                if peak_values[i]-trough_values[i]>=Threshold:
                    O2_delta.append(peak_values[i]-trough_values[i])
                if peak_values[i]-trough_values[i]>=4:
                    O2_delta_4.append(peak_values[i]-trough_values[i])

        self.ODE = len(O2_delta);
        self.ODE4 = len(O2_delta_4);
        self.ODE_new = (self.ODE+self.ODE4)/2

        self.AHI = round(self.ODE/TimeInBed*3600,2)
        self.AHI_new = round(self.ODE_new/TimeInBed*3600,2)

        if self.AHI_new>=30:
            self.osa_level='Severe'
        elif self.AHI_new>=15 and self.AHI_new<30:
            self.osa_level='Moderate'
        elif self.AHI_new>=5 and self.AHI_new<=15:
            self.osa_level='Mild'
        elif self.AHI_new<5:
            self.osa_level='Normal'

        self.Total_Record_time=round(TimeInBed/3600,2)
        self.Record_start=listdatakey[0]
        self.Record_end=listdatakey[-1]
        self.baseline=self.get_mode(SPO2_denoise)
        self.meanSPO2=round(np.mean(SPO2_denoise),2)
        self.LowestSPO2=min(SPO2_denoise)
        self.ratio_under90=round(len(SPO2_under90)/len(SPO2_denoise)*100,2)


import socket
import struct
from collections import defaultdict
from conf.const import MAX_TCP_CONNS, UDP_BROADCAST_ADDR

def ip2int(addr):
    return struct.unpack("!I", socket.inet_aton(addr))[0]

def int2ip(addr):
    return socket.inet_ntoa(struct.pack("!I", addr))

def id2str(conn_id):
    #return int2ip(conn_id >> 16) + ':' + str(conn_id % (1 << 16))
    return int2ip(conn_id)

def str2id(switch):
    #ip, port = switch.split(':')
    #return (ip2int(ip) << 16) + int(port)
    return ip2int(switch)

def id2name(conn_id):
    name = int2ip(conn_id).split('.')[2]
    for i in range(0, 3 - len(name)):
        name = '0' + name
    return 's' + name

def byteify(input):
    '''
    convert unicode from json.loads to utf-8
    '''
    if isinstance(input, dict):
        return {byteify(key): byteify(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

class UdpConn(object):
    '''
    For scl on the switch side, connect to scl on the controller side
    '''
    def __init__(self, dst_host, dst_port):
        # To send msg outside, first checkout the host route
        self.dst_addr = (dst_host, dst_port)

    def open(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setblocking(0)            # non-blocking

    def recv(self, buf_size):
        data = self.sock.recv(buf_size)
        return data

    def send(self, msg):
        self.sock.send(msg, self.dst_addr)

class UdpFloodListener(object):
    def __init__(self, src_intf, src_port, dst_port):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.setblocking(0)            # non-blocking
        if not src_intf:
            self.sock.bind(('', src_port))
        else:
            self.sock.bind((src_intf, src_port))
        self.dst_addr = (UDP_BROADCAST_ADDR, dst_port)

    def recvfrom(self, buf_size):
        data, addr = self.sock.recvfrom(buf_size)
        return data, addr

    def recv(self, buf_size):
        data = self.sock.recv(buf_size)
        return data

    def send(self, msgs):
        if isinstance(msgs, list):
            for msg in msgs:
                self.sock.sendto(msg, self.dst_addr)
        else:
            self.sock.sendto(msgs, self.dst_addr)

class UdpMcastListener(object):
    '''
    For scl on the controller side, listening the multicast group
    '''
    def __init__(self, src_mcast_grp, src_mcast_port, mcast_intf=None,
            dst_mcast_grp=None, dst_mcast_port=None):
        self.sock = None
        self.src_grp = src_mcast_grp
        self.src_port = src_mcast_port
        self.intf = mcast_intf              # which interface to listen at
        self.dst_grp = dst_mcast_grp
        self.dst_port = dst_mcast_port
        if self.intf is None:                    # None means all interfaces
            self.intf = socket.INADDR_ANY
        self.dst_addr = defaultdict(lambda: None)

    def open(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setblocking(0)            # non-blocking
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20)
        # Allow multiple copies of this program on one machine
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # Tell the operating system to add the socket to the multicast group
        # on target interface.
        addrinfo = socket.getaddrinfo(self.src_grp, None)[0]
        group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0])
        mreq = group_bin + socket.inet_aton(self.intf)
        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        self.sock.bind(('',self.src_port))

    def recvfrom(self, buf_size):
        data, addr = self.sock.recvfrom(buf_size) # addr = ('ip', port)
        addr_id = ip2int(addr[0])
        self.dst_addr[addr_id] = addr
        return data, addr_id

    def send_to_id(self, msgs, addr_id):
        if not self.dst_addr[addr_id]:
            ip, port = id2str(addr_id).split(':')
            addr = (ip, int(port))
            self.dst_addr[addr_id] = addr
        if isinstance(msgs, list):
            for msg in msgs:
                self.sock.sendto(msg, self.dst_addr[addr_id])
        else:
            self.sock.sendto(msgs, self.dst_addr[addr_id])

    def send_to_addr(self, msg, addr, port):
        self.sock.sendto(msg, (addr, port))

    def multicast(self, msgs, dst=False):
        # route add -host self.src_grp dev self.intf
        if not dst:
            if isinstance(msgs, list):
                for msg in msgs:
                    self.sock.sendto(msg, (self.src_grp, self.src_port))
            else:
                self.sock.sendto(msgs, (self.src_grp, self.src_port))
        else:
            if isinstance(msgs, list):
                for msg in msgs:
                    self.sock.sendto(msg, (self.dst_grp, self.dst_port))
            else:
                self.sock.sendto(msgs, (self.dst_grp, self.dst_port))

class TcpConn(object):
    '''
    For scl on the switch side, connect to switch.
    Or for scl on the controller side, connect to controller
    '''
    def __init__(self, dst_host, dst_port, sock=None, conn_id=None):
        self.sock = sock
        self.dst_addr = (dst_host, dst_port)
        self.connectted = False
        self.conn_id = conn_id

    def open(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setblocking(0)

    def recv(self, buf_size):
        msg = self.sock.recv(buf_size)
        return msg

    def send(self, msg):
        self.sock.send(msg)

    def isconnectted(self):
        err = self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        # EINPROGRESS ?
        if err is 0:
            self.connectted = True
            return True, err
        else:
            self.connectted = False
            return False, err

    def connect(self):
        if not self.connectted:
            try:
                self.open()
                self.sock.connect(self.dst_addr)
                self.connectted = True
                return True, 0
            except socket.error as serr:
                return False, serr
        else:
            return True, 0

    def close(self):
        if self.connectted:
            self.sock.close()
            self.connectted = False

class TcpConnsMulti2One(object):
    '''
    For scl on the controller side, connect to controller
    multiple sources to one destination
    '''
    def __init__(self, dst_host, dst_port):
        self.sock2conn = {}                     # k: v is sock: conn
        self.id2conn = {}                       # k: v is conn_id: conn
        self.dst_host = dst_host
        self.dst_port = dst_port

    def open(self, conn_id):
        conn = TcpConn(self.dst_host, self.dst_port, None, conn_id)
        ret, err = conn.connect()
        self.sock2conn[conn.sock] = conn
        self.id2conn[conn_id] = conn
        return ret, err

    def close(self, conn_id):
        self.id2conn[conn_id].close()
        del self.sock2conn[self.id2conn[conn_id].sock]
        del self.id2conn[conn_id]

    def recv(self):
        msg = self.sock.recv(1024)
        return msg

    def send(self, msg):
        self.sock.send(msg)

class TcpConnsOne2Multi(object):
    def __init__(self, dst_intfs, dst_port):
        self.intf2conn = defaultdict(lambda: None)  # k: v is intf: conn
        self.sock2conn = {}                         # k: v is sock: conn
        self.dst_intfs = dst_intfs
        self.dst_port = dst_port

    def open(self, intf):
        conn = TcpConn(intf, self.dst_port, None, intf)
        ret, err = conn.connect()
        self.intf2conn[intf] = conn
        self.sock2conn[conn.sock] = conn
        return ret, err

    def close(self, intf):
        self.intf2conn[intf].close()
        del self.sock2conn[self.intf2conn[intf].sock]
        del self.intf2conn[intf]

class TcpListener(object):
    '''
    For scl on the switch side, listen connections from switch
    '''
    def __init__(self, src_host, src_port):
        self.sock2conn = {}                     # k: v is sock: conn
        self.id2conn = {}                       # k: v is conn_id: conn
        self.sock = None
        self.host = src_host
        self.port = src_port
        self.open()

    def open(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setblocking(0)            # non-blocking
        self.sock.bind((self.host, self.port))
        self.sock.listen(MAX_TCP_CONNS)     # max open connections

    def accept(self):
        sock, addr = self.sock.accept()
        sock.setblocking(0)
        conn_id = ip2int(addr[0])
        conn = TcpConn(addr[0], addr[1], sock, conn_id)
        self.sock2conn[sock] = conn
        self.id2conn[conn_id] = conn
        return sock, conn_id

    def close(self, conn_id):
        self.id2conn[conn_id].close()
        del self.sock2conn[self.id2conn[conn_id].sock]
        del self.id2conn[conn_id]


"""Handles communication on the backend side between frontend and backend

Please keep this file Python 2.7 compatible.
See https://tox.readthedocs.io/en/rewrite/development.html#code-style-guide
"""
from __future__ import print_function

import importlib
import json
import os
import sys
import traceback

class MissingCommand(TypeError):
    """Missing command"""

class BackendProxy:
    def __init__(self, backend_module, backend_obj):
        self.backend_module = backend_module
        self.backend_object = backend_obj
        backend = importlib.import_module(self.backend_module)
        if self.backend_object:
            backend = getattr(backend, self.backend_object)
        self.backend = backend

    def __call__(self, name, *args, **kwargs):
        on_object = self if name.startswith("_") else self.backend
        if not hasattr(on_object, name):
            raise MissingCommand("{!r} has no attribute {!r}".format(on_object, name))
        return getattr(on_object, name)(*args, **kwargs)

    def __str__(self):
        return "{}(backend={})".format(self.__class__.__name__, self.backend)

    def _exit(self):
        return 0

    def _optional_hooks(self):
        return {
            k: hasattr(self.backend, k)
            for k in (
                "get_requires_for_build_sdist",
                "prepare_metadata_for_build_wheel",
                "get_requires_for_build_wheel",
                "build_editable",
                "get_requires_for_build_editable",
                "prepare_metadata_for_build_editable",
            )
        }

def flush():
    sys.stderr.flush()
    sys.stdout.flush()

def run(argv):
    reuse_process = argv[0].lower() == "true"

    try:
        backend_proxy = BackendProxy(argv[1], None if len(argv) == 2 else argv[2])
    except BaseException:
        print("failed to start backend", file=sys.stderr)
        raise
    else:
        print("started backend {}".format(backend_proxy), file=sys.stdout)
    finally:
        flush()  # pragma: no branch
    while True:
        content = read_line()
        if not content:
            continue
        flush()  # flush any output generated before
        try:
            if sys.version_info[0] == 2:  # pragma: no branch # python 2 does not support loading from bytearray
                content = content.decode()  # pragma: no cover
            parsed_message = json.loads(content)
            result_file = parsed_message["result"]
        except Exception:
            # ignore messages that are not valid JSON and contain a valid result path
            print("Backend: incorrect request to backend: {}".format(content), file=sys.stderr)
            flush()
        else:
            result = {}
            try:
                cmd = parsed_message["cmd"]
                print("Backend: run command {} with args {}".format(cmd, parsed_message["kwargs"]))
                outcome = backend_proxy(parsed_message["cmd"], **parsed_message["kwargs"])
                result["return"] = outcome
                if cmd == "_exit":
                    break
            except BaseException as exception:
                result["code"] = exception.code if isinstance(exception, SystemExit) else 1
                result["exc_type"] = exception.__class__.__name__
                result["exc_msg"] = str(exception)
                if not isinstance(exception, MissingCommand):  # for missing command do not print stack
                    traceback.print_exc()
            finally:
                try:
                    with open(result_file, "w") as file_handler:
                        json.dump(result, file_handler)
                except Exception:
                    traceback.print_exc()
                finally:
                    # used as done marker by frontend
                    print("Backend: Wrote response {} to {}".format(result, result_file))
                    flush()  # pragma: no branch
        if reuse_process is False:  # pragma: no branch # no test for reuse process in root test env
            break
    return 0

def read_line(fd=0):
    # for some reason input() seems to break (hangs forever) so instead we read byte by byte the unbuffered stream
    content = bytearray()
    while True:
        char = os.read(fd, 1)
        if not char:
            if not content:
                raise EOFError("EOF without reading anything")  # we didn't get a line at all, let the caller know
            break  # pragma: no cover
        if char == b"\n":
            break
        if char != b"\r":
            content += char
    return content

if __name__ == "__main__":
    sys.exit(run(sys.argv[1:]))


def multiply_lnks(lst_of_lnks):
    """
    >>> a = Link(2, Link(3, Link(5)))
    >>> b = Link(6, Link(4, Link(2)))
    >>> c = Link(4, Link(1, Link(0, Link(2))))
    >>> p = multiply_lnks([a, b, c])
    >>> p.first
    48
    >>> p.rest.first
    12
    >>> p.rest.rest.rest is Link.empty
    True
    """
    if Link.empty in lst_of_lnks:
        return Link.empty
    else:
        product = 1
        for i in range(len(lst_of_lnks)):
            product *= lst_of_lnks[i].first
            lst_of_lnks[i] = lst_of_lnks[i].rest
        return Link(product,multiply_lnks(lst_of_lnks))

def remove_duplicates(lnk):
    """
    >>> lnk = Link(1, Link(1, Link(1, Link(1, Link(5)))))
    >>> remove_duplicates(lnk)
    >>> lnk
    Link(1, Link(5))
    """
    #iterative
    """
    while lnk is not Link.empty and lnk.rest is not Link.empty :
        if lnk.first == lnk.rest.first:
            lnk.rest = lnk.rest.rest
        else:
           lnk = lnk.rest
    """
    #recursive
    if lnk is Link.empty or lnk.rest is Link.empty:
        return
    else:
        if lnk.first == lnk.rest.first:
            lnk.rest = lnk.rest.rest
            remove_duplicates(lnk)
        else:
            remove_duplicates(lnk.rest)

def is_palindrome(seq):
    """ Returns True if the sequence is a palindrome. A palindrome is a sequence
    that reads the same forwards as backwards
    >>> is_palindrome(Link("l", Link("i", Link("n", Link("k")))))
    False
    >>> is_palindrome(["l", "i", "n", "k"])
    False
    >>> is_palindrome("link")
    False
    >>> is_palindrome(Link.empty)
    True
    >>> is_palindrome([])
    True
    >>> is_palindrome("")
    True
    >>> is_palindrome(Link("a", Link("v", Link("a"))))
    True
    >>> is_palindrome(["a", "v", "a"])
    True
    >>> is_palindrome("ava")
    True
    """
    lst=[]
    l = len(seq)
    for i in range(l):
        if seq[i] == seq[l-1-i]:
            lst += [True]
        else:
            lst +=[False]
    if all(lst):
        return True
    else:
        return False

def average(t):
    """
    Returns the average value of all the nodes in t.
    >>> t0 = Tree(0, [Tree(1), Tree(2, [Tree(3)])])
    >>> average(t0)
    1.5
    >>> t1 = Tree(8, [t0, Tree(4)])
    >>> average(t1)
    3.0
    """
    def sum_helper(t):
        if t.is_leaf():
           return t.label
        else:
            return t.label + sum([sum_helper(b) for b in t.branches])
    def count_helper(t):
        count = 1
        for b in t.branches:
            count +=count_helper(b)
        return count
    return sum_helper(t)/count_helper(t)

def long_paths(tree, n):
    """Return a list of all paths in tree with length at least n.
    >>> t = Tree(3, [Tree(4), Tree(4), Tree(5)])
    >>> left = Tree(1, [Tree(2), t])
    >>> mid = Tree(6, [Tree(7, [Tree(8)]), Tree(9)])
    >>> right = Tree(11, [Tree(12, [Tree(13, [Tree(14)])])])
    >>> whole = Tree(0, [left, Tree(13), mid, right])
    >>> for path in long_paths(whole, 2):
    ...  print(path)
    ...
    <0 1 2>
    <0 1 3 4>
    <0 1 3 4>
    <0 1 3 5>
    <0 6 7 8>
    <0 6 9>
    <0 11 12 13 14>
    >>> for path in long_paths(whole, 3):
    ...  print(path)
    ...
    <0 1 3 4>
    <0 1 3 4>
    <0 1 3 5>
    <0 6 7 8>
    <0 11 12 13 14>
    >>> long_paths(whole, 4)
    [Link(0, Link(11, Link(12, Link(13, Link(14)))))]
    """
    lst = []
    if tree.is_leaf() and n<=0:
        return lst.append(Link(tree.label))
    else:
        for b in tree.branches:
            for e in long_paths(b,n-1):
                lst.append(Link(tree.label,e))
    return lst

#link Tree
class Link:
    """A linked list.

    >>> s = Link(1)
    >>> s.first
    1
    >>> s.rest is Link.empty
    True
    >>> s = Link(2, Link(3, Link(4)))
    >>> s.first = 5
    >>> s.rest.first = 6
    >>> s.rest.rest = Link.empty
    >>> s                                    # Displays the contents of repr(s)
    Link(5, Link(6))
    >>> s.rest = Link(7, Link(Link(8, Link(9))))
    >>> s
    Link(5, Link(7, Link(Link(8, Link(9)))))
    >>> print(s)                             # Prints str(s)
    <5 7 <8 9>>
    """
    empty = ()

    def __init__(self, first, rest=empty):
        assert rest is Link.empty or isinstance(rest, Link)
        self.first = first
        self.rest = rest

    def __repr__(self):
        if self.rest is not Link.empty:
            rest_repr = ', ' + repr(self.rest)
        else:
            rest_repr = ''
        return 'Link(' + repr(self.first) + rest_repr + ')'

    def __str__(self):
        string = '<'
        while self.rest is not Link.empty:
            string += str(self.first) + ' '
            self = self.rest
        return string + str(self.first) + '>'

    def __len__(self):
        # if self is Link.empty:
        # return 0
        # else:
        return 1 + len(self.rest)

    def __getitem__(self, i):
        if i == 0:
            return self.first
        else:
            return self.rest[i - 1]

class Tree:
    """
    >>> t = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])
    >>> t.label
    3
    >>> t.branches[0].label
    2
    >>> t.branches[1].is_leaf()
    True
    """
    def __init__(self, label, branches=[]):
        for b in branches:
            assert isinstance(b, Tree)
        self.label = label
        self.branches = list(branches)

    def is_leaf(self):
        return not self.branches

    def map(self, fn):
        """
        Apply a function `fn` to each node in the tree and mutate the tree.

        >>> t1 = Tree(1)
        >>> t1.map(lambda x: x + 2)
        >>> t1.map(lambda x : x * 4)
        >>> t1.label
        12
        >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])
        >>> t2.map(lambda x: x * x)
        >>> t2
        Tree(9, [Tree(4, [Tree(25)]), Tree(16)])
        """
        self.label = fn(self.label)
        for b in self.branches:
            b.map(fn)

    def __contains__(self, e):
        """
        Determine whether an element exists in the tree.

        >>> t1 = Tree(1)
        >>> 1 in t1
        True
        >>> 8 in t1
        False
        >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])
        >>> 6 in t2
        False
        >>> 5 in t2
        True
        """
        if self.label == e:
            return True
        for b in self.branches:
            if e in b:
                return True
        return False

    def __repr__(self):
        if self.branches:
            branch_str = ', ' + repr(self.branches)
        else:
            branch_str = ''
        return 'Tree({0}{1})'.format(self.label, branch_str)

    def __str__(self):
        def print_tree(t, indent=0):
            tree_str = '  ' * indent + str(t.label) + "\n"
            for b in t.branches:
                tree_str += print_tree(b, indent + 1)
            return tree_str
        return print_tree(self).rstrip()


from __future__ import annotations

from collections.abc import Callable
from dataclasses import dataclass
import logging
from typing import Final

from homeassistant.components.binary_sensor import (
    BinarySensorDeviceClass,
    BinarySensorEntity,
    BinarySensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN
from .coordinator import MapShareCoordinator
from .entity import MapShareBaseEntity

_LOGGER = logging.getLogger(__name__)

@dataclass
class MapShareBinarySensorEntityDescription(BinarySensorEntityDescription):
    """A class that describes custom binary sensor entities."""

    is_on: Callable[[dict[str, str]], bool] | None = None
    on_icon: str | None = None
    off_icon: str | None = None

SENSOR_DESCRIPTIONS: Final[tuple[MapShareBinarySensorEntityDescription, ...]] = (
    MapShareBinarySensorEntityDescription(
        key="in_emergency",
        name="In Emergency",
        is_on=lambda raw_values: raw_values.get('In Emergency', False) == "True",
        on_icon="mdi:alert-circle",
        off_icon="mdi:alert-circle",
        device_class=BinarySensorDeviceClass.PROBLEM,
    ),
    MapShareBinarySensorEntityDescription(
        key="valid_gps_fix",
        name="Valid GPS Fix",
        is_on=lambda raw_values: raw_values.get('Valid GPS Fix', False) == "True",
        on_icon="mdi:crosshairs-gps",
        off_icon="mdi:crosshairs",
    ),
)

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up binary_sensor platform."""
    coordinator: MapShareCoordinator = hass.data[DOMAIN][config_entry.entry_id]
    entities: list[MapShareConnectBinarySensor] = []
    for description in SENSOR_DESCRIPTIONS:
        entities.append(
            MapShareConnectBinarySensor(coordinator, description)
        )
    async_add_entities(entities)
    return True

class MapShareConnectBinarySensor(BinarySensorEntity, MapShareBaseEntity):

    def __init__(
        self,
        coordinator: MapShareCoordinator,
        description: MapShareBinarySensorEntityDescription,
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description: MapShareBinarySensorEntityDescription = description
        self._attr_unique_id = f"{coordinator.map_link_name}-{description.key}"
        self._attr_name = f"{description.name}"

    @property
    def is_on(self) -> bool | None:
        """Return true if the binary sensor is on."""
        if self.entity_description.is_on is not None:
            return self.entity_description.is_on(self.coordinator.raw_values)
        return None

    @property
    def icon(self):
        """Return the icon to use in the frontend, if any."""
        if (
            self.entity_description.on_icon == self.entity_description.off_icon
        ) is None:
            return BinarySensorEntity.icon
        return (
            self.entity_description.on_icon
            if self.is_on
            else self.entity_description.off_icon
        )


# def sum_of_digits(number):
# 	sum_ = 0
# 	while (number != 0):
# 		sum_ += number%10
# 		number = number//10
# 	return sum_
# def sum_of_digits_recursion(number):
# 	if number == 0:
# 		return 0
# 	# sum_ +=
# 	return number%10 + sum_of_digits_recursion(number//10)
# def main():
# 	print(sum_of_digits_recursion(46))
# if __name__ == '__main__':
# 	main()

def reverse(string,index):
	if index == 0:
		return ""

	return string[index-1]+reverse(string,index-1)
def main():
    # YOUR CODE GOES HERE
    # Please take input and print output to standard input/output (stdin/stdout)
    # E.g. 'input()/raw_input()' for input & 'print' for output
    string = input()
    output = reverse(string,len(string))
    print(output)
    return output

if __name__ == '__main__':
    main()
#


class test:
    k = 0

    def __init__(self, x, y):
        self.i = x
        self.j = y
        self.__class__.k += 1

    def sqr(self):
        self.i *= self.i
        self.j *= self.j

    def show(self):
        print(self.i, self.j, self.__class__.k)

t1=test(3,4)
t2=test(5,6)

t1.sqr()
t2.sqr()
t1.show()
t2.show()

OOP Problems/Methods in class 1 instant method.py


import numpy as np

def meta_accuracy(correct, decisions, confidence, max_confidence=4):
    """
    Compute metacognitive accuracy over a set of trials.
    :params correct: correct decision
    :params decisions: decisions of the subject
    :params confidence: confidence of the subject
    """
    correctness = np.array(correct) == np.array(decisions)
    score = 0
    for trial in range(len(correct)):
        if correctness[trial]:
            score += confidence[trial] / max_confidence
        else:
            score += 1 - confidence[trial] / max_confidence
    return score / len(correct)

def accuracy(correct, decisions):
    """
    Compute accuracy over a set of trials.
    :params correct: correct decision
    :params decisions: decisions of the subject
    """
    correctness = np.array(correct) == np.array(decisions)
    return sum(correctness) / len(correctness) * 100


import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/src")

import networkx as nx
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LogisticRegression
import scipy.sparse as sp

from models import Snore
from utils import read_graph_from_json
from link_prediction import methods, create_splits

def create_embedding_matrix(emb, pos_edges, neg_edges):
    embeddings = []
    for i, j, k in (pos_edges + neg_edges):
        embeddings.append(sp.csr_matrix.multiply(emb[i], emb[j]))
    return sp.vstack(embeddings), np.array([1 for i in range(len(pos_edges))] + [0 for i in range(len(neg_edges))])

if __name__ == '__main__':
    num_features = 5

    graph, node_ids, edge_ids = read_graph_from_json("data/go.json")
    splits = create_splits(graph)
    adj = nx.to_scipy_sparse_matrix(nx.Graph(graph))

    model = Snore()
    model.train(adj, [], [], [], [], None, (0, 0))
    embedding = model.embedding
    feature_names = model.model.selected_features

    train_mat, train_labels = create_embedding_matrix(embedding, splits[0][1] + splits[0][3] + splits[0][5],
                                                      splits[0][2] + splits[0][4] + splits[0][6])

    edge_classifier = LogisticRegression(random_state=0, solver='liblinear')
    edge_classifier.fit(train_mat, train_labels)

    predProbs = edge_classifier.predict_proba(train_mat)
    X_design = sp.hstack([np.ones((train_mat.shape[0], 1)), train_mat])
    V = np.product(predProbs, axis=1)

    covLogit = np.linalg.pinv(sp.csr_matrix.multiply(X_design.T, V).dot(X_design).toarray())
    se = np.sqrt(np.diag(covLogit))[1:]
    coefs = np.abs(edge_classifier.coef_ / se)[0]
    sorted_coefs = np.argsort(-coefs)

    relevant_parameters = sorted_coefs[:num_features]
    values = coefs[relevant_parameters]
    features = [node_ids[feature_names[i]].split("/")[-1] for i in relevant_parameters]

    print("Global explanation")
    for i, j in zip(features, values):
        print("{}, value: {}".format(i, j))

    sns.barplot(x="Feature", y="Importance", data=pd.DataFrame(data={"Feature": features, "Importance": values}),
                order=features).set_title("Global explanation")
    plt.show()


import heapq

INF = 1e9

def Prim(case):
    input()
    V = int(input())
    Adj = {}
    for i in range(V):
        city1, city2, cost = map(str, input().split())
        cost = int(cost)
        if city1 not in Adj:
            Adj[city1] = {}
        if city2 not in Adj:
            Adj[city2] = {}
        if city2 not in Adj[city1]:
            Adj[city1][city2] = INF
        Adj[city1][city2] = min(Adj[city1][city2], cost)
        if city1 not in Adj[city2]:
            Adj[city2][city1] = INF
        Adj[city2][city1] = min(Adj[city2][city1], cost)
    n_components = 0
    visited = {}
    for v in Adj.keys():
        if v not in visited:
            n_components += 1
            frontier = [v]
            visited[v] = True
            while frontier:
                next = []
                for vertex in frontier:
                    for u in Adj[vertex]:
                        if u not in visited:
                            visited[u] = True
                            next.append(u)
                frontier = next
        if n_components > 1:
            print("Case {0}: Impossible".format(case))
            return

    distances = {}
    for key in Adj.keys():
        distances[key] = INF
    pq = [(0, city2)]
    visited = {}
    while pq:
        w,v = heapq.heappop(pq)
        if v in visited:continue
        visited[v] = True
        for u in Adj[v]:
            if u not in visited and distances[u]>Adj[v][u]:
                distances[u] = Adj[v][u]
                heapq.heappush(pq,(distances[u],u))
    total = 0
    for k in distances:
        if distances[k]!=INF:
            total+=distances[k]
    print("Case {0}: {1}".format(case,total))
    return

T = int(input())
for case in range(1, T + 1):
    Prim(case)


from tkinter import *
from selenium import *
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.keys import Keys
import time
from plyer import notification

root = Tk()
root.title("Animedoro")
root.config(bg='green2')
root.geometry('300x120')
root.resizable(False,False)

PATH = "C:\Program Files (x86)\chromedriver.exe"

driver = webdriver.Chrome(PATH)

def start():
    website = websiteval.get()
    rawstudytime = int(studytimeval.get())
    timecurrent = round(time.time() * 1000)
    studytime = rawstudytime*3600
    studytitle = 'Study time starts'
    studymessage = 'Your Study time is going to start pay attention and use your brain wisely'
    animetitle = 'Anime time starts'
    animemessage = 'Anime time starts enjoy'
    while True:
        notification.notify(title=studytitle,message=studymessage,timeout=10,toast=False)
        study = int(studytime)
        time.sleep(study)
        notification.notify(title=animetitle, message=animemessage,timeout=10,toast=False)
        anime = int(study + 1800)
        time.sleep(anime)
        animeopen = driver.get(website)

websiteval = StringVar()
studytimeval = StringVar()

studytimelabel = Label(root,text='study time',font=('helvetica',10,'bold'),bg='green2',fg='black')
studytimelabel.place(x=8,y=8)

studytimeentry = Entry(root,font=('helvetica',10,'bold'),relief=FLAT, textvariable=studytimeval)
studytimeentry.place(x=112,y=8)

websitelabel = Label(root,text='website',font=('helvetica',10,'bold'),bg='green2',fg='black')
websitelabel.place(x=8,y=40)

websiteentry = Entry(root,font=('helvetica',10,'bold'),relief=FLAT,textvariable=websiteval)
websiteentry.place(x=112,y=40)

startinsidebtn = Button(root,text='Start',font=('helvetica',10,'bold'),bg='black',fg='green2',activebackground='green2',
activeforeground='black',width=20,command=start)
startinsidebtn.place(x=70,y=70)

root.mainloop()


import sys
for n in sys.stdin:
    start = list(map(int, input().split()))
    finish = list(map(int, input().split()))
    overtakes = 0
    for position in range(int(n)):
        if finish[position] != start[position]:
            before = start.index(finish[position])
            start.insert(position, start.pop(before))
            overtakes += before - position
    print(overtakes)


from scorers.scorer import Scorer
import numpy as np

class Task_phrases_Scorer(Scorer):
    def __init__(self):
        super(Scorer,self).__init__()

    def get_final_score(self, ans, histories, tasks):
        '''
        Input:
        - ans (str): The answer to be scored.
        - formats (list of dictionaries): Criteria for scoring the answer.

        Output:
        - final_score (float): The final score for the answer regarding *Task-prescribed Query*

        Function:
        Calculate the final score for the answer based on specified criteria.
        '''
        task_score = np.nan
        if not isinstance(ans, str):
            task_score = 0
        else:
            task_score = self.keywords_score(ans, tasks)

        return task_score

    def keywords_score(self, ans, criteria):
        keywords = ''
        for criterion in criteria:
            if criterion['criterion'] in ["keywords"]:
                keywords = criterion['limit']
                break
            elif criterion['criterion'] == 'NULL':
                return np.nan

        assert (keywords != '' and not isinstance(keywords, float) and  len(keywords) != 0)

        cnt = 0
        for keyword in keywords:
            if keyword in ans:
                cnt += 1

        return cnt / len(keywords)


import numpy as np
import nfl_data_py as NFL
import pandas as pd
import warnings
from QB import QB

def showLevel1(obj1, obj2):
    print(obj1.name,end=' vs ')
    print(obj2.name)
    print(obj1.team,end=' Team ')
    print(obj2.team)

    choice = int(input('Who would you rather have everything else equal? (input 1 or 2)\n'))
    print('\n')
    return choice

warnings.filterwarnings("ignore")

year = [2022]

# get seasonal data and rosters
data = NFL.import_seasonal_data(year)
rosters = NFL.import_rosters(year)

# ids of players who achieved a stat in 2021 season
playerID = list(data.player_id)

rosters = rosters[['season','team','position','status',
'player_name','height','weight','college','player_id','years_exp','headshot_url']]

################## groupby position ##################

## QB ##
qbs = rosters.groupby("position").get_group('QB') # get QBs from roster
qbsName = qbs[['player_name']]  # QB names
qbID = qbs.player_id # QB player ID from rosters
qbsData = data[data["player_id"].isin(qbID)] # get qb stats from data
qbsData = qbsData[qbsData.passing_air_yards > 2000] # only qbs with more than 2000 passing yards
qbID = qbsData.player_id # player ids for qbs that meet the above constraint
qbs = qbs[qbs["player_id"].isin(qbID)] # get qbs from roster

listQB  = []

for ind in qbs.index:

    season = rosters['season'][ind]
    team = rosters['team'][ind]
    name = rosters['player_name'][ind]
    position = rosters['position'][ind]
    status =  rosters['status'][ind]
    player_name = rosters['player_name'][ind]
    height = rosters['height'][ind]
    weight = rosters['weight'][ind]
    college = rosters['college'][ind]
    player_id = rosters['player_id'][ind]
    years_exp = rosters['years_exp'][ind]
    headshot_url = rosters['headshot_url'][ind]
    qbHold = QB(season,team,name,position,status,player_name,height,weight,college, player_id,years_exp, headshot_url,0 )
    listQB.append(qbHold)

numQB = len(listQB)

################## Ranking  V0 ################

## Success! but really slow and tedious. Brute force method
## amount of inputs by user needed are nCr = 528 (working on it)

testQB = listQB
for i in range(len(testQB)):
    holdQB1 = testQB[i]
    for j in range(i+1,len(testQB)):
        holdQB2 = testQB[j]
        choice = showLevel1(holdQB1, holdQB2)
        if choice == 1:
            # holdQB1 must be ranked higher than holdQB2
            testQB[i].qbRankWins = testQB[i].qbRankWins + 1
            #print(holdQB1.name, testQB[i].qbRankWins, holdQB2.name, testQB[j].qbRankWins)

        else:
            testQB[j].qbRankWins = testQB[j].qbRankWins + 1

            #print(holdQB1.name, testQB[i].qbRankWins, holdQB2.name, testQB[j].qbRankWins)

testQB.sort(key = lambda x: x.qbRankWins,reverse=True)
print('Rankings:')
for j in range(len(testQB)):
    print(j+1, testQB[j].name)