import numpy as np
import cv2
import dlib
import time
import sys
from imutils import face_utils
import imutils
import random

def run():
    RANDOM_TIMES = 20
    TIME_INTERVAL = 0.1

    cap = cv2.VideoCapture(0)
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
    images = [["mondrian_left.png", "mondrian_right.png"], [
        "garfield_left.png", "garfield_right.png"],["brownleft.png", "brownright.png"],
        ["yellowleft.png", "yellowright.png"], ["pinkleft.png", "pinkright.png"]]

    start = time.clock()

    # Choose random image
    ears = random.choice(images)
    times = 0

    while True:
        if len(sys.argv)>1:
            image = cv2.imread(sys.argv[1])
        else:
            ret, image = cap.read()
        image = imutils.resize(image, width=500)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        rects = detector(gray,1)

        # Choose random image
        if (time.clock() - start > TIME_INTERVAL) and times < RANDOM_TIMES:
            start = time.clock()
            times += 1
            ears = random.choice(images)
        for (i, rect) in enumerate(rects):
            # determine the facial landmarks for the face region, then
            # convert the facial landmark (x, y)-coordinates to a NumPy
            # array
            shape = predictor(gray, rect)
            shape = face_utils.shape_to_np(shape)

            #left ear
            left_ear_image = cv2.imread(ears[0], -1)
            orig_mask_l = left_ear_image[:,:,3]
            orig_mask_inv_l = cv2.bitwise_not(orig_mask_l)
            left_ear_image = left_ear_image[:,:,0:3]
            original_left_height, original_left_width = left_ear_image.shape[:2]
            placed = place_ear(image, original_left_width, original_left_height,
            shape, left_ear_image, orig_mask_l, orig_mask_inv_l, True)

            #right ear
            if placed :
                right_ear_image = cv2.imread(ears[1], -1)
                orig_mask_r = right_ear_image[:,:,3]
                orig_mask_inv_r = cv2.bitwise_not(orig_mask_r)
                right_ear_image = right_ear_image[:,:,0:3]
                original_right_height, original_right_width = right_ear_image.shape[:2]
                place_ear(image, original_right_width, original_right_height, shape, right_ear_image, orig_mask_r, orig_mask_inv_r, False)
        cv2.imshow("Output", image)
        k = cv2.waitKey(30) & 0xff
        if k == 27: # press 'ESC' to quit
            break
    cap.release()
    cv2.destroyAllWindows()

def place_ear(frame, ear_width, ear_height, shape, image, orig_mask, orig_mask_inv, left):
    if left:
        width = int(1.3*(np.linalg.norm(shape[0] - shape[19])))
        height = int(width * ear_height / ear_width)
        x1 = int(shape[0,0] - (width/2))
        x2 = int(x1 + width)
        y1 = int(shape[0,1] -(height/2)) -70
        y2 = int(y1 + height)
    else:
        width = int(1.3*(np.linalg.norm(shape[24] - shape[16])))
        height = int(width * ear_height / ear_width)
        x1 = int(shape[16,0] - (width/2))
        x2 = int(x1 + width)
        y1 = int(shape[16,1] -(height/2)) -70
        y2 = int(y1 + height)

    h, w = frame.shape[:2]

    if not (x1 < 0 or y1 <0 or x2>w or y2>h):
        earOverlayWidth = x2 - x1
        earOverlayHeight = y2 - y1

        earOverlay = cv2.resize(image, (earOverlayWidth,earOverlayHeight), interpolation = cv2.INTER_AREA)
        mask = cv2.resize(orig_mask, (earOverlayWidth,earOverlayHeight), interpolation = cv2.INTER_AREA)
        mask_inv = cv2.resize(orig_mask_inv, (earOverlayWidth,earOverlayHeight), interpolation = cv2.INTER_AREA)

        roi = frame[y1:y2, x1:x2]
        roi_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
        roi_fg = cv2.bitwise_and(earOverlay,earOverlay,mask = mask)
        dst = cv2.add(roi_bg,roi_fg)
        frame[y1:y2, x1:x2] = dst
        return True

    return False
run()


from queues import stack
A = stack()
B = stack()
C = stack()

n = 6

def move(a, b):
    if a.is_empty() and not b.is_empty():
        a.push_right(b.pop_right())
    elif not a.is_empty() and b.is_empty():
        b.push_right(a.pop_right())
    elif a.peek_right() > b.peek_right():
        a.push_right(b.pop_right())
    else:
        b.push_right(a.pop_right())

for i in range(n, 0, -1):
    A.push_right(i)

start, dest, aux = A, C, B

while not dest.is_empty():
    print(dest.pop_right())

total_num_of_moves = int(pow(2, n)-1)

for i in range(1, total_num_of_moves+1):
    if i%3==1:
        move(start, dest)
    elif i%3==2:
        move(start, aux)
    elif i%3==0:
        move(aux, dest)

if n % 2 == 0:
    temp = dest
    dest = aux
    aux = temp

while not dest.is_empty():
    print(dest.pop_right())


# https://programmers.co.kr/learn/courses/30/lessons/49191
# 15:32-16:10
'''
문제 예시 입력
각 번호에 해당하는 학생들의 대소 관계가 다음과 같이 주어짐

1 < 5
3 < 4
4 < 2
4 < 6
5 < 2
5 < 4

1 < 5 < 4 < 2
   3    |  6

# 위에서 4번 학생은 순위를 정확히 알 수 있으나 나머지는 알 수 없음
학생 성적을 비교한 결과가 주어질 때 성적 순위를 정확히 알 수 있는 학생은 몇 명인가?

# 입력 조건
- 학생 수 2 <= N <= 500
- 성적 비교 횟수 2 <= M <= 10,000

# 출력
성적 순위를 정확히 알 수 있는 학생의 수

# 접근
- N 수가 적다
- 모든 노드에 대해서 떨어진 거리가 필요
-> Floyd-worshall
# 행렬을 구한 뒤, 행과 열 모두에서 자기 자신을 제외한 모든 선수에 대해
# 적어도 한 번씩은 대전을 치뤘으면 순위 결정 가능

'''
string = '''6 6
1 5
3 4
4 2
4 6
5 2
5 4'''

# string = '''5 5
# 4 3
# 4 2
# 3 2
# 1 2
# 2 5'''

def testcase(string):
    string = string.split("\n")
    for i in string:
        yield i

G = testcase(string)

def input():
    return next(G)

import pprint

INF = int(1e9)
n, m = map(int, input().split())
graph = [[INF] * (n + 1) for _ in range(n + 1)]

# 자기 자신에 대한 거리는 0
for i in range(1, n + 1):
    for j in range(1, n + 1):
        if i == j:
            graph[i][j] = 0

for i in range(m):
    a, b = map(int, input().split())
    # a 학생의 성적이 b 학생보다 낮다
    graph[a][b] = 1

for k in range(1, n + 1):
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])

graph2 = [[0] * n for _ in range(n)]

for i in range(1, n + 1):
    for j in range(1, n + 1):
        if graph[i][j] != INF:
            graph2[i-1][j-1] = graph[i][j]
        else:
            graph2[i-1][j-1] = 0

count = 0
for i, col in enumerate(zip(*graph2)):
    is_rankable = True
    for j, (r, c) in enumerate(zip(graph2[i], col)):
        if r == 0 and c == 0 and i != j:
            is_rankable = False
            break
    if is_rankable:
        count += 1

print(count)

# # My Solution(Programmers)
INF = int(1e9)
def solution(n, results):
    graph = [[INF] * (n + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(1, n + 1):
            if i == j:
                graph[i][j] = 0

    # 자기 자신에 대한 거리는 0
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            if i == j:
                graph[i][j] = 0

    for i in results:
        a, b = i
        # a 학생의 성적이 b 학생보다 낮다
        graph[a][b] = 1

    for k in range(1, n + 1):
        for i in range(1, n + 1):
            for j in range(1, n + 1):
                graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])

    graph2 = [[0] * n for _ in range(n)]

    for i in range(1, n + 1):
        for j in range(1, n + 1):
            if graph[i][j] != INF:
                graph2[i-1][j-1] = graph[i][j]
            else:
                graph2[i-1][j-1] = 0

    answer = 0
    for i, col in enumerate(zip(*graph2)):
        is_rankable = True
        for j, (r, c) in enumerate(zip(graph2[i], col)):
            if r == 0 and c == 0 and i != j:
                is_rankable = False
                break
        if is_rankable:
            answer += 1

    return answer

n = 5
results = [[4, 3], [4, 2], [3, 2], [1, 2], [2, 5]]

n = 1
results = []
print(solution(n, results))

# defaultdict와 set을 이용한 풀이 : O(N^2)
from collections import defaultdict
def solutiont(n, results):
    answer = 0
    win, lose = defaultdict(set), defaultdict(set)
    # 대전 결과 반영
    for result in results:
        lose[result[1]].add(result[0])
        win[result[0]].add(result[1])
    # 대전 결과에 딸린 상대적 정보 반영
    # (a가 b에 승리, b가 c에 승리 -> a는 c에 승리)
    for i in range(1, n + 1):
        # i한테 이긴 선수는 i가 이긴 다른 선수들에게 모두 이긴다
        for winner in lose[i]:
            win[winner].update[win[i]]
        # i한테 진 선수들은 i가 진 다른 선수들에게 모두 진다
        for loser in win[i]:
            lose[loser].update[lose[i]]

    # 이긴 횟수와 진 횟수를 모두 합한 길이가
    # n - 1(자기 자신을 제외한 선수의 수)이 될 때
    # 순위 결정가능
    for i in range(1, n + 1):
        if len(win[i]) + len(lose[i]) == n - 1:
            answer += 1
    return answer

# Solution
INF = int(1e9)

# 노드의 개수, 간선의 개수 입력 받기
n, m = map(int, input().split())
# 2차원 리스트(그래프 표현)를 만들고, 모든 값을 무한으로 초기화
graph = [[INF] * (n + 1) for _ in range(n + 1)]

# 자기 자신에서 자기 자신 비용은 1로 초기화
for a in range(1, n + 1):
    for b in range(1, n + 1):
        if a == b:
            graph[a][b] = 1 # 0이어도 결과에 무관함

# 각 간선 정보를 입력받아, 그 값으로 초기화
for _ in range(m):
    # A에서 B로 가는 비용을 1로 설정
    a, b = map(int, input().split())
    graph[a][b] = 1

# 전화식에 따라 플로이드 워셜 알고리즘 수행
for k in range(1, n + 1):
    for a in range(1, n + 1):
        for b in range(1, n + 1):
            graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b])

result = 0
# 각 학생을 번호에 따라 한 명씩 확인하여 도달 가능한지 체크
for i in range(1, n + 1):
    count = 0
    for j in range(1, n + 1):
        if graph[i][j] != INF or graph[j][i] != INF:
            count += 1
    if count == n:
        result += 1

print(graph)
print(result)


import time
import logging

import os
import signal

import argparse

class SingingTwice:
    SONG_LIST = ["CHEER UP", "FANCY", "FEEL SPECIAL"]

    def __init__(self, log_file=None):
        logging.basicConfig(level=logging.INFO, format='%(message)s')
        self.logger = logging.getLogger("SingingTwice")
        self.log_file = log_file

        if log_file:
            self.log_handler = logging.FileHandler(self.log_file)
            self.logger.addHandler(self.log_handler)

        self.__stop = False

        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

    def main(self):
        i = 0
        self.logger.info("Start Singing, PID {0}".format(os.getpid()))
        while not self.__stop:
            self.logger.info(self.SONG_LIST[i % len(self.SONG_LIST)])
            i += 1
            time.sleep(1)

    def stop(self, signum, frame):
        self.__stop = True
        self.logger.info("Receive Signal {0}".format(signal))
        self.logger.info("Stop Singing")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--log", help="log filename", default=None)
    args = parser.parse_args()

singing_Twice = SingingTwice()
singing_Twice.main()


import glob
import matplotlib.pyplot as plt
import os, sys
import pandas as pd
import numpy as np
import seaborn as sns
from scipy import stats

colors = [ "amber", "faded green"]
palette = sns.xkcd_palette(colors)
sns.palplot(palette)
plt.rcParams.update({'font.size': 15})
sns.set_style("white")

#%%

RE = "/dors/capra_lab/projects/enhancer_ages/reilly15/results/pleiotropy/"
path = "/dors/capra_lab/projects/enhancer_ages/reilly15/data/multiintersect/"
f = "%strim-0.5_multiintersect_hu_count.bed" % path

#%%

def custom_round(x, base=10):
    return int(base * round(float(x)/base))

def match_len(simple_df, complex_df, base_len):

    columns = ["enh_id", "enh_len"]
    columns_names = ["matching_ids", "matching_len"]

    simple = simple_df[columns].drop_duplicates()

    simple.columns = columns_names
    simple.matching_len = simple.matching_len.astype(float).apply(lambda x: custom_round(x, base=base_len)) # round to the nearest 100bp

    complex = complex_df[columns].drop_duplicates()
    complex.columns = columns_names

    complex.matching_len = complex.matching_len.astype(float).apply(lambda x: custom_round(x, base=base_len))

    lens = set(list(simple.matching_len.unique()) + list(complex.matching_len.unique()))

    match_dict = {}

    for length in lens:
        complexn = len(complex.loc[complex.matching_len == length])
        simplen = len(simple.loc[simple.matching_len == length])

        sn = min(complexn, simplen)

        if length > 0 and sn > 0:

            # find 100 matched enhancer samples

            complex_ids = complex.loc[complex.matching_len == length].sample(n = complexn, replace = False) # sample w/ replacement
            simple_ids = simple.loc[simple.matching_len == length].sample(n = simplen, replace = False) # sample w/ replacement
            balanced = pd.concat([simple_ids, complex_ids])
            match_dict[sn] = balanced

    final_matched_id = pd.concat(match_dict.values())

    return final_matched_id.matching_ids.unique()

def format_df(f):

    df = pd.read_csv(f, sep= '\t', header = None)

    df.columns = ["chr_enh","start_enh", "end_enh",	"enh_id", "fourth_col", "id",\
    "core_remodeling","arch","seg_index","mrca","enh_len", "taxon", "mrca_2",\
    "taxon2",	"mya",	"mya2",	"seg_den",	"datatype", "count_overlap"]

    df["enh_len"] = df.end_enh - df.start_enh

    df["mrca"] = df["mrca"].astype(float).round(3)

    df = df.loc[df.chr_enh != "chrX"]
    df = df.loc[df.enh_len < 10000]

    #df = pd.merge(df, syn_gen_bkgd, how = "left", on = "mrca")

    median = df.seg_index.median()
    #median = 3
    df.loc[df.seg_index >=median, "core_remodeling"] = 1
    df.loc[df.seg_index >=median, "arch"] = "complexenh"

    df.loc[df.seg_index <median, "core_remodeling"] = 0
    df.loc[df.seg_index <median, "arch"] = "simple"

    return df

def get_counts(res, strat):

    if strat == 1:
        counts = res.groupby(["mrca_2", "core_remodeling"])["enh_id"].count().reset_index()

        # add empty dataframe for complex human enhancers (do not exist by our def)
        empty = pd.DataFrame({"mrca_2": [0.000],
        "core_remodeling": [1],
        "enh_id": [0]
        })

        counts = pd.concat([counts, empty]) # concat the dataframe

        counts =counts.sort_values(by = ["core_remodeling", 'mrca_2']).reset_index()

    else:
        counts = res.groupby("arch")["enh_id"].count().reset_index()
        counts =counts.sort_values(by = "arch", ascending = False).reset_index()

    counts["enh_id"] = counts["enh_id"].astype(int)
    counts = counts.drop(["index"], axis = 1)

    return counts
#%%

df = format_df(f)
#%% remove human, primate specific sequences. Sequence must be as olds as euarchontaglires (common ancestor with mouse) in order to be evaluated here.
# removes 470 sequences

print(len(df))
print(median)
#%%
df.groupby(["core_remodeling", "arch"])["enh_id"].count()

#%%

simple_df = df.loc[df.core_remodeling ==0]

complex_df = df.loc[(df.core_remodeling ==1) & (df.enh_len<=simple_df.enh_len.max())]

#%%

matched_id = match_len(simple_df, complex_df, 100)

matched = df.loc[df.enh_id.isin(matched_id)]

matched["arch"] = "simple"
matched.loc[matched.core_remodeling ==1, "arch"] = "complexenh"
matched.mrca = matched.mrca.round(3)
#matched = pd.merge(matched, syn_gen_bkgd[["mrca", "mrca_2", "taxon2"]], how = "left", on ="mrca")
matched = matched.loc[matched.chr_enh != "chrX"]
matched.head()
#%%

sns.distplot(matched.loc[matched.core_remodeling == 0, "enh_len"], kde = False, norm_hist = True, label = "simple")
sns.distplot(matched.loc[matched.core_remodeling != 1, "enh_len"], kde = False, norm_hist = True, label = "complex")
plt.legend()

#%% plot simple v. complex
order = ["simple", "complexenh"]
sns.boxplot(x= "arch", y = "count_overlap", data = matched, order = order)

#%%
from matplotlib import gridspec
from matplotlib.ticker import MultipleLocator

fig = plt.figure(figsize = (12, 8))
gs = gridspec.GridSpec(1, 2, width_ratios=[1, 3])
ax0 = plt.subplot(gs[0])

splot = sns.barplot(x = "arch", y = "count_overlap", data = matched,
            palette = palette, order = order,
            ax = ax0)
STRAT = 0
agecounts = get_counts(matched, STRAT)

for n, p in enumerate(splot.patches):

    value = agecounts.iloc[n]["enh_id"].astype(int)

    splot.annotate(value,
                   (p.get_x() + p.get_width() / 2.,0.05),
                   ha = 'center', va = 'baseline',
                   size=15,
                   rotation = 90,
                   color = "white",
                   xytext = (0, 1),
                   textcoords = 'offset points'
                   )
ax0.set_xticklabels(["Simple", "Complex"], rotation = 90)
ax0.set(xlabel="", ylabel ="Number of Active Species", ylim=(0,2))
ax0.yaxis.set_major_locator(MultipleLocator(0.5))

sns.set("poster")

ax2 = plt.subplot(gs[1])
mplot = sns.barplot(x = "taxon2", y = "count_overlap", hue = "core_remodeling",
              data = matched.sort_values(by = "mrca_2"),
                palette = palette,
            ax = ax2)

STRAT = 1
agecounts = get_counts(matched, STRAT)

for n, p in enumerate(mplot.patches):

    value = agecounts.iloc[n]["enh_id"].astype(int)

    mplot.annotate(value,
                   (p.get_x() + p.get_width() / 2.,0.05),
                   ha = 'center', va = 'baseline',
                   size=15,
                   rotation = 90,
                   color = "white",
                   xytext = (0, 1),
                   textcoords = 'offset points'
                   )

ax2.set_xticklabels(ax2.get_xticklabels(), rotation = 90)
sns.set("poster")
ax2.yaxis.set_major_locator(MultipleLocator(0.5))
ax2.set(ylabel="",  ylim=(0,2))
ax2.legend().remove()
plt.savefig("%sFigS14-JOINT_barplot_reilly15_cross_species_overlap_x_mrca_2.pdf" % RE, bbox_inches = "tight" )

#%%
mwu, p = stats.mannwhitneyu(matched.loc[matched.arch == "simple", "count_overlap"],\
matched.loc[matched.arch != "simple", "count_overlap"])
print(mwu, p)

#%%
matched.groupby("arch")["count_overlap"].mean()

#%%
RE


from discord.ext import commands
import discord

#INVITE
class InviteCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context = True)
    async def invite(self, ctx):
        inv = discord.Embed(title = "", color = 0x3079ec )
        inv.set_author(
            name = "Click here to invite",
            url = "https://discordapp.com/oauth2/authorize?client_id=505040895200985089&scope=bot&permissions=37088334")
        inv.set_footer(
            text = self.bot.user.name + " BOT",
            icon_url = self.bot.user.avatar_url)

        main = discord.Embed(title = ":mailbox_with_mail: Sended! check pm", color = 0x39d0d6 )
        main.set_footer(text = f'Requested by: {ctx.message.author.name}')

        await ctx.send(embed = main)
        await ctx.message.author.send(embed = inv)
        await ctx.message.delete()

def setup(bot):
    bot.add_cog(InviteCog(bot))


import numpy as np
import cv2
from imutils.video import VideoStream
import time

# Model can be downloaded from:
# https://github.com/doleron/yolov5-opencv-cpp-python/tree/main/config_files
net = cv2.dnn.readNet('data/yolov5s.onnx')

labels = open('data/coco.names').read().strip().split('\n')
colors = np.random.randint(0, 255, size=(80, 3), dtype='uint8')

vs = VideoStream(0).start()

while True:
    start = time.time()
    frame = vs.read()
    (h, w) = frame.shape[:2]

    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (640, 640), swapRB=True)
    net.setInput(blob)
    preds = net.forward()

    boxes = []
    confidences = []
    classIds = []

    output = preds[0]
    x_factor = w / 640
    y_factor = h / 640

    for i in range(25200):
        row = output[i]
        confidence = row[4]

        if confidence > 0.5:
            scores = row[5:]
            _, _, _, maxIdx = cv2.minMaxLoc(scores)
            classId = maxIdx[1]

            if scores[classId] > 0.25:
                confidences.append(confidence)
                classIds.append(classId)

                (x, y) = (row[0].item(), row[1].item())
                (w, h) = (row[2].item(), row[3].item())

                left = int((x - 0.5 * w) * x_factor)
                top = int((y - 0.5 * h) * y_factor)
                width = int(w * x_factor)
                height = int(h * y_factor)
                box = np.array([left, top, width, height])
                boxes.append(box)

    indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

    if len(indices) > 0:
        for i in indices.flatten():
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])

            color = [int(c) for c in colors[classIds[i]]]
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            text = '{}: {:.2f}'.format(labels[classIds[i]], confidences[i])
            cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

    end = time.time()
    fps = 1 / (end - start)
    cv2.putText(frame, 'FPS: {}'.format(round(fps, 2)), (50, 50),
                    cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2)

    cv2.imshow('Yolo v5', frame)
    if cv2.waitKey(50) == 27:
        break

cv2.destroyAllWindows()
vs.stop()


from email import header
import json
import pandas as pd
import gspread
from dotenv import load_dotenv
from gspread_dataframe import set_with_dataframe
import os
import json

load_dotenv()

def download_gspread():
    credentials = json.loads(os.environ.get("GCLOUD_CREDENTIALS"))
    gc = gspread.service_account_from_dict(credentials)
    sh = gc.open_by_key(os.environ.get("SPREADSHEET_KEY"))
    worksheet = sh.get_worksheet(0)
    df = pd.DataFrame(worksheet.get_all_values())
    df = df.drop(df.index[0])
    df.columns = ["idOp", "rate", "email"]
    df["idOp"] = pd.to_numeric(df["idOp"])
    df["rate"] = df["rate"].apply(lambda x: float(x.replace(",", ".")))
    return df.to_dict('records')

def upload_datafrae_to_gspread(df):
    credentials = json.loads(os.environ.get("GCLOUD_CREDENTIALS"))
    gc = gspread.service_account_from_dict(credentials)
    sh = gc.open_by_key(os.environ.get("SPREADSHEET_KEY"))
    worksheet = sh.get_worksheet(0)
    worksheet.clear()
    set_with_dataframe(worksheet, df)


"""Finding the time differences between two timestamps or datetime objects."""
# ------------------------ Import libraries and functions ---------------------
import datetime
import re

import dateutil.parser

from cleaning_utils.constants import DATE_SET, ISO_PATTERN, TIME_SET

# ---------------------------- function definition ----------------------------

def datetime_diff(dt1, dt2):
    """Calculates the differences between two timestamps or datetime objects.

    Args:
        dt1 (dict or ISO 8601 str):
            The first datetime input
        dt2 (dict or ISO 8601 str):
            The second datetime input

    Returns:
        A <class 'datetime.timedelta'> from dt2 - dt1.

    Raises:
        Exception: If the input is not a known ISO 8601.

    Examples:
        >>> datetime1 = {
        ...         'month': 1,
        ...         'year': 1399,
        ...         'day': 4,
        ...         'hour': 23,
        ...         'minute': 5,
        ...         'second': 25
        ...     }
        >>> datetime2 = {
        ...         'month': 1,
        ...         'year': 1399,
        ...         'day': 8,
        ...         'hour': 0,
        ...         'minute': 1,
        ...         'second': 0
        ...     }
        >>> datetime_diff(datetime1, datetime2)
        datetime.timedelta(days=3, seconds=3335)
        >>> datetime3 = '2020-03-23T23:05:25+03:26'
        >>> datetime4 = '2020-03-27T00:01:00+03:26'
        >>> datetime_diff(datetime3, datetime4)
        datetime.timedelta(days=3, seconds=3335)

    """
    # -------------------------- string input branch --------------------------
    # string pattern for checking whether the input is a known ISO 8601
    if isinstance(dt2, str) and isinstance(dt1, str):
        if bool(re.match(re.compile(ISO_PATTERN), dt1)) and bool(
            re.match(re.compile(ISO_PATTERN), dt2),
        ):
            result = dateutil.parser.parse(dt2) - dateutil.parser.parse(dt1)
        else:
            raise Exception("unknown datetime formats")
    # --------------------------- dict input branch ---------------------------
    elif isinstance(dt2, dict) and isinstance(dt1, dict):
        if len(dt1.keys()) == len(dt2.keys()) == 6:
            if (TIME_SET <= dt1.keys()) and (TIME_SET <= dt2.keys()):
                result = datetime.datetime(
                    dt2["year"],
                    dt2["month"],
                    dt2["day"],
                    dt2["hour"],
                    dt2["minute"],
                    dt2["second"],
                ) - datetime.datetime(
                    dt1["year"],
                    dt1["month"],
                    dt1["day"],
                    dt1["hour"],
                    dt1["minute"],
                    dt1["second"],
                )
            else:
                raise Exception("unknown datetime formats")
        elif len(dt1.keys()) == len(dt2.keys()) == 3:
            if (DATE_SET <= dt1.keys()) and (DATE_SET <= dt2.keys()):
                result = (
                    datetime.datetime(
                        dt2["year"],
                        dt2["month"],
                        dt2["day"],
                    )
                    - datetime.datetime(dt1["year"], dt1["month"], dt1["day"])
                )
            else:
                raise Exception("unknown datetime formats")
        else:
            raise Exception("unknown datetime formats")
    # ------------------------- incorrect input branch ------------------------
    else:
        raise Exception("unknown datetime formats")
    return result


import sys
sys.stdin = open('input.txt', 'r')

T = int(input())

for tc in range(1, T+1):

    N = int(input())

    B = list(map(int, input().split()))

    max_1 = 0
    min_1 = 1000000
    for i in B:
        if i > max_1:

            max_1 = i

        if i < min_1:

            min_1 = i
    result = max_1 - min_1

    print(f'#{tc} {result}')

알고리즘/알고리즘/강의내용/0804 수업 중 내용/prob_min_max_강현준.py


#比起JS中习惯的NPM 跟 YARN，py的包管理工具是pip/
# 安装一个Pillow pip install Pillow

from PIL import Image
im = Image.open('liangzi.jpg')
print(im.format, im.size, im.mode)
# JPEG (1920, 1080) RGB
im.thumbnail((200, 100))
im.save('liangzi1.jpg', 'JPEG')
# PYTHON真好玩啊，哈哈哈
# python模块的搜索路径是：默认情况下，Python解释器会搜索当前目录、所有已安装的内置模块和第三方模块，搜索路径存放在sys模块的path变量中

# 如果我们要添加自己的搜索目录，有两种方法：
#
# 一是直接修改sys.path，添加要搜索的目录：
#
# >>> import sys
# >>> sys.path.append('/Users/michael/my_py_scripts')


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

# #### Merging games dataframe and season stats dataframe

# > Run all cells in sequence<br>
# > Assumes season stats & game stats files are in '..\data' directory

# In[1]:

import pandas as pd
import os
from tqdm import tqdm

# In[2]:

full_path = os.getcwd()
base_path = full_path
# base_path = str(Path(full_path).parents[0])  # one dir up
base_path = os.path.join(base_path, 'data')

try:
    team_stats_file = os.path.join(base_path, '1970-2020.csv')
    team_schedules_file = os.path.join(base_path, '1970-2020_team_schedule.csv')
    df_stats_raw = pd.read_csv(team_stats_file, sep=';')
    df_schedules_raw = pd.read_csv(team_schedules_file, sep=';')

except FileNotFoundError:
    team_stats_file = os.path.join(base_path, '1970-2021.csv')
    team_schedules_file = os.path.join(base_path, '1970-2021_team_schedule.csv')
    df_stats_raw = pd.read_csv(team_stats_file, sep=';')
    df_schedules_raw = pd.read_csv(team_schedules_file, sep=';')

except:
    raise FileNotFoundError(f"no data files found in {base_path}")

# ---

# In[9]:

df_stats = df_stats_raw.copy()
df_schedules = df_schedules_raw.copy()

# In[11]:

# unnamed_cols = {
#     'Unnamed: 0': 'year',
#     'Unnamed: 1': 'team',
#     'Unnamed: 2': 'week_number'
# }
# df_stats.drop('Unnamed: 1', axis=1, inplace=True)

unnamed_cols = {
    'Unnamed: 0': 'id',
}
df_stats.rename(columns=unnamed_cols, inplace=True)
df_schedules.rename(columns=unnamed_cols, inplace=True)

# #### add 'is_playoff' col

# In[25]:

df_schedules['is_playoff'] = False

for season in tqdm(df_schedules['year'].unique()):
    df_season = df_schedules.query('year == @season')  # only current season
    # print(season, end=', ', flush=False)
    for team in df_season['team'].unique():
        df_season_team = df_season.query('team == @team')  # only current team
        try:  # try to find a row with 'playoff' value
            playoff_index = df_season_team[df_season_team['game_date'] == 'Playoffs'].index[0]
        except IndexError:
            playoff_index = False

        max_index = df_season_team.index[-1]
        if playoff_index:  # if there is a playoff row
            for row in range(playoff_index + 1, max_index + 1):  # for games after playoff row and before last row of current team and current season
                # playoff_game = df_season_team.loc[row].to_dict()

                df_schedules.loc[row, 'is_playoff'] = True

# #### remove 'bye week' & 'playoff' rows

# In[35]:

df_bye_week = df_schedules[(df_schedules['opp'] == 'Bye Week') | (df_schedules['game_date'] == 'Playoffs')]
df_schedules = df_schedules.drop(df_bye_week.index, axis=0)

# ---

# #### column cleaning

# ##### home & away games

# In[36]:

home_games = df_schedules[df_schedules['game_location'] == '@'].index
away_games = df_schedules[pd.isna(df_schedules['game_location'])].index

df_schedules.loc[home_games, 'game_location'] = 'home'
df_schedules.loc[away_games, 'game_location'] = 'away'

# ##### games with overtime

# In[37]:

ot_games = df_schedules[df_schedules['overtime'] == 'OT'].index
non_ot_games = df_schedules[pd.isna(df_schedules['overtime'])].index

df_schedules.loc[ot_games, 'overtime'] = True
df_schedules.loc[non_ot_games, 'overtime'] = False

# #### further column cleaning

# In[38]:

columns = df_schedules.columns
df_schedules = df_schedules.drop('boxscore_word', axis=1)

# #### the actual merge

# ##### Column prefixes
#     - gs_  : game_stat_
#     - hts_ : home_team_stat_
#     - ats_ : away_team_stat_

# In[40]:

df_schedules.columns = 'gs_' + df_schedules.columns

df_home_team_stats = df_stats.copy()
df_home_team_stats.columns =  'hts_' + df_home_team_stats.columns

df_away_team_stats = df_stats.copy()
df_away_team_stats.columns =  'ats_' + df_away_team_stats.columns

# In[41]:

df_games = pd.merge(
    df_schedules,
    df_home_team_stats,
    how='inner',
    left_on=['gs_team', 'gs_year'],
    right_on=['hts_team', 'hts_year'],
)
print('With home team stats:', df_games.shape)

df_games = pd.merge(
    df_games,
    df_away_team_stats,
    how='inner',
    left_on=['gs_opp', 'gs_year'],
    right_on=['ats_team', 'ats_year'],
)
print('With home and away team stats:', df_games.shape)

# ---

# #### playoffs and regular season

# In[43]:

df_regular_season = df_games[df_games['gs_is_playoff'] == False]
df_playoffs = df_games[df_games['gs_is_playoff'] == True]

# #### export to csv

df_games = df_games.reset_index().drop('index', axis=1)
df_playoffs = df_playoffs.reset_index().drop('index', axis=1)
df_regular_season = df_regular_season.reset_index().drop('index', axis=1)

# In[54]:
print('')
print(f'{"Exporting raw data":<30}', end='')
df_games.to_csv(os.path.join(base_path, 'all_games.csv'), sep=';', encoding='utf-8', index=True)
df_playoffs.to_csv(os.path.join(base_path, 'playoffs.csv'), sep=';', encoding='utf-8', index=True)
df_regular_season.to_csv(os.path.join(base_path, 'regular_season.csv'), sep=';', encoding='utf-8', index=True)

print('Done')
# In[]:

# #### kaggle files
print(f'{"Exporting kaggle data":<30}', end='')
cols_to_drop = [
    'gs_overtime', 'gs_pts_off', 'gs_pts_def',
    'gs_first_down_off', 'gs_yards_off', 'gs_pass_yds_off',
    'gs_rush_yds_off', 'gs_to_off', 'gs_first_down_def',
    'gs_yards_def', 'gs_pass_yds_def', 'gs_rush_yds_def',
    'gs_to_def', 'gs_exp_pts_off', 'gs_exp_pts_def', 'gs_exp_pts_st',
    'gs_is_playoff', 'gs_team_record',
    'hts_year', 'hts_team', 'hts_team.1',
    'ats_year', 'ats_team', 'ats_team.1'
]
df_playoffs.drop(cols_to_drop, axis=1, inplace=True)
df_playoffs = df_playoffs[df_playoffs['gs_game_location'].isin(['N', 'home'])]

# renaming cols
cols_to_rename = {
    'gs_game_outcome': 'winorlose'
}
df_playoffs.rename(cols_to_rename, axis=1, inplace=True)

# reordering
new_col_order = ['gs_id', 'gs_year', 'gs_team', 'gs_opp']
new_col_order += df_playoffs.drop(new_col_order + ['winorlose'], axis=1).columns.tolist() + ['winorlose']
df_playoffs = df_playoffs[new_col_order]

# In[]:
# exporting kaggle datasets
df_kaggle_train = df_playoffs[~df_playoffs['gs_year'].isin([2018, 2019, 2020, 2021])]  # years not in
df_kaggle_test = df_playoffs[df_playoffs['gs_year'].isin([2018, 2019, 2020, 2021])]  # years in
df_kaggle_test_labels = df_kaggle_test[['gs_id', 'winorlose']]

df_kaggle_test.drop('winorlose', axis=1, inplace=True)  # target col

sample_submission = [(i, 'W') for i in range(10)] + [(i, 'L') for i in range(10, 20)]
df_sample_submission = pd.DataFrame(sample_submission, columns=['gs_id', 'winorlose'])

df_kaggle_train.to_csv(os.path.join(base_path, 'df_kaggle_train.csv'), sep=';', encoding='utf-8', index=False)
df_kaggle_test.to_csv(os.path.join(base_path, 'df_kaggle_test.csv'), sep=';', encoding='utf-8', index=False)
df_kaggle_test_labels.to_csv(os.path.join(base_path, 'df_kaggle_test_labels.csv'), sep=';', encoding='utf-8', index=False)
df_sample_submission.to_csv(os.path.join(base_path, 'df_kaggle_sample_submission.csv'), sep=';', encoding='utf-8', index=False)
print('Done')


from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.validators import MinValueValidator, RegexValidator
from django.db import models

User = get_user_model()

class Recipe(models.Model):
    author = models.ForeignKey(
        User,
        verbose_name='Автор',
        related_name='recipes',
        on_delete=models.CASCADE,
        default=1
    )
    name = models.CharField(
        verbose_name='Название',
        max_length=200)
    image = models.ImageField(
        verbose_name='Картинка',
        upload_to='recipes/',
        help_text='Загрузите изображение',
        default='default.jpg',
        blank=False,
    )
    text = models.TextField(
        verbose_name='Описание',
        max_length=5000)
    ingredient = models.ManyToManyField(
        'Ingredient',
        verbose_name='Ингредиенты',
        related_name='recipes',
        through='IngredientAmount'
    )
    tags = models.ManyToManyField(
        'Tag',
        verbose_name='Теги',
        related_name='recipes',
    )
    cooking_time = models.PositiveSmallIntegerField(
        verbose_name='Время приготовления',
        validators=(
            MinValueValidator(
                limit_value=settings.MIN_TIME_COOKING,
                message='Укажите время приготовления, которое больше, '
                        + f'либо равно {settings.MIN_TIME_COOKING}'),),
        default=1)
    pub_date = models.DateTimeField(
        verbose_name='Дата публикации',
        auto_now_add=True,
        editable=False,
    )

    class Meta:
        verbose_name = 'Рецепт'
        verbose_name_plural = 'Рецепты'
        ordering = ('-pub_date',)

    def __str__(self):
        return self.name

    def clean(self):
        self.name = self.name.capitalize()
        return super().clean()

class Tag(models.Model):
    name = models.CharField(
        verbose_name='Название',
        max_length=200,
        unique=True,
    )
    color = models.CharField(
        verbose_name='Цвет в виде "HEX"',
        max_length=7,
        unique=True,
        validators=([RegexValidator(regex=r'^#[A-Fa-f0-9]{6}$')])
    )
    slug = models.SlugField(
        verbose_name='Уникальный фрагмент URL-адреса',
        max_length=200,
        unique=True,
    )

    class Meta:
        verbose_name = 'Тег'
        verbose_name_plural = 'Теги'
        ordering = ('name',)

    def __str__(self):
        return self.name

    def clean(self):
        self.name = self.name.lower()
        self.slug = self.slug.lower()
        return super().clean()

class Ingredient(models.Model):
    name = models.CharField(
        verbose_name='Название',
        max_length=200,
    )
    measurement_unit = models.CharField(
        verbose_name='Единица измерения',
        max_length=200,
    )

    class Meta:
        verbose_name = 'Ингредиент'
        verbose_name_plural = 'Ингредиенты'
        ordering = ('name',)
        constraints = (
            models.UniqueConstraint(
                fields=('name', 'measurement_unit',),
                name='unique_ingredient'),)

    def __str__(self) -> str:
        return self.name

    def clean(self):
        self.name = self.name.lower()
        self.measurement_unit = self.measurement_unit.lower()
        return super().clean()

class IngredientAmount(models.Model):
    recipe = models.ForeignKey(
        'Recipe',
        verbose_name='Рецепт',
        on_delete=models.CASCADE,
        related_name='ingredient_amount'
    )
    ingredient = models.ForeignKey(
        'Ingredient',
        verbose_name='Ингредиент',
        on_delete=models.CASCADE,
        related_name='ingredient_amount'
    )
    amount = models.PositiveSmallIntegerField(
        verbose_name='Количество',
        validators=(
            MinValueValidator(
                limit_value=settings.MIN_AMOUNT,
                message='Укажите количество, которое больше, '
                + f'либо равно {settings.MIN_AMOUNT}'),),
    )

    class Meta:
        verbose_name = 'Количество ингредиента'
        verbose_name_plural = 'Количество ингредиентов'
        constraints = (
            models.UniqueConstraint(
                fields=('recipe', 'ingredient',),
                name='unique_ingredient_amount'),)

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

class Subscriptions(models.Model):
    user = models.ForeignKey(
        User,
        verbose_name='Подписчик',
        related_name='subscriber',
        on_delete=models.CASCADE,
    )
    author = models.ForeignKey(
        User,
        verbose_name='Автор',
        related_name='subscribing',
        on_delete=models.CASCADE,
    )

    class Meta:
        verbose_name = 'Подписка'
        verbose_name_plural = 'Подписки'
        constraints = (
            models.UniqueConstraint(
                fields=('user', 'author',), name='unique_subscriptions'),)

    def __str__(self) -> str:
        return f'{self.user} подписан(-а) на {self.author}'

class Favorites(models.Model):
    user = models.ForeignKey(
        User,
        verbose_name='Пользователь',
        related_name='favorites',
        on_delete=models.CASCADE,
    )
    recipe = models.ForeignKey(
        'Recipe',
        verbose_name='Рецепт',
        related_name='favorites',
        on_delete=models.CASCADE,
    )

    class Meta:
        verbose_name = 'Избранное'
        verbose_name_plural = 'Избранное'
        constraints = (
            models.UniqueConstraint(
                fields=('user', 'recipe',), name='unique_favorites'),)

    def __str__(self) -> str:
        return f'{self.recipe} добавлен в избранное {self.user}'

class ShoppingCart(models.Model):
    user = models.ForeignKey(
        User,
        verbose_name='Покупатель',
        related_name='shopping_cart',
        on_delete=models.CASCADE,
    )
    recipe = models.ForeignKey(
        'Recipe',
        verbose_name='Рецепт',
        related_name='shopping_cart',
        on_delete=models.CASCADE,
    )

    class Meta:
        verbose_name = 'Список покупок'
        verbose_name_plural = 'Списки покупок'
        constraints = (
            models.UniqueConstraint(
                fields=('user', 'recipe',), name='unique_shopping_cart'),)

    def __str__(self) -> str:
        return f'{self.recipe} в списке покупок {self.user}'


import pygame

class Compass:
    def __init__(self, surface, func_list):
        self.screen=surface
        self.dg=func_list[0]
        self.npc=func_list[1]
        self.ms=func_list[2]
        self.pl=func_list[3]
        self.level=[[0 for i in range(42)] for j in range(64)]
        self.color={'mist':(0,0,0), 'bk':(255, 255, 255), 'wall1':(100, 100, 100),
                    'floor1':(190, 190, 190), 'box':(225, 185, 0), 'grass':(124, 252, 0),
                    'tree':(0,128, 0), 'swamp':(50, 205, 50), 'water':(30, 144, 255),
                    'lava':(255, 0, 0), 'stairs':(128, 0, 0), 'fence':(150, 150, 150), 'door':(128, 128, 0),
                    'clay1':(105, 50, 0), 'clay2':(130, 90, 50), 'deco1':(255, 99, 71),
                    'deco2':(110, 255, 195), 'trap':(0, 0, 255), 'npc':(186, 85, 211)}
        self.colorMap={0:'wall1',  # 灰色砖墙
            1:'floor1',  # 黑色地板
            2:'stairs', # 楼梯
            3:'grass',  # 草地
            4:'water',  # 水体
            5:'lava',  # 岩浆
            6: 'swamp',  # 沼泽
            7: 'tree',  # 树木
            8:'fence',  # 铁栅栏和gate
            9:'clay1',      #洞穴墙
            10:'clay2',     #洞穴地面
            64 :'door',       #不透明门
            65 :'box',       #箱子
            66 :'trap',       #陷阱
            67:'deco1',  #不可交互的装饰品
            68:'deco2'      #可交互物品
        }
        self.judge=0
        self.pic=pygame.image.load(r'asset\compass.png').convert_alpha()

    def getColor(self, x):
        if x<=99:
            return self.colorMap[x]
        elif x>99: return 'npc'
        else: return 'floor1'

    def getChar(self, x, y):
        return self.level[x][y]

    def setChar(self, x, y, val):
        self.level[x][y]=val

    def getMap(self):
        for x in range(0, 64):
            for y in range(0, 42):
                dgp = self.convertDg(self.dg.getChar(x, y))
                surp = self.convertSur(self.dg.sur.getChar(x, y))
                self.setChar(x, y, max(dgp, surp))
        for k in self.npc.npc_pos:
            self.setChar(*k, 100)

    @staticmethod
    def convertDg(x):
        if x in {0, 10, 15, 22}:
            return 0        #灰色砖墙
        elif x in {1, 2, 11, 12, 14, 23, 24, 25, 26}:
            return 1        #黑色地板
        elif x in {3, 4, 16, 17, 29, 30}:
            return 2        #楼梯
        elif x in {5, 6}:
            return 3        #草地
        elif x in {8, 9}:
            return 4        #水体
        elif x in {18, 19}:
            return 5        #岩浆
        elif x in {20, 21}:
            return 6        #沼泽
        elif x==7:
            return 7        #树木
        elif x==13:
            return 8        #铁栅栏和gate
        elif x in {27, 28}:     #褐色墙壁
            return 9
        elif x in {31, 32}:     #褐色地面
            return 10

    @staticmethod
    def convertSur(x):
        if x in {0, 1, 2, 12, 39}:
            return 64       #不透明门
        elif x in {3, 4}:
            return 8        #铁栅栏和gate
        elif x in range(5, 10):
            return 65       #箱子
        elif x in {10, 11, 13, 14, 15}:
            return 66       #陷阱
        elif x in {16, 17, 18, 24, 26, 29, 32, 34, 36, 42}:
            return 67       #不可交互的装饰品
        elif x in {22, 23, 25, 27, 28, 30, 31, 33, 34, 37, 38, 40, 41}:     #其他装饰
            return 68
        else: return -1

    def drawMist(self, x, y):
        for i in range(0, 64):
            for j in range(0, 42):
                judge=self.ms.getChar(i, j)
                if not judge:
                    pygame.draw.rect(self.screen, self.color['mist'], (x+4*i, 4*j+y, 4, 4), 0)

    def drawMap(self, x, y):
        for i in range(0, 64):
            for j in range(0, 42):
                judge=self.getChar(i, j)
                tag=self.getColor(judge)
                pygame.draw.rect(self.screen, self.color[tag], (x+4*i, y+4*j, 4, 4), 0)

    def drawCompass(self, x, y):
        if self.judge:
            self.getMap()
            self.screen.blit(self.pic, (x-9, y-9))
            self.drawMap(x, y)
            pygame.draw.rect(self.screen, self.color['bk'], (self.pl.xat*4+x, self.pl.yat*4+y, 4, 4), 0)
            self.drawMist(x, y)

    def openMap(self):
        self.judge=1-self.judge


"""
This module provides orchestration to run and execute Python Jobs from the command line
"""
from typing import Callable, Any, List
from jobtools.arguments import TaskArguments, get_args_from_signature, get_parser_from_signature
from jobtools.joblogger import get_logger

class TaskRunner():
    """
    Allows an easy way to run a task in Azure ML and log any input into the run. Tasks are
    specified a callable with arguments that are automatically parsed from the signature. The
    method should return a dictionary with keys "metrics", "arguments" and "artifacts".
    """

    def __init__(self, name: str, args: TaskArguments = None, ignore_arguments: List[str] = None,
                 debug: bool = False) -> None:
        """
        Initializes the TaskRunner. If `args` is indicated, then the argument's won't be parsed
        from the command line. Otherwise they will.

        Parameters
        ----------
        name: str
            Name of the module or task to run. This property can be any string value.
        args: TaskArguments
            Use args when you are using `TaskRunner` directly in Python instead of from the command
            line. When this argument is indicated, no parsing from command line will happen.
        ignore_arguments: List[str]
            Arguments that will be present in the command line but should not be used or enforced
            for the task that will be executed. Defaults to none. This parameter has no effect if
            `args` is indicated.
        debug: bool
            Indicates if debug information should be displayed
        """
        self.name = name
        self.task_arguments = args
        self.ignore_arguments = ignore_arguments or []
        self.debug = debug
        self._logger = get_logger(name, debug)

    def run(self, task: Callable[[], Any]) -> Any:
        """
        Runs the given task specified as a method. Arguments are determined from the signature of
        the method and they should match the arguments indicated in the command line unless they
        are indicated using the `args` arguments during `init`.

        Parameters
        ----------
        task: Callable[[], Dict[TaskResultKey, Dict[str, Any]]]
            The task you want to run. This method can be any that returns a dictionary with keys
            `arguments`, `metrics` and `artifacts`. Parameters for this method will either be
            demanded from the command line or have to be indicated in the constructor of the
            `TaskRunner` object.
        """
        if self.task_arguments is None:
            args = get_args_from_signature(task, self.ignore_arguments)
        else:
            args = self.task_arguments.resolve_for_method(task)

        for key, value in args.items():
            self._logger.debug(f"Argument {key} = {str(value)}")

        self._logger.debug(f"Running method -> {task.__name__}")
        return task(**args)

    def display_help(self, task: Callable[[], Any]) -> None:
        """
        Displays the help for a given method

        Parameters
        ----------
        task : Callable[[], Any]
            The task or method you want to display help for.
        """
        parser = get_parser_from_signature(task, self.ignore_arguments)
        parser.print_help()


"""
Starting from scratch with the discord bot template using the Bot class instead of the Client class.
"""
import asyncio
import discord
from discord.ext import commands
import os

intents = discord.Intents.all()
bot = commands.Bot(
    intents=intents,
    command_prefix='/',
)

def process_message(message):
    try:
        """
        This is where the logic for the bot goes.
        """
        pass
    except Exception as e:
        return f'<Error>: {e}'

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')
    channel = bot.get_channel(int(os.environ.get('SANDBOX_DISCORD_CHAN_ID')))
    await channel.send(f'{bot.user} has connected to Discord!')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    elif message.content.startswith('!') or message.content == "":
        return
    else:
        # use asyncio to run the process_message function in the background
        response = await asyncio.get_event_loop().run_in_executor(None, process_message, message)
        channel = bot.get_channel(int(os.environ.get('SANDBOX_DISCORD_CHAN_ID')))
        await channel.send(response)

bot.run(os.environ.get('SANDBOX_DISCORD_TOKEN'))


# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 09:26:02 2021

@author: beatriz garcia
"""
import random

tablero = [
	[ '_', '_', '_' ],
	[ '_', '_', '_' ],
	[ '_', '_', '_' ]
]

conteo = 0
for i in range(3):
    for j in range(3):
        if (tablero[i][j]=="_"):
            conteo = conteo + 1

if (conteo == 9):
    inicio = []
    for i in range(3):
        for j in range(3):
            inicio.append((i,j))
    inicial = random.choice(inicio)
    tablero[inicial[0]][inicial[1]] = 'O'

for k in range(conteo):
    def recompensas(tablero):

    	# Evaluar por filas las victorias de X y O
    	for i in range(3) :
    		if (tablero[i][0] == tablero[i][1] and tablero[i][1] == tablero[i][2]) :
    			if (tablero[i][0] == 'X') :
    				return 1
    			elif (tablero[i][0] == 'O') :
    				return -1

    	# Evaluar por columnas las victorias de X y O
    	for j in range(3) :

    		if (tablero[0][j] == tablero[1][j] and tablero[1][j] == tablero[2][j]) :

    			if (tablero[0][j] == 'X') :
    				return 1
    			elif (tablero[0][j] == 'O') :
    				return -1

    	# Evaluar por diagonales las victorias de X y O
    	if (tablero[0][0] == tablero[1][1] and tablero[1][1] == tablero[2][2]) :

    		if (tablero[0][0] == 'X') :
    			return 1
    		elif (tablero[0][0] == 'O') :
    			return -1

    	if (tablero[0][2] == tablero[1][1] and tablero[1][1] == tablero[2][0]) :

    		if (tablero[0][2] == 'X') :
    			return 1
    		elif (tablero[0][2] == 'O') :
    			return -1

    	# Si nadie gana
    	return 0

    def betty(tablero, depth, isMax) :
    	score = recompensas(tablero)

    	if (score == 1) :
    		return score

    	if (score == -1) :
    		return score

    	if (score == 0 and isMovesLeft(tablero) == False) :
    		return 0

    	if (score == 0 and isMovesLeft(tablero) == True) :
    		if (isMax):
    			bestlist1 = []
    			for i in range(3) :
    				for j in range(3) :

    					if (tablero[i][j]=='_') :

    						tablero[i][j] = 'X'

    						# Recursividad
    						bestlist1.append( betty(tablero, depth + 1, not isMax) )
    						sumar = 0
    						value = 0
    						for t in range(len(bestlist1)):
    							sumar = sumar + bestlist1[t]
    						value = sumar / len(bestlist1)

    						tablero[i][j] = '_'
    			return value

    		else :
    			bestlist2 = []

    			for i in range(3) :
    				for j in range(3) :

    					if (tablero[i][j] == '_') :

    						tablero[i][j] = 'O'

    						# Recursividad
    						bestlist2.append(betty(tablero, depth + 1, not isMax) )

    						sumar = 0
    						value = 0
    						for t in range(len(bestlist2)):
    							sumar = sumar + bestlist2[t]
    						value = sumar / len(bestlist2)

    						tablero[i][j] = '_'
    			return value
    	return score

    def isMovesLeft(tablero) :

    	for i in range(3) :
    		for j in range(3) :
    			if (tablero[i][j] == '_') :
    				return True
    	return False

    def findBestMove(tablero, par):
    	if k in par:
    		bestVal = -1000
    	if k not in par:
    		bestVal = 1000
    	bestMove = (-1, -1)

    	# Minimax
    	for i in range(3) :
    		for j in range(3) :
    			if (tablero[i][j] == '_') :
    				score = 0
    				# Verifica si hay lugares en donde puede ganar el oponente
    				if k in par:
    					tablero[i][j] = 'X'
    					score = recompensas(tablero)
    					if (score == 1):
    						tablero[i][j] = '_'
    						bestMove = (i, j, score)
    						return bestMove
    					tablero[i][j] = 'O'
    					score = recompensas(tablero)
    					if (score == -1):
    						tablero[i][j] = '_'
    						bestMove = (i, j, score)
    						return bestMove
    				else:
    					tablero[i][j] = 'O'
    					score = recompensas(tablero)
    					if (score == -1):
    						tablero[i][j] = '_'
    						bestMove = (i, j, score)
    						return bestMove
    					tablero[i][j] = 'X'
    					score = recompensas(tablero)
    					if (score == 1):
    						tablero[i][j] = '_'
    						bestMove = (i, j, score)
    						return bestMove

    				if k in par:
    					tablero[i][j] = 'X'
    				else:
    					tablero[i][j] = 'O'

    				moveVal = betty(tablero, 0, False)
    				tablero[i][j] = '_'
    				# Nuevo mejor que el anterior
    				if (k in par and moveVal >= bestVal) :
    					bestMove = (i,j,moveVal)
    					bestVal = moveVal
    					if (len(options) > 0):
    						for y in range(len(options)):
    							if (moveVal > options[0][2]):
    								options.pop(0)
    					options.append(bestMove)
    				if (k not in par and moveVal <= bestVal) :
    					bestMove = (i,j,moveVal)
    					bestVal = moveVal
    					if (len(options) > 0):
    						for t in range(len(options)):
    							if (moveVal < options[0][2]):
    								options.pop(0)
    					options.append(bestMove)

    	if len(options) == 0:
    		return 'termina'
    	else:
    		return random.choice(options)

    options = []
    par = [0,2,4,6,8]

    bestMove = findBestMove(tablero, par)
    if bestMove !='termina':
        print()
        if k in par:
            print("El movimiento óptimo para 'X' es:","Fila", bestMove[0], " Columna", bestMove[1])
        else:
            print("El movimiento óptimo para 'O' es:","Fila", bestMove[0], " Columna", bestMove[1])

        if k in par:
            tablero[bestMove[0]][bestMove[1]] = 'X'
        else:
            tablero[bestMove[0]][bestMove[1]] = 'O'
        print("Tablero con el movimiento óptimo:")
        for i in range(3):
            print (tablero[i][0]+str('|'), tablero[i][1]+str('|'), tablero [i][2])
        if (recompensas(tablero) == 1 or recompensas(tablero)==-1):
            break


from selenium import  webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
import time

class Slider():
    def test(self):

        #for firefox at first we have to show the path where is the Geckodriver located
        #we set a variable "driverlocation" which will store the driver path
        driverlocation = "/usr/local/bin/gecko_driver/geckodriver"
        #now instantiate the firefox browser with the parameter of driver location
        driver = webdriver.Firefox(executable_path=driverlocation)
        # At first maximize the window
        driver.maximize_window()
        # Open The Provided URL with driver.get method
        baseURL = "http://www.jqueryui.com/droppable"
        driver.get(baseURL)
        # wait until the browser is fully loaded by implicitly_wait method
        driver.implicitly_wait(3)

        # At first switch to the iframe where is the drag and drop element located
        driver.switch_to.frame(0)

        element = driver.find_element(By.XPATH,"//div[@id='slider']//span")
        time.sleep(2)
        try:
            # for actions like mouse hovering we have to use selenium method Action Chains
            actions = ActionChains(driver) # here actions is the object we created from the class ActionChains
            # For every actions we have to run move to element method and perform the action
            actions.drag_and_drop_by_offset(element,100,0).perform()
            print("Sliding Element Successfully")
            time.sleep(2)

        except:
            print("Sliding failed on element")

run_test = Slider()
run_test.test()


from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

def visualize_svd(A, fig, pos=111, show_axes=True):
    ax = fig.add_subplot(pos, projection='3d')
    ax.view_init(elev=30, azim=30)
    ax.set_aspect('equal')

    s = np.linspace(0, 2*np.pi, 50)
    t = np.linspace(0, np.pi, 50)

    X = np.outer(np.cos(s), np.sin(t))
    Y = np.outer(np.sin(s), np.sin(t))
    Z = np.outer(np.ones(np.size(s)), np.cos(t))

    for i in range(len(s)):
        for j in range(len(t)):
            X[i,j], Y[i,j], Z[i,j] = A @ np.array([X[i,j], Y[i,j], Z[i,j]])

    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='plasma', edgecolor=None, alpha=0.7)
    #ax.plot_wireframe(X, Y, Z, edgecolor='black', linewidth=0.2)

    if show_axes:
        u, s, vh = np.linalg.svd(A)
        for s1 in np.diag(s):
            b = np.dot(u, s1) # było v
            ax.plot([0, b[0]], [0, b[1]], [0, b[2]], linewidth=2)

    # aspect ratio 1:1
    max_range = np.array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max() / 2.0
    mid_x = (X.max()+X.min()) * 0.5
    mid_y = (Y.max()+Y.min()) * 0.5
    mid_z = (Z.max()+Z.min()) * 0.5
    ax.set_xlim(mid_x - max_range, mid_x + max_range)
    ax.set_ylim(mid_y - max_range, mid_y + max_range)
    ax.set_zlim(mid_z - max_range, mid_z + max_range)

if __name__ == "__main__":

    #A = np.random.rand(3, 3)
    A = np.array([[7,0,0],[2,3,0],[0,0,4]])
    # print(A)
    u, sd, vh = np.linalg.svd(A)
    s = np.diag(sd)
    v = vh.T
    I = np.identity(3)

    for i, T in enumerate((I, v, s @ v, A), 1):
        fig = plt.figure()
        visualize_svd(T, fig, 111, i == 4)
        plt.show()
    #plt.savefig('main.png', dpi=1200)


# Попов Юрий ИУ7-12Б
# Дана матрица символов. Заменить в ней все гласные английские буквы на
# точки. Напечатать матрицу до и после преобразования.

def input_matrix(n: int, name: str) -> list:
    """Ввод квадратной матрицы"""
    matx = []
    for i in range(n):
        el = list(map(int, input(f'Введите {i + 1} строку матрицы {name} : ').split()))
        matx.append(el)
    return matx

def input_lst(n: int, name: str) -> list:
    lst = []
    for i in range(n):
        el = int(input(f'Введите {i + 1} элемент списка {name}: '))
        lst.append(el)

    return lst

def output_matrix(matx, name: str):
    """Вывод матрицы"""
    output_string = ''
    for i, string in enumerate(matx):
        output = ''.join([f"{s:^6.6g}" for s in string])
        output_string += f'{name}[{i + 1}] = {output}\n'
    return output_string

def output_list(list, name: str):
    """Вывод листа"""
    output_string = ''
    for i, s in enumerate(list):
        output_string += f'{name}[{i + 1}] = {s:^6.6g}\n'
    return output_string

vowels = "aouei"
len_d = int(input('Введите размер матрицы: '))
matrix = input_matrix(len_d, 'matrix')
print('До:')
output_matrix(matrix, "matrix")

for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        try:
            if matrix[i][j].lower() in vowels:
                matrix[i][j] = "."
        except AttributeError:
            pass

print('После:')
output_matrix(matrix, "matrix")


from bs4 import BeautifulSoup as bs
import re
from contextlib import suppress
import traceback
from dateutil import parser
import requests
import xlsxwriter
from difflib import SequenceMatcher
from datetime import datetime, date
from datetime import timedelta
from webauto_base import webauto_base
import time
import math
import sqlite3
import logging
import os
espnArray =  []
collageArray = []
spreadArray = []

def get_espn():
    try:
        print("Request to https://www.espn.com/mens-college-basketball/standings...")
        url = "https://www.espn.com/mens-college-basketball/standings"
        #Get the Page Content String from the Espn
        pageString = requests.get(url).text
        soup = bs(pageString, 'html.parser')

        sections = soup.findAll('section', {'class':'ResponsiveTable'})

        for section in sections:
            conference_name = list(section.children)[0].get_text()

            tr = section.findChildren("tr", {'class','Table__TR--sm'})

            for i in range(int(len(tr)/2)):
                team_name = tr[i].find("abbr")
                point = tr[int(len(tr)/2)+i].findChildren("span", {'class', 'stat-cell'})
                if team_name is not None:
                    espnArray.append({
                        "conference_name" : conference_name,
                        "team_name" : team_name['title'],
                        "abbr" : team_name.get_text(),
                        "c_w_l": point[0].get_text(),
                        "c_gb": point[1].get_text(),
                        "c_pct": point[2].get_text(),
                        "o_w_l": point[3].get_text(),
                        "o_pct": point[4].get_text(),
                        "o_home": point[5].get_text(),
                        "o_away": point[6].get_text(),
                        "o_strk": point[7].get_text(),
                    })
    except Exception as e:
        print(str(e))
        logging.info(str(e))
        traceback.print_exc()

def get_colleage():
    try:
        print("Request to https://www.espn.com/mens-college-basketball/bpi/_/view/overview/sort/sospastrank/dir/asc...")
        url = "https://www.espn.com/mens-college-basketball/bpi/_/view/overview/sort/sospastrank/dir/asc"
        pg = 1
        while pg < 100:
            try:
                url = "https://www.espn.com/mens-college-basketball/bpi/_/view/overview/sort/sospastrank/page/" + str(pg) + "/dir/asc"
                page = requests.get(url).text
                soup = bs(page, 'html.parser')

                no_data = soup.find('div', {'class' : 'no-data-available'})
                if no_data is not None and no_data.get_text() == "No data available.":
                    break

                trs = soup.findAll('tr')

                for tr in trs:
                    try:
                        td = tr.findChildren('td')
                        if len(td) == 8:
                            collageArray.append({
                                'team_name' : td[1].find('span',{'class','team-names'}).get_text(),
                                'abbr' : td[1].find('abbr').get_text(),
                                'conf' : '',
                                'bpi_rk' : td[4].get_text(),
                                'sos_rk' : td[5].get_text(),
                                'sor_rk' : td[6].get_text(),
                            })
                    except:
                        pass

            except Exception as exx:
                print(str(exx))
                logging.info(str(exx))
                pass
            pg = pg + 1

    except Exception as e:
        print(str(e))
        logging.info(str(e))
        traceback.print_exc()

class get_spread(webauto_base):
    def __del__(self):
        super().__init__()

    def automate(self):
        try:
            print("Automation to get spreads...")

            url = "https://www.sportsbookreview.com/betting-odds/ncaa-basketball/"
            self.start_browser(False)
            self.navigate(url)

            self.delay_me(3)

            xpath = "//div[@id='bettingOddsGridContainer']/div[3]/*"
            bettingContainer = self.browser.find_elements_by_xpath(xpath)

            # #print(day)
            xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//div[@data-vertical-sbid='time']/div//span"
            p_time = self.browser.find_elements_by_xpath(xpath)
            #print(len(p_time))

            # #print(len(p_time))

            xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section//a//span"
            teams = self.browser.find_elements_by_xpath(xpath)

            #print(len(teams))
            xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='-1']//span[@data-cy='odd-grid-opener-league']"
            opener = self.browser.find_elements_by_xpath(xpath)

            bookmarker = None
            five_times = None
            bovada = None

            count = 0
            while True:
                xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='93']//span[@data-cy='odd-grid-league']"
                bookmarker = self.browser.find_elements_by_xpath(xpath)

                xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='19']//span[@data-cy='odd-grid-league']"
                five_times = self.browser.find_elements_by_xpath(xpath)

                xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='1618']//span[@data-cy='odd-grid-league']"
                bovada = self.browser.find_elements_by_xpath(xpath)

                if len(opener) == len(bookmarker) or len(opener) == len(five_times) or len(opener) == len(bovada):
                    break

                count = count + 1
                if count > 100 and (len(bookmarker) == 0 or len(five_times) == 0 or len(bovada) == 0):
                    break

            if len(bookmarker) == 0 or len(five_times) == 0 or len(bovada) == 0:
                xpath = "//i[@class='sbr-icon-chevron-right']"
                right = self.browser.find_element_by_xpath(xpath)
                right = right.find_element_by_xpath("..")
                right.click()

                self.delay_me(3)

                if len(bookmarker) == 0:
                    xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='93']//span[@data-cy='odd-grid-league']"
                    bookmarker = self.browser.find_elements_by_xpath(xpath)

                if len(five_times) == 0:
                    xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='19']//span[@data-cy='odd-grid-league']"
                    five_times = self.browser.find_elements_by_xpath(xpath)

                if len(bovada) == 0:
                    xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='1618']//span[@data-cy='odd-grid-league']"
                    bovada = self.browser.find_elements_by_xpath(xpath)

                right.click()

                self.delay_me(3)

                if len(bookmarker) == 0:
                    xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='93']//span[@data-cy='odd-grid-league']" #93
                    bookmarker = self.browser.find_elements_by_xpath(xpath)

                if len(five_times) == 0:
                    xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='19']//span[@data-cy='odd-grid-league']"
                    five_times = self.browser.find_elements_by_xpath(xpath)

                if len(bovada) == 0:
                    xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section[@data-vertical-sbid='1618']//span[@data-cy='odd-grid-league']"
                    bovada = self.browser.find_elements_by_xpath(xpath)

            print("Processing...")
            bettingDate = None
            i = 0
            for divs in bettingContainer:
                try:
                    bettingDate = divs.find_element_by_xpath("./div/div/span")
                    if bettingDate.text != "Box Scores":
                        bettingDate = bettingDate.text
                        continue

                    if bettingDate.text == "Box Scores":
                        continue

                except:
                    pass
                try:
                    length = len(divs.find_elements_by_xpath("./div"))
                    if length >= 2 and bettingDate is not None:

                        point_A_T = ""
                        point_B_T = ""
                        diff_A = 0
                        diff_B = 0
                        if length == 3:
                            points = divs.find_elements_by_xpath("./div[2]/div/div")
                            try:
                                point_A_T = int(points[len(points)-1].text.split("\n")[0])
                                point_B_T = int(points[len(points)-1].text.split("\n")[1])
                                diff_A = point_A_T - point_B_T
                                diff_B = point_B_T - point_A_T
                            except:
                                pass

                        opener_f = "-"
                        opener_s = "-"
                        try:
                            opener_val = opener[i].find_elements_by_xpath("./span")
                            opener_f = opener_val[0].text
                            opener_s = opener_val[1].text
                        except:
                            pass

                        bookmarker_f = "-"
                        bookmarker_s = "-"
                        try:
                            bookmarker_val = bookmarker[i].find_elements_by_xpath("./span")
                            bookmarker_f = bookmarker_val[0].text
                            bookmarker_s = bookmarker_val[1].text
                        except:
                            pass

                        five_times_f = "-"
                        five_times_s = "-"
                        try:
                            five_times_val = five_times[i].find_elements_by_xpath("./span")
                            five_times_f = five_times_val[0].text
                            five_times_s = five_times_val[1].text
                        except:
                            pass

                        bovada_f = "-"
                        bovada_s = "-"
                        try:
                            bovada_val = bovada[i].find_elements_by_xpath("./span")
                            bovada_f = bovada_val[0].text
                            bovada_s = bovada_val[1].text
                        except:
                            pass

                        spreadArray.append({
                            'team' : teams[i].text,
                            'opener' : getOdds(opener_f),
                            'opener_odds': getOdds(opener_s),
                            'bookmarker' : getOdds(bookmarker_f),
                            'bookmarker_odds' : getOdds(bookmarker_s),
                            'five_times' : getOdds(five_times_f),
                            'five_times_odds' : getOdds(five_times_s),
                            'bovada' : getOdds(bovada_f),
                            'bovada_odds' : getOdds(bovada_s),
                            'date': bettingDate,
                            'point': point_A_T,
                            'diff': diff_A
                        })

                        opener_f = "-"
                        opener_s = "-"
                        try:
                            opener_val = opener[i+1].find_elements_by_xpath("./span")
                            opener_f = opener_val[0].text
                            opener_s = opener_val[1].text
                        except:
                            pass

                        bookmarker_f = "-"
                        bookmarker_s = "-"
                        try:
                            bookmarker_val = bookmarker[i+1].find_elements_by_xpath("./span")
                            bookmarker_f = bookmarker_val[0].text
                            bookmarker_s = bookmarker_val[1].text
                        except:
                            pass

                        five_times_f = "-"
                        five_times_s = "-"
                        try:
                            five_times_val = five_times[i+1].find_elements_by_xpath("./span")
                            five_times_f = five_times_val[0].text
                            five_times_s = five_times_val[1].text
                        except:
                            pass

                        bovada_f = "-"
                        bovada_s = "-"
                        try:
                            bovada_val = bovada[i+1].find_elements_by_xpath("./span")
                            bovada_f = bovada_val[0].text
                            bovada_s = bovada_val[1].text
                        except:
                            pass

                        spreadArray.append({
                            'team' : teams[i+1].text,
                            'opener' : getOdds(opener_f),
                            'opener_odds': getOdds(opener_s),
                            'bookmarker' : getOdds(bookmarker_f),
                            'bookmarker_odds' : getOdds(bookmarker_s),
                            'five_times' : getOdds(five_times_f),
                            'five_times_odds' : getOdds(five_times_s),
                            'bovada' : getOdds(bovada_f),
                            'bovada_odds' : getOdds(bovada_s),
                            'date': bettingDate,
                            'point': point_B_T,
                            'diff': diff_B
                        })
                        i = i + 2
                except:
                    pass

            print("getting point ...")
            yesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y%m%d')
            url = "https://www.sportsbookreview.com/betting-odds/ncaa-basketball/?date=" + yesterday

            xpath = "/html/body/div[1]/div/div/div/section/div/div[2]/div[1]/span[2]"
            self.click_element(xpath, 3, 0)

            self.delay_me(3)

            xpath = "//div[@id='bettingOddsGridContainer']/div[3]/*"
            self.wait_present(xpath, 30)
            bettingContainer = self.browser.find_elements_by_xpath(xpath)

            xpath = "//div[@id='bettingOddsGridContainer']//div//div//div//section//a//span"
            teams = self.browser.find_elements_by_xpath(xpath)

            bettingDate = None
            i = 0
            for divs in bettingContainer:
                try:
                    bettingDate = divs.find_element_by_xpath("./div/div/span")
                    if bettingDate.text != "Box Scores":
                        bettingDate = bettingDate.text
                        #print(i)
                        continue

                    if bettingDate.text == "Box Scores":
                        continue

                except:
                    pass
                try:
                    length = len(divs.find_elements_by_xpath("./div"))
                    if length >= 2 and bettingDate is not None:

                        point_A_T = ""
                        point_B_T = ""
                        diff_A = 0
                        diff_B = 0

                        teamNameA = ""
                        teamNameB = ""
                        if length == 3:
                            points = divs.find_elements_by_xpath("./div[2]/div/div")
                            teamNameA = divs.find_element_by_xpath("./div[1]/section/div[1]/div[1]/div/a/span").text
                            teamNameB = divs.find_element_by_xpath("./div[1]/section/div[1]/div[2]/div/a/span").text
                            try:
                                point_A_T = int(points[len(points)-1].text.split("\n")[0])
                                point_B_T = int(points[len(points)-1].text.split("\n")[1])
                                diff_A = point_A_T - point_B_T
                                diff_B = point_B_T - point_A_T
                            except:
                                pass

                        if spreadArray[i]["point"] == "" and teamNameA == spreadArray[i]["team"]:
                            spreadArray[i]["point"] = point_A_T
                            spreadArray[i]["diff"] = diff_A

                        if spreadArray[i+1]["point"] == "" and teamNameB == spreadArray[i+1]["team"]:
                            spreadArray[i+1]["point"] = point_B_T
                            spreadArray[i+1]["diff"] = diff_B
                        i = i + 2
                except:
                    pass
            self.quit_browser()
        except Exception as e:
            print(str(e))
            logging.info(str(e))
            traceback.print_exc()

def findDay():
    return date.today().weekday()

def getToday():
    return datetime.today().strftime("%Y-%m-%d")

def get_conf(team_name):

    try:
        tmp = espnArray[0]
        pt = 0
        for espn in espnArray:
            if pt < SequenceMatcher(None, espn['team_name'].lower(), team_name.lower()).ratio():
                pt = SequenceMatcher(None, espn['team_name'].lower(), team_name.lower()).ratio()
                tmp = espn

        return tmp
    except:
        logging.info("Not found the get_conf of team_name")
        return None

def get_coll(team_name):
    try:
        tmp = collageArray[0]
        pt = 0
        for collage in collageArray:
            if pt < SequenceMatcher(None, collage['team_name'].lower(), team_name.lower()).ratio():
                pt = SequenceMatcher(None, collage['team_name'].lower(), team_name.lower()).ratio()
                tmp = collage

        return tmp
    except:
        logging.info("Not found the coll of team_name")
        return None

def getCurrentDate():
    return datetime.today().day

def getCurrentMonth():
    return datetime.today().strftime("%b")

def getOdds(odds):
    try:
        odds = odds.replace('½','.5')
        if odds == 'PK':
            odds = '0'
        elif odds == '-':
            odds = '0'

        return odds

    except:
        return '0'

def make_data():
    print("Creating...")
    try:
        # insert the information into database

        today = getToday()

        conn = sqlite3.connect('my.db')
        c = conn.cursor()
        c.execute("delete from spread where update_time='{}'".format(today))
        conn.commit()

        index = 1
        flag = False

        todayData = []
        for spread in spreadArray:
            first_A = get_conf(spread['team'])
            first_B = get_coll(spread['team'])

            away_home = ""
            result = 0
            away_30 = ""
            home_70 = ""
            sharp = ""
            wager = ""
            p_d = ""
            if spread['diff'] > 0:
                p_d = spread['diff']

            if index % 2 == 1:
                away_home = first_A["o_away"]

                try:
                    array = first_A["o_away"].split('-')
                    result = round(int(array[0])/(int(array[0])+int(array[1])) * 100)
                except:
                    result = 0
                    pass

                if result <= 30:
                    flag = True
                else:
                    flag = False
            else:
                away_home = first_A["o_home"]

                result = 0
                try:
                    array = first_A["o_home"].split('-')
                    result = round(int(array[0])/(int(array[0])+int(array[1])) * 100)
                except:
                    result = 0
                    pass

                if result >= 70:
                    home_70 = 1
                else:
                    home_70 = 0

                try:
                    sharp = float(spread['bovada']) - float(spread['bookmarker'])
                except:
                    sharp = 0

                wager = "no"
                if flag == True:
                    away_30 = 1

                    if result >= 70 and sharp > 0:
                        wager = "yes"
                else:
                    away_30 = 0

            todayData.append(list({
                'date': spread['date'],
                'team': spread['team'],
                'conf': first_A["conference_name"],
                'spread': spread['opener'],
                'spread_odd': spread['opener_odds'],
                'bookmaker': spread['bookmarker'],
                'bootmaker_odd': spread['bookmarker_odds'],
                'fivetime': spread['five_times'],
                'fivetime_odd': spread['five_times_odds'],
                'bovada': spread['bovada'],
                'bovada_odd': spread['bovada_odds'],
                'away_home': away_home,
                'percentage': str(result) + "%",
                'w_l': first_A["o_pct"],
                'strk': first_A["o_strk"],
                'bpi_rank': first_B['bpi_rk'],
                'sos_rank': first_B['sos_rk'],
                'sor_rank': first_B['sor_rk'],
                'score': spread['point'],
                'p_d': p_d,
                'away_30': str(away_30),
                'home_70': str(home_70),
                'sharp': str(sharp),
                'wager': wager,
                'update_time': today
            }.values()))

            index = index + 1

        c.executemany("insert into spread('date','team','conf','spread','spread_odd','bookmaker','bootmaker_odd','fivetime','fivetime_odd','bovada','bovada_odd','away_home','percentage','w_l','strk','bpi_rank','sos_rank','sor_rank','score','p_d','away_30','home_70','sharp','wager','update_time') values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", todayData)
        conn.commit()
        conn.close()
    except Exception as e:
        logging.info(str(e))
        pass

def make_spread():
    print("Making...")
    try:
        today = datetime.now()

        dayNumber = findDay()
        filename = "result_" + today.strftime("%Y%m%d%H%M%S") + ".xlsx"

        workbook = xlsxwriter.Workbook(filename)
        worksheet = workbook.add_worksheet('NCAA Teams')

        bold = workbook.add_format({'bold': True})
        worksheet.write(0, 0, "Team", bold)
        worksheet.write(0, 1, "Conference", bold)
        worksheet.write(0, 2, "W-L (Conference)", bold)
        worksheet.write(0, 3, "GB", bold)
        worksheet.write(0, 4, "PCT", bold)
        worksheet.write(0, 5, "W-L (Overall)", bold)
        worksheet.write(0, 6, "PCT", bold)
        worksheet.write(0, 7, "Home", bold)
        worksheet.write(0, 8, "PCT", bold)
        worksheet.write(0, 9, "Away", bold)
        worksheet.write(0, 10, "PCT", bold)
        worksheet.write(0, 11, "STRK", bold)

        index = 1
        for espn in espnArray:
            worksheet.write(index, 0, espn['team_name'])
            worksheet.write(index, 1, espn['conference_name'])
            worksheet.write(index, 2, espn['c_w_l'])
            worksheet.write(index, 3, espn['c_gb'])
            worksheet.write(index, 4, espn['c_pct'])
            worksheet.write(index, 5, espn['o_w_l'])
            worksheet.write(index, 6, espn['o_pct'])
            worksheet.write(index, 7, espn['o_home'])
            worksheet.write(index, 9, espn['o_away'])
            worksheet.write(index, 11, espn['o_strk'])

            result = 0
            try:
                array = espn["o_home"].split('-')
                result = round(int(array[0])/(int(array[0])+int(array[1])) * 100)
            except:
                result = 0
                pass
            worksheet.write(index, 8, str(result) + "%")

            result = 0
            try:
                array = espn["o_away"].split('-')
                result = round(int(array[0])/(int(array[0])+int(array[1])) * 100)
            except:
                result = 0
                pass
            worksheet.write(index, 10, str(result) + "%")

            index = index + 1

        conn = sqlite3.connect('my.db')
        c = conn.cursor()

        weekday = findDay()

        bold = workbook.add_format({'bold': True})
        green_format1 = workbook.add_format()
        green_format1.set_pattern(1)  # This is optional when using a solid fill.
        green_format1.set_bg_color('green')

        tomato_format2 = workbook.add_format()
        tomato_format2.set_pattern(1)  # This is optional when using a solid fill.
        tomato_format2.set_bg_color('#ff6347')

        magenta_format = workbook.add_format()
        magenta_format.set_pattern(1)  # This is optional when using a solid fill.
        magenta_format.set_bg_color('magenta')

        for i in range(weekday+1):

            findex = weekday -i
            day = datetime.strftime(datetime.now() - timedelta(findex), '%Y-%m-%d')
            date = datetime.strftime(datetime.now() - timedelta(findex), '%d')
            month = datetime.strftime(datetime.now() - timedelta(findex), '%b')
            worksheet = workbook.add_worksheet(month + '.' + date)

            c.execute("select * from spread where update_time='" + day + "'")
            data = c.fetchall()
            if data is not None:

                worksheet.write(0, 0, "Date", bold)
                worksheet.write(0, 1, "Team", bold)
                worksheet.write(0, 2, "Conf", bold)
                worksheet.write(0, 3, "Spread (Opener)", bold)
                worksheet.write(0, 4, "Odds", bold)
                worksheet.write(0, 5, "Spread (BookMaker)", bold)
                worksheet.write(0, 6, "Odds", bold)
                worksheet.write(0, 7, "Spread (5 Dimes)", bold)
                worksheet.write(0, 8, "Odds", bold)
                worksheet.write(0, 9, "Spread (Bovada)", bold)
                worksheet.write(0, 10, "Odds", bold)
                worksheet.write(0, 11, "Away/Home Overall Record", bold)
                worksheet.write(0, 12, "Percentage", bold)
                worksheet.write(0, 13, "W-L (Overall) PCT", bold)
                worksheet.write(0, 14, "STRK", bold)
                worksheet.write(0, 15, "BPI Rank", bold)
                worksheet.write(0, 16, "SOS Rank", bold)
                worksheet.write(0, 17, "SOR Rank", bold)
                worksheet.write(0, 18, "Score", bold)
                worksheet.write(0, 19, "P.D", bold)
                worksheet.write(0, 20, "Away 30% below", bold)
                worksheet.write(0, 21, "Home 70% above", bold)
                worksheet.write(0, 22, "Sharp-Square", bold)
                worksheet.write(0, 23, "Wager", bold)

                index = 1
                for row in data:
                    worksheet.write(index, 0, row[1])
                    worksheet.write(index, 1, row[2])
                    worksheet.write(index, 2, row[3])
                    worksheet.write(index, 3, row[4])
                    worksheet.write(index, 4, row[5])

                    if row[6] != row[10]:
                        worksheet.write(index, 5, row[6], magenta_format)
                        worksheet.write(index, 9, row[10], magenta_format)
                    else:
                        worksheet.write(index, 5, row[6])
                        worksheet.write(index, 9, row[10])

                    worksheet.write(index, 6, row[7])
                    worksheet.write(index, 7, row[8])
                    worksheet.write(index, 8, row[9])
                    worksheet.write(index, 10, row[11])

                    worksheet.write_string(index, 11, row[12])

                    if index % 3 == 1:
                        if float(row[13].replace('%','')) <= 30:
                            worksheet.write(index, 12, row[13], tomato_format2)
                        else:
                            worksheet.write(index, 12, row[13])
                    else:
                        if float(row[13].replace('%','')) >= 70:
                            worksheet.write(index, 12, row[13], green_format1)
                        else:
                            worksheet.write(index, 12, row[13])

                    #worksheet.write(index, 12, row[13])
                    worksheet.write(index, 13, row[14])
                    worksheet.write(index, 14, row[15])
                    worksheet.write(index, 15, row[16])
                    worksheet.write(index, 16, row[17])
                    worksheet.write(index, 17, row[18])
                    worksheet.write(index, 18, row[19])
                    worksheet.write(index, 19, row[20])
                    worksheet.write(index, 20, row[21])
                    worksheet.write(index, 21, row[22])
                    worksheet.write(index, 22, row[23])
                    worksheet.write(index, 23, row[24])

                    index = index + 1
                    if index % 3 == 0:
                        index = index + 1

        worksheet = workbook.add_worksheet("Weekly Total")
        worksheet.write(0, 0, "Date", bold)
        worksheet.write(0, 1, "Matchcup", bold)
        worksheet.write(0, 2, "Result", bold)
        worksheet.write(0, 3, "P.D", bold)
        worksheet.write(0, 4, "Bookmaker", bold)
        worksheet.write(0, 5, "Away Record", bold)
        worksheet.write(0, 6, "Home Record", bold)
        worksheet.write(0, 7, "Wager", bold)
        worksheet.write(0, 8, "Bookmaker-P.D", bold)
        index = 1
        for i in range(weekday+1):

            findex = weekday -i
            day = datetime.strftime(datetime.now() - timedelta(findex), '%Y-%m-%d')
            date = datetime.strftime(datetime.now() - timedelta(findex), '%d')
            month = datetime.strftime(datetime.now() - timedelta(findex), '%b')

            c.execute("select * from spread where update_time='" + day + "'")
            data = c.fetchall()
            if data is not None:

                for tindex in range(int(len(data)/2)):
                    row = data[tindex*2]
                    nrow = data[tindex*2 + 1]
                    if nrow[24] == "yes":
                        away = "0"
                        home = "0"
                        naway = "0"
                        nhome = "0"
                        try:
                            h_a = row[12].split("-")
                            away = h_a[0]
                            home = h_a[1]
                        except:
                            pass

                        try:
                            nh_a = nrow[12].split("-")
                            naway = nh_a[0]
                            nhome = nh_a[1]
                        except:
                            pass

                        worksheet.write(index, 0, row[1])   #Date
                        worksheet.write(index, 1, row[2])   #Matchcup
                        worksheet.write(index, 2, row[19])   #Result
                        worksheet.write(index, 3, row[20])   #P.D
                        worksheet.write(index, 4, row[6])   #Bookmaker
                        worksheet.write(index, 5, away)   #Away Record
                        worksheet.write(index, 6, home)   #Home Record
                        worksheet.write(index, 7, row[24])   #Wager
                        worksheet.write(index, 8, row[23])   #Bookmaker-P.D

                        worksheet.write(index+1, 0, nrow[1])   #Date
                        worksheet.write(index+1, 1, nrow[2])   #Matchcup
                        worksheet.write(index+1, 2, nrow[19])   #Result
                        worksheet.write(index+1, 3, nrow[20])   #P.D
                        worksheet.write(index+1, 4, nrow[6])   #Bookmaker
                        worksheet.write(index+1, 5, naway)   #Away Record
                        worksheet.write(index+1, 6, nhome)   #Home Record
                        worksheet.write(index+1, 7, nrow[24])   #Wager
                        worksheet.write(index+1, 8, nrow[23])   #Bookmaker-P.D

                        index = index + 2
                        if index % 3 == 0:
                            index = index + 1
        conn.close()
        workbook.close()
    except Exception as e:
        logging.info(str(e))
        pass

def main():
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)
    filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ncaa.log')
    logging.basicConfig(filename=filename,level=logging.INFO,format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',)
    logging.info("Start...")
    logging.info("Espn...")
    get_espn()

    logging.info("colleage...")
    get_colleage()

    logging.info("spread...")
    spread = get_spread()
    spread.automate()

    logging.info("making...")
    make_data()

    logging.info("creating...")
    make_spread()

    logging.info("End...")

main()


# encoding: utf-8
__author__ = 'Liubov Penyugalova'

import pickle
import os
import sys

# debug.py - вывод на экран + добавила все сопутствующие функции, необходимые для работы программы

def action_func():
    act = input('Нажмите 1 чтобы внести данные. 2 чтобы увидеть весь список. 3 чтобы найти определенный атомобилью 4 чтобы править/удалитью 5 чтобы выйти: ')
    action = act
    return action

def error():
    print('Ошибка ввода!')

def input_data(file):
    user_input = []

    key = input('Введите марку автомобиля:')
    key = key.lower()
    key2 = key.replace(' ', '')

    while key2.isalpha() == False:
        error()
        key = input('Введите марку автомобиля:')
        key = key.lower()
        key2 = key.replace(' ', '')
        continue

    value = input('Введите его мощность:')
    value_to_check = str(value)
    value_to_check = value_to_check.replace(".","")

    while value_to_check.isnumeric() == False:
        error()
        value = input('Введите мощность автомобиля числами (разделитель порядков - точка):')
        value_to_check = str(value)
        value_to_check = value_to_check.replace(".","")
        continue

    tup = (key, value)
    user_input.append(tup)

    act = action_func()

    if act == 1:
        input_data()
    else:
        user_inp = user_input
        import db
        db.pickle_close(user_inp, file)

def show_data(file_db):
    lst_1 = sorted(file_db)
    print('Обычная сортировка')
    for i in lst_1:
        print(i, ':', file_db.get(i))

    lst_2 = list(file_db.keys())
    for n1, i in enumerate(lst_2):
        for n2, ii in enumerate(lst_2):
            if i<ii:
                lst_2[n1], lst_2[n2] = lst_2[n2], lst_2[n1]
    print('Пузырьковая сортировка')
    for i in lst_2:
        print(i, ':', file_db.get(i))

def filter_strict(file_db):
    user_input = input('Введите марку автомобиля: ')
    user_input = user_input.strip()
    user_input = user_input.lower()
    if user_input in file_db.keys():
        print(user_input, ':', file_db.get(user_input))

def filter_non_strict(file_db):
        user_input = input('Введите элемент марки автомобиля: ')
        user_input = user_input.strip()
        user_input = user_input.lower()

        for i in file_db.keys():
            key_string = str(i)
            if key_string.find(user_input) != -1:
                print(i, ':', file_db.get(i))

def filter_power(file_db):
    user_input = input('Введите мощность автомобиля одной или двумя (если интересует промежуток) цифрами с пробелом: ')
    user_input = user_input.strip()
    user_input = user_input.split()
    if len(user_input) == 1:
        for i in file_db.keys():
            if type(file_db.get(i)) == str:
                val = [file_db.get(i)]
            else:
                val = file_db.get(i)
            if len(val) > 1:
                for ii in val:
                    if user_input[0] == ii:
                        print(i, ':', ii)
            else:
                if user_input[0] == val[0]:
                    print(i, ':', val[0])

    elif len(user_input) == 2:
        n1 = int(user_input[0])
        n2 = int(user_input[1])

        if n1 > n2:
           n1, n2 = n2, n1

        for i in file_db.keys():
            if type(file_db.get(i)) == str:
                val = [file_db.get(i)]
            else:
                val = file_db.get(i)
            if len(val) > 1:
                for ii in val:
                    if int(ii) >= n1 and int(ii) <= n2:
                        print(i, ':', ii)
            else:
                if int(val[0]) >= n1 and int(val[0]) <= n2:
                    print(i, ':', val[0])
    else:
        user_input = input('Неверно указана мощность.')

def edit(file_db):
    print('Сейчас в базе хранится следующая информация: ')
    print(file_db)
    sec_action = input('Введите 1 для внесения изменений. Введите 2 для удаления элементов.')

    if sec_action == '1':
        key_input   = input('Напечатайте авто, информацию о котором вы хотите изменить: ')
        what_input  = input('Нажмите 1, чтобы исправить название и 2 - мощность: ')
        if  what_input == '1':
           new_input = input('Введите правильное написание: ')
           new_power = file_db.get(key_input)
           file_db.update({new_input:new_power})
           file_db.pop(key_input)
           print('Информация исправлена: ')
           print(file_db)
        else:
           new_power = input('Введите правильную мощность: ')
           trash = file_db.pop(key_input)
           file_db.update(key_input,new_power)
    elif sec_action == '2':
        key_input   = input('Напечатайте авто, информацию о котором вы хотите изменить: ')
        trash = file_db.pop(key_input)
        print('Информация удалена: ')
        print(file_db)
    else:
        pass


# -*- coding: utf-8 -*-
"""
Created on Wed May 30 21:08:08 2018

@author: Mike
"""

import numpy as np

(v,m) = np.genfromtxt('sample.csv',skip_header=1,delimiter=';',unpack=True)

#%%
m_total = np.sum(m)
iters = int(len(m)*(len(m)-1)/2)

sums = np.zeros((iters,4))

#%%
i=0
for end in range(len(m)):
    for start in range(end):

        sums[i,0]=start
        sums[i,1]=end
        sums[i,2]=end-start
        sums[i,3]=np.sum(m[start:end])/m_total
        i+=1

#%%
r_crit = 0.8

s=sums[sums[:,3]>r_crit]


from __future__ import unicode_literals
import youtube_dl

def my_status(d):
    if d['status'] == 'finished':
        print('Finished!')

ydl_opts = {
    'progress_hooks': [my_status]
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/playlist?list=PL86SiVwkw_ofvEbosKlapvTrLs7geMKvp'])


'''
# Time   : 2020/10/22 15:07
# Author : junchaoli
# File   : model.py
'''

from layer import Wide_layer, Deep_layer

import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Embedding

class WideDeep(Model):
    def __init__(self, feature_columns, hidden_units, output_dim, activation):
        super().__init__()
        self.dense_feature_columns, self.sparse_feature_columns = feature_columns
        self.embedding_layer = {'embed_layer'+str(i): Embedding(feat['feat_onehot_dim'], feat['embed_dim'])
                                for i,feat in enumerate(self.sparse_feature_columns)}

        self.wide = Wide_layer()
        self.deep = Deep_layer(hidden_units, output_dim, activation)

    def call(self, inputs):
        # dense_inputs: 数值特征，13维
        # sparse_inputs： 类别特征，26维
        # onehot_inputs：onehot处理的类别特征(wide侧的输入)
        dense_inputs, sparse_inputs, onehot_inputs = inputs[:, :13], inputs[:, 13:39], inputs[:, 39:]

        # wide部分
        wide_input = tf.concat([dense_inputs, onehot_inputs], axis=-1)
        wide_output = self.wide(wide_input)

        # deep部分
        sparse_embed = tf.concat([self.embedding_layer['embed_layer'+str(i)](sparse_inputs[:, i]) \
                        for i in range(sparse_inputs.shape[-1])], axis=-1)
        deep_output = self.deep(sparse_embed)

        output = tf.nn.sigmoid(0.5*(wide_output + deep_output))
        return output


#!/usr/bin/env python3

"""https://www.graphviz.org/pdf/dotguide.pdf, Figure 12"""

import graphviz

s = graphviz.Digraph('structs', filename='structs_revisited.gv',
                     node_attr={'shape': 'record'})

s.node('struct1', '<f0> left|<f1> middle|<f2> right')
s.node('struct2', '<f0> one|<f1> two')
s.node('struct3', r'hello\nworld |{ b |{c|<here> d|e}| f}| g | h')

s.edges([('struct1:f1', 'struct2:f0'), ('struct1:f2', 'struct3:here')])

s.view()