import random

from PyQt6.QtWidgets import QMainWindow, QLabel, QPushButton
from PyQt6.QtGui import QPixmap, QPainter, QPen, QBrush
from PyQt6.QtCore import Qt

from model import Model

class View(QMainWindow):
    '''Класс для создания объекта окна приложения'''

    def __init__(self):
        super(View, self).__init__()

        self.setGeometry(800, 200, 417, 684)

        self.setWindowTitle("My App")

        self.to_update = False

    def label_1(self):
        self.label1 = QLabel(self)
        self.label1.setText(" - Веревочка с колокольчиком")
        self.label1.move(102, 366)
        self.label1.adjustSize()

    def label_2(self):
        self.label2 = QLabel(self)
        self.label2.setText(" - Детектор протоплазмы")
        self.label2.move(102, 405)
        self.label2.adjustSize()

    def button_1(self):
        self.button1 = QPushButton(self)
        self.button1.setText("Стереть траектории")
        self.button1.move(60, 452)
        self.button1.setFixedSize(294, 27)

    def button_2(self):
        self.button2 = QPushButton(self)
        self.button2.setText("Перетасовать ловушки")
        self.button2.move(60, 485)
        self.button2.setFixedSize(294, 27)

    def button_3(self):
        self.button3 = QPushButton(self)
        self.button3.setStyleSheet('QPushButton {color: blue;}')
        self.button3.setText("Запустить кошку")
        self.button3.move(60, 543)
        self.button3.setFixedSize(294, 27)

    def button_4(self):
        self.button4 = QPushButton(self)
        self.button4.setStyleSheet('QPushButton {color: green;}')
        self.button4.setText("Запустить вампуса")
        self.button4.move(60, 576)
        self.button4.setFixedSize(294, 27)

    def button_5(self):
        self.button5 = QPushButton(self)
        self.button5.setStyleSheet('QPushButton {color: yellow;}')
        self.button5.setText("Запустить преведение")
        self.button5.move(60, 609)
        self.button5.setFixedSize(294, 27)

    def pictore_box_1(self):
        self.labelImage1 = QLabel(self)
        self.pixmap1 = QPixmap("./rope.png")
        self.labelImage1.setGeometry(60, 355, 36, 35)
        self.pixmap1 = self.pixmap1.scaled(36, 35)
        self.labelImage1.setPixmap(self.pixmap1)

    def pictore_box_2(self):
        self.labelImage2 = QLabel(self)
        self.pixmap2 = QPixmap("./detector.png")
        self.labelImage2.setGeometry(60, 394, 36, 35)
        self.pixmap2 = self.pixmap2.scaled(36, 35)
        self.labelImage2.setPixmap(self.pixmap2)

    def pictore_box_3(self, picutre, qp): #1
        self.pixmap3 = QPixmap(f"./{picutre}.png")
        self.pixmap3 = self.pixmap3.scaled(100, 100)
        qp.drawPixmap(60, 45, 100, 100, self.pixmap3)

    def pictore_box_4(self, picutre, qp): #2
        self.pixmap4 = QPixmap(f"./{picutre}.png")
        self.pixmap4 = self.pixmap4.scaled(100, 100)
        qp.drawPixmap(157, 45, 100, 100, self.pixmap4)

    def pictore_box_5(self, picutre, qp): #3
        self.pixmap5 = QPixmap(f"./{picutre}.png")
        self.pixmap6 = self.pixmap5.scaled(100, 100)
        qp.drawPixmap(254, 45, 100, 100, self.pixmap5)

    def pictore_box_6(self, picutre, qp):#4
        self.pixmap6 = QPixmap(f"./{picutre}.png")
        self.pixmap6 = self.pixmap6.scaled(100, 100)
        qp.drawPixmap(60, 142, 100, 100, self.pixmap6)

    def pictore_box_7(self, picutre, qp): #5
        self.pixmap7 = QPixmap(f"./{picutre}.png")
        self.pixmap7 = self.pixmap7.scaled(100, 100)
        qp.drawPixmap(157, 142, 100, 100, self.pixmap7)

    def pictore_box_8(self, picutre, qp): #6
        self.pixmap8 = QPixmap(f"./{picutre}.png")
        self.pixmap8 = self.pixmap8.scaled(100, 100)
        qp.drawPixmap(254, 142, 100, 100, self.pixmap8)

    def pictore_box_9(self, picutre, qp): #7
        self.pixmap9 = QPixmap(f"./{picutre}.png")
        self.pixmap9 = self.pixmap9.scaled(100, 100)
        qp.drawPixmap(60, 239, 100, 100, self.pixmap9)

    def pictore_box_10(self, picutre, qp): #8
        self.pixmap10 = QPixmap(f"./{picutre}.png")
        self.pixmap10 = self.pixmap10.scaled(100, 100)
        qp.drawPixmap(157, 239, 100, 100, self.pixmap10)

    def pictore_box_11(self, picutre, qp): #9
        self.pixmap11 = QPixmap(f"./{picutre}.png")
        self.pixmap11 = self.pixmap11.scaled(100, 100)
        qp.drawPixmap(254, 239, 100, 100, self.pixmap11)

    def paintEvent(self, e):
        '''Метод для создания графики'''

        self.qp = QPainter()
        self.qp.begin(self)
        self.create_field()
        self.draw_traps()
        self.draw_cat(Model.cat_coords)
        self.draw_vampus(Model.vampus_coords)
        self.draw_ghost(Model.ghost_coords)
        self.qp.end()

    def create_field(self):
        '''Метод, генерирующий основное поле'''

        if Model.update_field:
            random.shuffle(Model.traps_on_the_field)

        for idx, value in enumerate(Model.traps_on_the_field, start=3):
                eval(f"self.pictore_box_{idx}")(value, self.qp)

        Model.update_field = False

    def draw_cat(self, coords):
        '''Метод, отображающий траекторию кота'''

        if coords:
            pen = QPen(Qt.GlobalColor.blue, 7, Qt.PenStyle.SolidLine)

            first_point, second_point = 0, 1
            while second_point <= len(coords) - 1:
                first_coord = coords[first_point]
                second_coord = coords[second_point]

                self.qp.setPen(pen)
                self.qp.drawLine(first_coord[0], first_coord[1], second_coord[0], second_coord[1])
                first_point += 1
                second_point += 1

    def draw_vampus(self, coords):
        '''Метод, отображающий траекторию вампуса'''

        if coords:
            pen = QPen(Qt.GlobalColor.green, 7, Qt.PenStyle.SolidLine)

            first_point, second_point = 0, 1
            while second_point <= len(coords) - 1:
                first_coord = coords[first_point]
                second_coord = coords[second_point]
                self.qp.setPen(pen)
                self.qp.drawLine(first_coord[0], first_coord[1], second_coord[0], second_coord[1])
                first_point += 1
                second_point += 1

    def draw_ghost(self, coords):
        '''Метод, отображающий траекторию приведения'''

        if coords:
            pen = QPen(Qt.GlobalColor.yellow, 7, Qt.PenStyle.SolidLine)

            first_point, second_point = 0, 1
            while second_point <= len(coords) - 1:
                first_coord = coords[first_point]
                second_coord = coords[second_point]
                self.qp.setPen(pen)
                self.qp.drawLine(first_coord[0], first_coord[1], second_coord[0], second_coord[1])
                first_point += 1
                second_point += 1

    def draw_traps(self):
        '''Метод, отображающий сработавшие ловушки'''

        pen = QPen(Qt.GlobalColor.red, 7, Qt.PenStyle.SolidLine)
        self.qp.setPen(pen)
        brush = QBrush()
        self.qp.setBrush(brush)
        for trap in Model.triggered_traps:
            cell = Model.cells_coords[trap]
            self.qp.drawRect(cell[0], cell[1], 100, 100)


#!/usr/bin/env python3

import turtle              # 1.  import the modules
import random
wn = turtle.Screen()       # 2.  Create a screen
wn.bgcolor('lightblue')

sean = turtle.Turtle()     # 3.  Create two turtles
amy = turtle.Turtle()
sean.color('red')
amy.color('blue')
sean.shape('turtle')
amy.shape('turtle')

sean.up()                  # 4.  Move the turtles to their starting point
amy.up()
sean.goto(-300,20)
amy.goto(-300,-20)

# your code goes here
for i in range(100):
	sean.forward(random.randrange(1,11))
	amy.forward(random.randrange(1,11))

wn.exitonclick()


from uagents import Context, Model, Protocol
import typing
import os
from dotenv import load_dotenv
import requests

class CurrencyParams(Model):
    base_currency: str
    foreign_currency: str
    number: str

class RequestLimits(Model):
    msg: str

class ThresholdLimits(Model):
    max: float
    min: float

class RegistrationStatus(Model):
    msg: str

currency_protocol = Protocol()

@currency_protocol.on_message(CurrencyParams, replies=RequestLimits)
async def process_input(ctx: Context, sender: str, msg:CurrencyParams):

    ctx.logger.info(msg.base_currency)
    ctx.storage.set("base", msg.base_currency)

    ctx.storage.set('foreign', msg.foreign_currency)
    ctx.storage.set("number", msg.number)

    output_msg = f"Please Enter Values For {msg.foreign_currency}"

    await ctx.send(sender, RequestLimits(msg=output_msg))

@currency_protocol.on_message(ThresholdLimits, replies=RegistrationStatus)
async def process_limits(ctx: Context, sender: str, msg:ThresholdLimits):

    min = msg.min
    max = msg.max

    ctx.storage.set("min", min)
    ctx.storage.set("max", max)

    output_msg = f"Your inputs have been recorded! We will notify you if the rates go past the limits."

    ctx.storage.set("check", 1)
    ctx.storage.set("completed", True)

    await ctx.send(sender, RegistrationStatus(msg=output_msg))

@currency_protocol.on_interval(period=30, messages=None)
async def interval(ctx: Context):
    check = ctx.storage.get("check") or 0

    if check:

        load_dotenv()

        API_KEY = os.getenv("EXCHANGE_RATE_API_KEY")
        API_URL = f"http://api.exchangeratesapi.io/v1/latest?access_key={API_KEY}"

        number = ctx.storage.get("number")
        message = ""

        base = ctx.storage.get("base")

        foreign = ctx.storage.get("foreign")
        response = requests.get(API_URL + f"&{base}")

        data = response.json()
        min = ctx.storage.get("min")
        max = ctx.storage.get("max")
        rate = data['rates'][foreign]
        print(rate)

        phone_number = "+919737012383"

        WHATSAPP_API = os.getenv("WHATSAPP_API_KEY")
        if rate > max:
            message = f"The rate is {rate} above the limits set!"
            MESSAGE_API = f"https://api.callmebot.com/whatsapp.php?phone={number}&text={message}&apikey={WHATSAPP_API}"

            response = requests.get(MESSAGE_API)
            print(MESSAGE_API)
            print("UPARRR!")

        elif rate < min:
            message = f"The rate is {rate} and it is below the limits set!"
            MESSAGE_API = f"https://api.callmebot.com/whatsapp.php?phone={number}&text={message}&apikey=3367362"

            response = requests.get(MESSAGE_API)
            print("NEECHE")

        else:
            message = "The rate is: {rate} Looks good, nothing's out of range"
            MESSAGE_API = f"https://api.callmebot.com/whatsapp.php?phone={number}&text={message}&apikey=3367362"
            response = requests.get(MESSAGE_API)

            ctx.logger.info(message)


"""
Depth First Search
Time complexity: O(V + E), V - vertices, E - edges
"""
from queue import LifoQueue

class DepthFirstSearch():

    def dfsUsingRecursion(self, graph, vertex, visited = []):
        if vertex not in visited:
            visited.append(vertex)
            for i in graph:
                self.dfsUsingRecursion(graph, i, visited)
        return visited

    def dfsUsingStack(self, graph, vertex):
        stack = LifoQueue()
        stack.put(vertex)
        visited = []
        while not stack.empty():
            node = stack.get()
            #print(node)
            if node not in visited:
                visited.append(node)
            for i in graph[node]:
                #print('i: ',i)
                if i not in visited:
                    stack.put(i)

        return visited

if __name__ == '__main__':
    obj = DepthFirstSearch()
    #graph = {1:[2,3,5],2:[1,4],3:[1,5],4:[2],5:[1,3]}
    #visited = [0] * len(graph)  # length of graph is number of vertices
    graph = {
        'A': ['B', 'S'],
        'B': ['A'],
        'C': ['D', 'E', 'F', 'S'],
        'D': ['C'],
        'E': ['C', 'H'],
        'F': ['C', 'G'],
        'G': ['F', 'S'],
        'H': ['E', 'G'],
        'S': ['A', 'C', 'G']
    }

    print(obj.dfsUsingRecursion(graph,'A'))
    print(obj.dfsUsingStack(graph,'A'))


import pandas as pd
import pickle

QUERY = ('SELECT created_utc, subreddit, domain, url, num_comments, score, title, selftext FROM [fh-bigquery:reddit_posts.2017_12]'
            'WHERE subreddit in ("todayilearned", "politics", "science", "worldnews", "new", \
                    "technology", "KotakuInAction", "movies", "books", "space", "gadgets", \
                    "Games", "Economics", "relationships", "Fitness", "Bitcoin", "lgbt", \
                    "writing", "Android", "PS4", "nyc", "LosAngeles", "toronto") AND selftext <> "[removed]" \
                    AND selftext <> "[deleted]"')
data = pd.read_gbq(QUERY, project_id='graphic-armor-194600')
data = data.loc[(data['score'] >= 10) | (data['num_comments'] >= 10)]
data.to_pickle('/home/wli/dec2017_raw')

data['para_count'] = 0
data['lexical_diversity'] = 0
data['word_count'] = 0
data['reading_time'] = 0
data['img_count'] = 0
data['grade'] = 0
data['word_freq'] = 0
data['descriptive_words'] = 0
data['video_count'] = 0
data['sentiment'] = 0
data['original_title'] = ''
data['title_nchar'] = 0
data['title_nword'] = 0
data['title_sentiment'] = 0
data['linkedin_shares'] = 0
data['score_rank'] = 0
data['num_comments_rank'] = 0

data.to_pickle('/home/wli/dec2017')


# %%
import torch
import torch.nn as nn
from torchvision import transforms

import pandas as pd
import numpy as np

from PIL import Image

from SiameseModels import SiameseNetworkTripletLoss

# %%
model = SiameseNetworkTripletLoss()
model.load_state_dict(torch.load("model_e_4_l_0.1467277131297434.pth"))
# %%
df = pd.read_csv("data/identity_CelebA.csv", sep=",", header=0)
df = df[df["train"] == False]
# %%
transform = transforms.Compose([
                transforms.Resize((224, 224)),
                transforms.ToTensor(),
                transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])
# %%
ids = df.id.sample(10).values
tmp_df = df[df["id"].isin(ids)]
# %%
model = model.eval()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
img_dict = {}

for id in tmp_df.id.unique():
    img_df = tmp_df[tmp_df["id"] == id]
    size = img_df.shape[0]
    for i, image_id in enumerate(img_df.image_id):
        img = Image.open(f"data/img/{image_id}")
        img = transform(img)
        img = img.to(device)
        img = img.unsqueeze(0)
        out = model(img)
        out = out.detach().cpu().numpy()
        l = img_dict.get(id, [])
        l.append(out)
        img_dict[id] = l

# %%
distance_fn = nn.PairwiseDistance()
key_dict = {}
for key in img_dict.keys():
    key_dict[key] = np.mean(img_dict[key][:-2], axis=0)
# %%
for anchor_key in img_dict.keys():
    anchor = img_dict[anchor_key][-1]
    for reference_key in key_dict.keys():

        reference = key_dict[reference_key]

        print(distance_fn(torch.tensor(anchor), torch.tensor(reference)).item(), anchor_key, reference_key)

# %%


class Hamming:
    def __init__(self, n: int, m: int, code: str) -> None:
        self.r = n - m
        self.m = m
        self.n = n

        if not ((m + self.r + 1) <= 2**self.r):
            raise Exception("\n\nla secuencia no cumple la condicion para ser valida: (m + r + 1) <= 2 ** r\n\n")
        else:
            self.code = code

    def get_parities(self):
        self.r = 0
        self.m = len(self.code)

        while (2 ** self.r < self.m + self.r + 1):
            self.r += 1

        self.final_len = self.m + self.r
        return self.r

    def get_by_index(self, index: int, secuence: str):
        val = 0

        for i in range(1, self.final_len + 1):
            if i & index != 0:
                if secuence[i].startswith("p"):
                    continue
                val ^= int(secuence[i])

        return val

    def set_parity_positions(self):
        result = [None for _ in range(self.final_len+1)]
        j = 0

        for i in range(1, self.final_len+1):
            if i == 2**j:
                result[i] = "p" + str(j+1)
                j += 1
            else:
                result[i] = self.code[i-j-1]

        for i in range(self.r):
            index = 2**i
            val = self.get_by_index(index=index, secuence=result)
            result[index] = f"({str(val)})"

        return result

    def encode(self, arr: list[str]):
        encoded = ""
        insides = ""
        for i in range(1, len(arr)):
            if arr[i] is not None:
                encoded += arr[i]
                if arr[i].endswith(")") and arr[i].startswith("("):
                    insides += arr[i][1:-1]

        return (encoded.replace("(", "").replace(")", ""), insides)

    def hamming(self):
        self.get_parities()
        hamming_arr = self.set_parity_positions()
        self.hamming_encoded, self.parities = self.encode(hamming_arr)

    def print_results(self):
        print(f"""Hamming:
            Secuencia ingresada: {self.code}
            Cantidad de bits de paridad: {self.get_parities()}
            Codificacion: {self.hamming_encoded}
            Bits de paridad: {self.parities}
        """)


import customtkinter as ctk
from tkinter.scrolledtext import ScrolledText
from tkinter import filedialog
import speech_recognition as sp

ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")

class SpeechToTextGUI(ctk.CTk):
    def __init__(self):
        super().__init__()

        self.geometry("1920x1080")
        self.title("Speech-to-Text")
        self.font = ("Comic Sans MS", 20, "bold")
        self.font1 = ("Comic Sans MS", 24, "bold")

        label = ctk.CTkLabel(self, text="~~~~~~~~~~~ PRESS THE SPEAK BUTTON TO START TALKING ~~~~~~~~~~~", font=self.font1, text_color="magenta")
        label.pack(padx=10, pady=10)

        self.text_area = ScrolledText(self, font=self.font, width=70, height=20, bg="lavender", wrap="word")
        self.text_area.pack(padx=10, pady=10)

        speak_button = ctk.CTkButton(self, text="Speak", font=self.font, height=60, command=self.recognize_speech)
        speak_button.pack(padx=10, pady=10)

        save_button = ctk.CTkButton(self, text="Save Text", font=self.font, height=60, command=self.save_text)
        save_button.pack(padx=10, pady=10)

        self.recognizer = sp.Recognizer()

    def recognize_speech(self):
        with sp.Microphone() as source:
            self.recognizer.adjust_for_ambient_noise(source)
            audio = self.recognizer.listen(source)

            try:
                recognized_text = self.recognizer.recognize_google(audio)
                if self.text_area.get("1.0", ctk.END).strip() == "":
                    recognized_text = recognized_text.capitalize()
                else:
                    last_char = self.text_area.get("end-2c", ctk.END).strip()
                    if last_char == "." or last_char == "?":
                        recognized_text = recognized_text.capitalize()
                    else:
                        recognized_text = recognized_text.lower()
                    recognized_text = " " + recognized_text

                self.text_area.insert(ctk.END, recognized_text)
                self.text_area.see(ctk.END)
            except Exception as e:
                print('Error : ' + str(e))

    def save_text(self):
        filename = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", "*.txt")])
        if filename:
            with open(filename, "w") as f:
                f.write(self.text_area.get("1.0", ctk.END))

if __name__ == '__main__':
    app = SpeechToTextGUI()
    app.mainloop()


import collections
from functools import lru_cache
import math
import os
import argparse
import cv2
import numpy as np
import av

class RectificationException(Exception):
    pass

default_args = dict(
    width=1920,
    height=1080,
    resize_factor=1,
    make_dimensions_divisible_by=8,
    calibration_frame_idx_dist=30,
    autoexposure_frames=90,
    recalibrate=True,
    recalibrate_iterative=True,
    use_deepmatching=False,
    use_cotr=True,
    show_matches=False,
    show_rectification=False,
    save_rectification=False,
    draw_epipolar_lines=False,
    grayscale=True,
    denoise=False,
    denoise_num_frames=5,
    denoise_noise_std=5,
    output_calibration_file=None,
    invert=False,
)

def rectify(**args):
    args = {**default_args, **args}
    input_file = args["input_file"]
    image_size = (args["width"], args["height"])
    resize_factor = args["resize_factor"]
    make_dimensions_divisible_by = args["make_dimensions_divisible_by"]
    calibration_frame_idx_dist = args["calibration_frame_idx_dist"]
    autoexposure_frames = args["autoexposure_frames"]
    recalibrate = args["recalibrate"]
    recalibrate_iterative = args["recalibrate"] and args["recalibrate_iterative"]
    use_deepmatching = args["use_deepmatching"]
    use_cotr = args["use_cotr"]
    show_matches = args["show_matches"]
    show_rectification = args["show_rectification"]
    draw_epipolar_lines = args["draw_epipolar_lines"]
    grayscale = args["grayscale"]
    denoise = args["denoise"]
    denoise_num_frames = args["denoise_num_frames"]
    denoise_noise_std = args["denoise_noise_std"]
    output_calibration_file = args["output_calibration_file"]
    invert = args["invert"]

    assert not (use_deepmatching and use_cotr)

    if autoexposure_frames < denoise_num_frames:
        raise ValueError("argument autoexposure_frames must be greater or equal to denoise_num_frames")

    if not use_deepmatching:
        sift = cv2.SIFT_create()
        flann = cv2.FlannBasedMatcher({"algorithm": 1, "trees": 5}, {"checks": 50})

    init_cam_mats_left = np.array([
        [1998.548313762794, 0.00000000e+00, 899.1958547906069],
        [0.00000000e+00, 1995.552255534815, 598.8278928199517],
        [0.00000000e+00, 0.00000000e+00, 1],
    ])
    init_cam_mats_right = np.array([
        [2007.1648145600445, 0.00000000e+00, 859.7953980050097],
        [0.00000000e+00, 2009.1782660647034, 613.4969001852309],
        [0.00000000e+00, 0.00000000e+00, 1],
    ])

    init_dist_coefs_left =  np.array([-0.4595421970863985, 0.2019752346541169, -0.0019327353310391964, 0.001957806937187838])
    init_dist_coefs_right = np.array([-0.473438679479971, 0.1967383195268051, -0.0032260744184233843, 0.005053066550145099])

    init_rot_mat = np.array([
        [ 0.99982747,  0.00547327,  0.01775028, -0.25437443 ],
        [-0.00613865,  0.99927213,  0.03765017,  0.0070481  ],
        [-0.01753129, -0.03775264,  0.99913332,  -0.01743795],
        [ 0.        ,  0.        ,  0.        ,  1.        ],
    ])

    init_rot_mat = np.array([
        [0.9997373615098061, 0.004595532919614159, 0.022451928170746975, -0.2509914052172423],
        [-0.005437145244579489, 0.9992792439499563, 0.037569004011037285, 0.003944074622135025],
        [-0.022263096212993057, -0.03768121133903117, 0.9990417813380091, 0.017989804386538424],
        [0.0, 0.0, 0.0, 1.0],
    ])

    init_trans_vec = init_rot_mat[:-1, -1]
    init_rot_mat = init_rot_mat[:-1, :-1]

    if recalibrate_iterative:
        rect_trans_left, rect_trans_right, proj_mats_left, proj_mats_right, disp_to_depth, valid_boxes_left, valid_boxes_right = cv2.stereoRectify(
            init_cam_mats_left,
            init_dist_coefs_left,
            init_cam_mats_right,
            init_dist_coefs_right,
            image_size,
            init_rot_mat,
            init_trans_vec,
            flags=0
        )

        undistort_map_left, rectify_map_left = cv2.initUndistortRectifyMap(
            init_cam_mats_left,
            init_dist_coefs_left,
            rect_trans_left,
            proj_mats_left,
            image_size,
            cv2.CV_32FC1
        )

        undistort_map_right, rectify_map_right = cv2.initUndistortRectifyMap(
            init_cam_mats_right,
            init_dist_coefs_right,
            rect_trans_right,
            proj_mats_right,
            image_size,
            cv2.CV_32FC1
        )

        min_x = max(valid_boxes_left[0], valid_boxes_right[0])
        min_y = max(valid_boxes_left[1], valid_boxes_right[1])
        max_x = min(valid_boxes_left[2], valid_boxes_right[2])
        max_y = min(valid_boxes_left[3], valid_boxes_right[3])
        valid_width = max_x - min_x
        valid_height = max_y - min_y

        if valid_width < image_size[0] / 2 or valid_height < image_size[1] / 2:
            raise RectificationException()

    if denoise:
        frame_buffer_left = collections.deque(maxlen=denoise_num_frames)
        frame_buffer_right = collections.deque(maxlen=denoise_num_frames)

        import torch
        from fastdvdnet.fastdvdnet import denoise_seq_fastdvdnet_custom
        from fastdvdnet.models import FastDVDnet

        fastdvdnet_device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        fastdvdnet_model = FastDVDnet(num_input_frames=denoise_num_frames)
        if torch.cuda.is_available():
            fastdvdnet_model = torch.nn.DataParallel(fastdvdnet_model, device_ids=[0]).cuda()
        else:
            raise RuntimeError("not implemented")
        fastdvdnet_model.load_state_dict(torch.load(os.path.join("fastdvdnet", "model.pth"), map_location=fastdvdnet_device))
        fastdvdnet_model.eval()

    def denoise_frame(left, right):
        if not denoise:
            return left, right

        for frame, frame_buffer in [(left, frame_buffer_left), (right, frame_buffer_right)]:
            frame_buffer.append(frame.transpose(2, 0, 1).astype(np.float32) / 255)

        if len(frame_buffer_left) < denoise_num_frames:
            return left, right

        with torch.no_grad():
            left = denoise_seq_fastdvdnet_custom(frame_buffer_left, denoise_noise_std / 255, fastdvdnet_model, fastdvdnet_device)
            right = denoise_seq_fastdvdnet_custom(frame_buffer_right, denoise_noise_std / 255, fastdvdnet_model, fastdvdnet_device)

        return left, right

    if recalibrate:
        container = av.open(input_file)
        pts1 = []
        pts2 = []
        for frame_i, frame in enumerate(container.decode(video=0)):

            array = frame.to_ndarray(format="rgb24")
            left = array[:, : array.shape[1] // 2, :]
            right = array[:, array.shape[1] // 2 :, :]
            if invert:
                left, right = right, left
            if resize_factor != 1:
                left = cv2.resize(left, dsize=None, fx=resize_factor, fy=resize_factor, interpolation=cv2.INTER_AREA)
                right = cv2.resize(right, dsize=None, fx=resize_factor, fy=resize_factor, interpolation=cv2.INTER_AREA)
            if left.shape[0:2] != image_size[::-1] or right.shape[0:2] != image_size[::-1]:
                raise RectificationException()

            left, right = denoise_frame(left, right)

            if frame_i < autoexposure_frames or frame_i % calibration_frame_idx_dist != 0:
                continue

            if recalibrate_iterative:
                left = cv2.remap(left, undistort_map_left, rectify_map_left, cv2.INTER_CUBIC)
                right = cv2.remap(right, undistort_map_right, rectify_map_right, cv2.INTER_CUBIC)

            if use_deepmatching:
                from deepmatching_utils import deepmatching
                pts1, pts2, dm_score, dm_idx = deepmatching(
                    cv2.cvtColor(left, cv2.COLOR_RGB2GRAY),
                    cv2.cvtColor(right, cv2.COLOR_RGB2GRAY),
                    resize_factor=1/2,
                )
                if show_matches:
                    show_correspondences(left, right, np.stack([pts1[:, 0], pts1[:, 1], pts2[:, 0], pts2[:, 1], dm_score, dm_idx], axis=0).transpose(1, 0))
                break
            elif use_cotr:
                from cotr_utils import get_cotr
                pts1, pts2 = get_cotr()(left, right)
                if show_matches:
                    from deepmatching_utils import show_correspondences
                    show_correspondences(left, right, np.stack([pts1[:, 0], pts1[:, 1], pts2[:, 0], pts2[:, 1], dm_score, dm_idx], axis=0).transpose(1, 0))
                break
            else:
                kp1, desc1 = sift.detectAndCompute(cv2.cvtColor(left, cv2.COLOR_RGB2GRAY), None)
                kp2, desc2 = sift.detectAndCompute(cv2.cvtColor(right, cv2.COLOR_RGB2GRAY), None)

                if desc1 is None or desc2 is None:
                    continue

                def match_is_valid(kp1, kp2, m, max_y_deviation=100, p=10):
                    (x1, y1) = kp1[m.queryIdx].pt
                    (x2, y2) = kp2[m.trainIdx].pt

                    return (
                        abs(y1 - y2) <= max_y_deviation and
                        x1 >= x2 and
                        (
                            not recalibrate_iterative or (
                                min_x + p < x1 < max_x - p and
                                min_x + p < x2 < max_x - p and
                                min_y + p < y1 < max_y - p and
                                min_y + p < y2 < max_y - p
                            )
                        )
                    )

                matches = flann.knnMatch(desc1, desc2, k=2)
                matchesMask = [[0,0] for i in range(len(matches))]
                for i, (m1, m2) in enumerate(matches):
                    if m1.distance < 0.7 * m2.distance and match_is_valid(kp1, kp2, m1):
                        matchesMask[i] = [1,0]
                        pt1 = kp1[m1.queryIdx].pt
                        pt2 = kp2[m1.trainIdx].pt
                        pts1.append(pt1)
                        pts2.append(pt2)

                if show_matches:
                    vis = cv2.drawMatchesKnn(left,kp1,right,kp2,matches,None, matchColor=(255, 0, 0), singlePointColor=(0,0,255), matchesMask=matchesMask, flags=0)
                    cv2.imshow("Matches", vis)
                    cv2.waitKey(1000//10)

        container.close()

        if len(pts1) < 8:
            raise RectificationException()

        _pts1 = np.array(pts1, dtype=np.float32)
        _pts2 = np.array(pts2, dtype=np.float32)

        f = np.mean([init_cam_mats_left[0, 0], init_cam_mats_left[1, 1], init_cam_mats_right[0, 0], init_cam_mats_right[1, 1]])
        if recalibrate_iterative:
            px = image_size[0] / 2
            py = image_size[1] / 2
            cam_mats_simple = np.array([
                [f, 0, px],
                [0, f, py],
                [0, 0, 1],
            ])
        else:
            px = np.mean([init_cam_mats_left[0, 2], init_cam_mats_right[0, 2]])
            py = np.mean([init_cam_mats_left[1, 2], init_cam_mats_right[1, 2]])
            cam_mats_simple = np.mean([init_cam_mats_left, init_cam_mats_right], axis=0)
        E, _ = cv2.findEssentialMat(_pts1,_pts2, f, (px, py), method=cv2.FM_RANSAC)
        _, R, t, _ = cv2.recoverPose(E, _pts1, _pts2, cam_mats_simple)
        t = t * init_trans_vec[0] / t[0]

        trans_vec = t

    if recalibrate and recalibrate_iterative:
        rot_mat = R @ init_rot_mat
        cam_mats_left = init_cam_mats_left
        cam_mats_right = init_cam_mats_right
    else:
        rot_mat = init_rot_mat
        trans_vec = init_trans_vec
        cam_mats_left = init_cam_mats_left if not recalibrate or recalibrate_iterative else cam_mats_simple
        cam_mats_right = init_cam_mats_right if not recalibrate or recalibrate_iterative else cam_mats_simple

    rect_trans_left, rect_trans_right, proj_mats_left, proj_mats_right, disp_to_depth, valid_boxes_left, valid_boxes_right = cv2.stereoRectify(
        cam_mats_left,
        init_dist_coefs_left,
        cam_mats_right,
        init_dist_coefs_right,
        image_size,
        rot_mat,
        trans_vec,
        flags=0
    )

    undistort_map_left, rectify_map_left = cv2.initUndistortRectifyMap(
        cam_mats_left,
        init_dist_coefs_left,
        rect_trans_left,
        proj_mats_left,
        image_size,
        cv2.CV_32FC1
    )

    undistort_map_right, rectify_map_right = cv2.initUndistortRectifyMap(
        cam_mats_right,
        init_dist_coefs_right,
        rect_trans_right,
        proj_mats_right,
        image_size,
        cv2.CV_32FC1
    )

    min_x = max(valid_boxes_left[0], valid_boxes_right[0])
    min_y = max(valid_boxes_left[1], valid_boxes_right[1])
    max_x = min(valid_boxes_left[2], valid_boxes_right[2])
    max_y = min(valid_boxes_left[3], valid_boxes_right[3])

    crop_width = (max_x - min_x) % make_dimensions_divisible_by
    crop_height = (max_y - min_y) % make_dimensions_divisible_by

    min_x += math.floor(crop_width / 2)
    max_x -= math.ceil(crop_width / 2)
    min_y += math.floor(crop_height / 2)
    max_y -= math.ceil(crop_height / 2)

    valid_width = max_x - min_x
    valid_height = max_y - min_y

    if valid_width < image_size[0] / 2 or valid_height < image_size[1] / 2:
        raise RectificationException()

    if output_calibration_file is not None:
        np.savez(
            output_calibration_file,

            rot_mat=rot_mat,
            init_rot_mat=init_rot_mat,
            trans_vec=trans_vec,
            init_trans_vec=init_trans_vec,
            cam_mats_left=cam_mats_left,
            init_cam_mats_left=init_cam_mats_left,
            cam_mats_right=cam_mats_right,
            init_cam_mats_right=init_cam_mats_right,
            undistort_map_left=undistort_map_left,
            rectify_map_left=rectify_map_left,
            undistort_map_right=undistort_map_right,
            rectify_map_right=rectify_map_right,
            init_dist_coefs_left=init_dist_coefs_left,
            init_dist_coefs_right=init_dist_coefs_right,
            image_size=image_size,
            disp_to_depth=disp_to_depth,
            valid_boxes_left=valid_boxes_left,
            valid_boxes_right=valid_boxes_right,
            min_x=min_x,
            max_x=max_x,
            min_y=min_y,
            max_y=max_y,
        )

    container = av.open(input_file)
    for frame_i, frame in enumerate(container.decode(video=0)):

        array = frame.to_ndarray(format="rgb24")
        left = array[:, : array.shape[1] // 2, :]
        right = array[:, array.shape[1] // 2 :, :]
        if invert:
            left, right = right, left
        if resize_factor != 1:
            left = cv2.resize(left, dsize=None, fx=resize_factor, fy=resize_factor, interpolation=cv2.INTER_AREA)
            right = cv2.resize(right, dsize=None, fx=resize_factor, fy=resize_factor, interpolation=cv2.INTER_AREA)
        if left.shape[0:2] != image_size[::-1] or right.shape[0:2] != image_size[::-1]:
            raise RectificationException()

        left, right = denoise_frame(left, right)

        if frame_i < autoexposure_frames:
            continue

        if grayscale:
            left = cv2.cvtColor(left, cv2.COLOR_RGB2GRAY)
            right = cv2.cvtColor(right, cv2.COLOR_RGB2GRAY)

        left = cv2.remap(left, undistort_map_left, rectify_map_left, cv2.INTER_CUBIC)
        left = left[min_y:max_y, min_x:max_x]

        right = cv2.remap(right, undistort_map_right, rectify_map_right, cv2.INTER_CUBIC)
        right = right[min_y:max_y, min_x:max_x]

        if draw_epipolar_lines:
            for image in [left, right]:
                for y in np.linspace(0, left.shape[0], 20):
                    cv2.line(image, (0, int(y)), (left.shape[1], int(y)), (0, 255, 0), thickness=2)

        if show_rectification:
            cv2.imshow("Rectified", np.hstack([left, right]))
            cv2.waitKey(1000//30)

        yield (frame_i, left, right)

    container.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Rectify stereo image sequences from CSI cameras")
    parser.add_argument("--width", type=int, help="original (single image) width")
    parser.add_argument("--height", type=int, help="original (single image) height")
    parser.add_argument("--resize_factor", type=float, help="resize factor at which the original calibration was performed")
    parser.add_argument("--make_dimensions_divisible_by", type=int, help="make output dimensions divisible by this constant (needed for some video codecs")
    parser.add_argument("--calibration_frame_idx_dist", type=int, help="interval at which to take iterative recalibration frames")
    parser.add_argument("--autoexposure_frames", type=int, help="number of frames to skip due to autoexposure")
    parser.add_argument("--recalibrate", dest="recalibrate", action="store_true")
    parser.add_argument("--no-recalibrate", dest="recalibrate", action="store_false")
    parser.add_argument("--recalibrate_iterative", dest="recalibrate_iterative", action="store_true")
    parser.add_argument("--no-recalibrate_iterative", dest="recalibrate_iterative", action="store_false")
    parser.add_argument("--use_deepmatching", dest="use_deepmatching", action="store_true")
    parser.add_argument("--no-use_deepmatching", dest="use_deepmatching", action="store_false")
    parser.add_argument("--use_cotr", dest="use_cotr", action="store_true")
    parser.add_argument("--no-use_cotr", dest="use_cotr", action="store_false")
    parser.add_argument("--show_matches", dest="show_matches", action="store_true")
    parser.add_argument("--no-show_matches", dest="show_matches", action="store_false")
    parser.add_argument("--show_rectification", dest="show_rectification", action="store_true")
    parser.add_argument("--no-show_rectification", dest="show_rectification", action="store_false")
    parser.add_argument("--save_rectification", dest="save_rectification", action="store_true")
    parser.add_argument("--no-save_rectification", dest="save_rectification", action="store_false")
    parser.add_argument("--draw_epipolar_lines", dest="draw_epipolar_lines", action="store_true")
    parser.add_argument("--no-draw_epipolar_lines", dest="draw_epipolar_lines", action="store_false")
    parser.add_argument("--grayscale", dest="grayscale", action="store_true")
    parser.add_argument("--no-grayscale", dest="grayscale", action="store_false")
    parser.add_argument("--denoise", dest="denoise", action="store_true")
    parser.add_argument("--no-denoise", dest="denoise", action="store_false")
    parser.add_argument("--denoise_num_frames", type=int, help="number of frames to use at once for denoising")
    parser.add_argument("--denoise_noise_std", type=int, help="standard deviation of expeced noise")
    parser.add_argument("--output_calibration_file", type=str, help="write calibration parameters to this .npz file")
    parser.add_argument("input_file", type=str, help="input mkv file")
    parser.add_argument("output_dir", type=str, help="output directory containing left and right subdirectories")
    parser.add_argument("--invert", dest="invert", action="store_true")
    parser.add_argument("--no-invert", dest="invert", action="store_false")
    parser.set_defaults(**default_args)
    args = parser.parse_args()

    if args.save_rectification:
        os.makedirs(args.output_dir, exist_ok=True)
        os.makedirs(os.path.join(args.output_dir, "left"), exist_ok=True)
        os.makedirs(os.path.join(args.output_dir, "right"), exist_ok=True)

    for frame_i, (left, right) in enumerate(rectify(**vars(args))):
        if args.save_rectification:
            cv2.imwrite(os.path.join(args.output_dir, "left", f"{frame_i:06d}.png"), left)
            cv2.imwrite(os.path.join(args.output_dir, "right", f"{frame_i:06d}.png"), right)


import random
import pylab

# Global Variables
MAXRABBITPOP = 1000
CURRENTRABBITPOP = 500
CURRENTFOXPOP = 30

def rabbitGrowth():
    """
    rabbitGrowth is called once at the beginning of each time step.

    It makes use of the global variables: CURRENTRABBITPOP and MAXRABBITPOP.

    The global variable CURRENTRABBITPOP is modified by this procedure.

    For each rabbit, based on the probabilities in the problem set write-up,
      a new rabbit may be born.
    Nothing is returned.
    """
    # you need this line for modifying global variables
    global CURRENTRABBITPOP
    currentRabbitPopCopy = CURRENTRABBITPOP

    for rabbit in range(currentRabbitPopCopy):
        if 10 < CURRENTRABBITPOP < MAXRABBITPOP:
            reproduce = random.random()
            if reproduce <= (1 - CURRENTRABBITPOP/MAXRABBITPOP):
                CURRENTRABBITPOP += 1

def foxGrowth():
    """
    foxGrowth is called once at the end of each time step.

    It makes use of the global variables: CURRENTFOXPOP and CURRENTRABBITPOP,
        and both may be modified by this procedure.

    Each fox, based on the probabilities in the problem statement, may eat
      one rabbit (but only if there are more than 10 rabbits).

    If it eats a rabbit, then with a 1/3 prob it gives birth to a new fox.

    If it does not eat a rabbit, then with a 1/10 prob it dies.

    Nothing is returned.
    """
    # you need these lines for modifying global variables
    global CURRENTRABBITPOP
    global CURRENTFOXPOP

    currentFoxPopCopy = CURRENTFOXPOP

    for fox in range(currentFoxPopCopy):
        if 10 < CURRENTRABBITPOP:
            eatRabbitPop = random.random()
            if eatRabbitPop <= CURRENTRABBITPOP/MAXRABBITPOP:
                CURRENTRABBITPOP -= 1
                reproducePop = random.random()
                if reproducePop <= 1/3:
                    CURRENTFOXPOP += 1
            foxDiePop = random.random()
            if foxDiePop <= 0.1:
                CURRENTFOXPOP -= 1

def runSimulation(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """
    rabbit_populations = []
    fox_populations = []
    for step in range(numSteps):
        rabbitGrowth()
        foxGrowth()
        rabbit_populations.append(CURRENTRABBITPOP)
        fox_populations.append(CURRENTFOXPOP)

    return rabbit_populations, fox_populations

if __name__ == '__main__':
    rabbitPops, foxPops = runSimulation(200)
    timeSteps = []
    for i in range(200):
        timeSteps.append(i)

    pylab.plot(timeSteps, rabbitPops)
    pylab.plot(timeSteps, foxPops)
    pylab.title('rabbit and fox simulation')
    pylab.xlabel('Time step')
    pylab.ylabel('# of animal')

    rabbitModel = pylab.polyfit(timeSteps, rabbitPops, 2)
    estRabbitPops = pylab.polyval(rabbitModel, timeSteps)
    pylab.plot(timeSteps, estRabbitPops, label='rabbit pops 2nd order poly fit')
    foxModel = pylab.polyfit(timeSteps, foxPops, 2)
    estFoxPops = pylab.polyval(foxModel, timeSteps)
    pylab.plot(timeSteps, estFoxPops, label='fox pops 2nd order poly fit')

    pylab.show()


from turtle import Turtle, Screen

timmy = Turtle()
print(timmy)

# Giving timmy a shape of turtle, i.e calling its method shape
timmy.shape("arrow")

# Giving color to obj timmy
timmy.color("blue")

# Move timmy

for _ in range(15):
    timmy.forward(10)
    timmy.penup()
    timmy.forward(10)
    timmy.pendown()

# Making obj of Screen to fit the turtle
my_screen = Screen()

# on clicking anywhere the screen should be exited, i.e calling a method exitonclick() of Screen class
my_screen.exitonclick()


import random
import streamlit as st

# Create a deck of cards
deck = []

# Define a function to create a new deck
def new_deck():
    global deck
    deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] * 24
    random.shuffle(deck)

# Define a function to calculate the value of a hand
def calculate_hand(hand):
    value = 0
    aces = 0
    for card in hand:
        if card == 'A':
            aces += 1
        elif card in ['K', 'Q', 'J']:
            value += 10
        else:
            value += card
    for i in range(aces):
        if value + 11 <= 21:
            value += 11
        else:
            value += 1
    return value

# Define a function to play the dealer's turn
def dealer_turn(dealer_hand):
    while calculate_hand(dealer_hand) < 17:
        dealer_hand.append(deck.pop())

# Helper function to get the value of a card
def get_card_value(card):
    if card in ["J", "Q", "K"]:
        return 10
    elif card == "A":
        return 11
    else:
        return int(card)

# Helper function to get the value of a hand
def get_hand_value(hand):
    value = sum(get_card_value(card) for card in hand)
    if value > 21 and "A" in hand:
        value -= 10
    return value

# Define a function to simulate the player's decision using basic strategy
def blackjack_strategy(player_hand, dealer_card):
    """
    Implements a perfect blackjack strategy based on the player's hand and the dealer's up card.
    Args:
    - player_hand: a list of strings representing the player's hand, e.g. ["A", "5"]
    - dealer_card: a string representing the dealer's up card, e.g. "10"
    Returns:
    - A string representing the recommended action, one of "stand", "hit", "split", "double", or "surrender"
    """

    # Helper functions to check if the player's hand is a soft hand or a pair
    def is_soft_hand(hand):
        return any(card == "A" for card in hand) and sum(get_card_value(card) for card in hand) <= 11

    def is_pair(hand):
        return len(hand) == 2 and hand[0] == hand[1]

    # Helper function to check if a hand can be doubled
    def can_double(hand):
        return len(hand) == 2

    # Helper function to check if a hand can be split
    def can_split(hand):
        return len(hand) == 2 and hand[0] == hand[1]

    # Implement the rules for surrender
    if len(player_hand) == 2 and is_soft_hand(player_hand):
        if get_hand_value(player_hand) == 15 and dealer_card in ["10", "J", "Q", "K"]:
            return "surrender"
        elif get_hand_value(player_hand) == 16 and dealer_card in ["9", "10", "J", "Q", "K", "A"]:
            return "surrender"

    # Implement the rules for pairs
    if can_split(player_hand):
        if player_hand[0] == "A":
            return "split"
        elif player_hand[0] == "8":
            return "split"
        elif player_hand[0] == "7" and dealer_card in ["2", "3", "4", "5", "6", "7"]:
            return "split"
        elif player_hand[0] == "6" and dealer_card in ["2", "3", "4", "5", "6"]:
            return "split"
        elif player_hand[0] == "5" and dealer_card in ["2", "3", "4", "5", "6", "7", "8", "9"]:
            return "double"
        elif player_hand[0] == "4" and dealer_card in ["5", "6"]:
            return "split"
        elif player_hand[0] == "3" and dealer_card in ["2", "3", "4", "5", "6", "7"]:
            return "split"
        elif player_hand[0] == "2" and dealer_card in ["2", "3", "4", "5", "6", "7"]:
            return "split"
        elif player_hand[0] == "9" and dealer_card in ["2", "3", "4", "5", "6", "8", "9"]:
            return "stand"

    # Implement the rules for soft hands
    if is_soft_hand(player_hand):
        if get_hand_value(player_hand) == 20:
            return "stand"
        elif get_hand_value(player_hand) == 19 and dealer_card == "6":
            return "double"
        elif get_hand_value(player_hand) == 19 and dealer_card != "6":
            return "stand"
        elif get_hand_value(player_hand) == 18 and dealer_card in ["2", "3", "4", "5", "6"]:
            return "double"
        elif get_hand_value(player_hand) == 18 and dealer_card in ["9", "10", "J", "Q", "K", "A"]:
            return "hit"
        elif get_hand_value(player_hand) == 18 and dealer_card in ["7", "8"]:
            return "stand"
        elif get_hand_value(player_hand) == 17 and dealer_card in ["3", "4", "5", "6"]:
            return "double"
        elif get_hand_value(player_hand) == 16 and dealer_card in ["4", "5", "6"]:
            return "double"
        elif get_hand_value(player_hand) == 15 and dealer_card in ["4", "5", "6"]:
            return "double"
        elif get_hand_value(player_hand) == 14 and dealer_card in ["5", "6"]:
            return "double"
        elif get_hand_value(player_hand) == 13 and dealer_card in ["5", "6"]:
            return "double"
        else:
            return "hit"

    # Implement the rules for hard hands
    if get_hand_value(player_hand) >= 17:
        return "stand"
    elif get_hand_value(player_hand) == 16 and dealer_card in ["2", "3", "4", "5", "6"]:
        return "stand"
    elif get_hand_value(player_hand) == 15 and dealer_card in ["2", "3", "4", "5", "6"]:
        return "stand"
    elif get_hand_value(player_hand) == 14 and dealer_card in ["2", "3", "4", "5", "6"]:
        return "stand"
    elif get_hand_value(player_hand) == 13 and dealer_card in ["2", "3", "4", "5", "6"]:
        return "stand"
    elif get_hand_value(player_hand) == 12 and dealer_card in ["4", "5", "6"]:
        return "stand"
    elif get_hand_value(player_hand) == 11:
        if can_double(player_hand):
            return "double"
        else:
            return "hit"
    elif get_hand_value(player_hand) == 10:
        if can_double(player_hand) and dealer_card in ["2", "3", "4", "5", "6", "7", "8", "9"]:
            return "double"
        else:
            return "hit"
    elif get_hand_value(player_hand) == 9:
        if can_double(player_hand) and dealer_card in ["3", "4", "5", "6"]:
            return "double"
        else:
            return "hit"
    else:
        return "hit"

# Define a function to play a game of blackjack
def play_blackjack(num_hands, bet_amount, min_win_amount, max_loss_amount):
    """
    Plays multiple hands of blackjack using a perfect strategy and returns the total winnings.
    Args:
    - num_hands: an integer representing the number of hands to play
    - bet_amount: an integer representing the amount to bet on each hand
    - min_win_amount: an integer representing the minimum amount to win before stopping
    - max_loss_amount: an integer representing the maximum amount to lose before stopping
    Returns:
    - An integer representing the total winnings or losses
    """

    # Create a deck of cards (hardcoded in a 6 deck shuffle)
    deck = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] * 24

    # Helper function to shuffle the deck
    def shuffle_deck(deck):
        random.shuffle(deck)

    # Helper function to deal a card
    def deal_card(deck):
        return deck.pop()

    # Helper function to calculate the winnings or losses from a single hand
    def calculate_hand_winnings(player_hand, dealer_hand, bet_amount):
        player_hand_value = get_hand_value(player_hand)
        dealer_hand_value = get_hand_value(dealer_hand)
        st.write(f"player hand value: {player_hand_value}")
        st.write(f"dealer hand value: {dealer_hand_value}")
        if player_hand_value > 21:
            st.write(f"player busted, should lose: {bet_amount}")
            return -bet_amount
        elif dealer_hand_value > 21 or player_hand_value > dealer_hand_value or (player_hand_value == 21 and len(player_hand) == 2 and dealer_hand_value != 21):
            if player_hand_value == 21 and len(player_hand) == 2:
                return int(1.5 * bet_amount)
            else:
                return bet_amount
        elif player_hand_value == dealer_hand_value:
            return 0
        else:
            return -bet_amount

    # Play multiple hands of blackjack
    total_winnings = 0
    num_hands_played = 0
    shuffle_deck(deck)
    while num_hands_played < num_hands and total_winnings >= -max_loss_amount and total_winnings <= min_win_amount:
        # Shuffle the deck (hardcoded in a 6 deck shuffle)
        if len(deck) < 6 * 52 / 4:
            shuffle_deck(deck)

        # Deal the player's and dealer's initial hands
        player_hand = [deal_card(deck), deal_card(deck)]
        dealer_hand = [deal_card(deck), deal_card(deck)]

        # Play the player's hand
        while True:
            action = blackjack_strategy(player_hand, dealer_hand[0])
            st.write(f"action: {action}")
            if action == "hit":
                player_hand.append(deal_card(deck))
            elif action == "stand":
                st.write(f"player hand: {player_hand}")
                break
            elif action == "double":
                player_hand.append(deal_card(deck))
                bet_amount *= 2
                st.write(f"player hand: {player_hand}")
                break
            elif action == "split":
                hand1 = [player_hand[0], deal_card(deck)]
                hand2 = [player_hand[1], deal_card(deck)]
                winnings1 = calculate_hand_winnings(hand1, dealer_hand, bet_amount)
                winnings2 = calculate_hand_winnings(hand2, dealer_hand, bet_amount)
                total_winnings += winnings1 + winnings2
                num_hands_played += 2
                st.write(f"player hand if split: {hand1}, {hand2}")
                break
            elif action == "surrender":
                bet_amount -= 0.5 * bet_amount
                num_hands_played += 1
                st.write(f"player hand: {player_hand}")
                break

            if get_hand_value(player_hand) > 21:
                # total_winnings -= bet_amount
                num_hands_played += 1
                st.write(f"player hand: {player_hand}")
                break

        # Play the dealer's hand
        while get_hand_value(dealer_hand) < 17:
            dealer_hand.append(deal_card(deck))
        st.write(f"dealer hand: {dealer_hand}")

        # Calculate the winnings or losses from the hand
        if action != "split":
            winnings = calculate_hand_winnings(player_hand, dealer_hand, bet_amount)
        st.write(f"Hand result: {winnings}")
        st.write(f"Total before last hand: {total_winnings}")
        total_winnings += winnings
        st.write(f"Total: {total_winnings}")
        num_hands_played += 1
        #reset the bet amount if it was lowered for a surrender, before playing next hand
        bet_amount = bet_slider

    # Return the total winnings or losses
    st.write(f"Winnings: {total_winnings}")
    total_winnings = 0

# Set up the Streamlit app
st.title("Blackjack Simulator")
num_hands_slider = st.slider("How many hands do you want to play?", min_value=100, max_value=3000, value=200, step=50)
bet_slider = st.slider ("How much do you want to bet per hand?", min_value=10, max_value=100, value=20, step=5)
min_win_slider = st.slider ("How much do you need to win to stop?", min_value=10, max_value=500, value=100, step=5)
max_loss_slider = st.slider ("How much do you need to lose to stop?", min_value=100, max_value=500, value=200, step=50)
button = st.button("Play")

if button:
    # Play the specified number of games of blackjack
    wins = 0
    losses = 0
    pushes = 0
    result = play_blackjack(num_hands=num_hands_slider, bet_amount=bet_slider, min_win_amount=min_win_slider, max_loss_amount=max_loss_slider)

   # for i in range(num_hands):
    #    result = play_blackjack(num_decks=6, num_hands=num_hands, can_double=True, can_surrender=True)
     #   if result == 'win':
      #      wins += 1
       # elif result == 'loss':
        #    losses += 1
       # else:
        #    pushes += 1

    # Output the results
    # st.write(f"Wins: {wins}")
    # st.write(f"Losses: {losses}")
    # st.write(f"Pushes: {pushes}")


import asyncio
import json
import os

from datetime import datetime

from azure.iot.device.aio import IoTHubDeviceClient

from . import AbstractDeviceHandler

CONNECTION_STRING = os.environ.get('AZURE_CONNECTION_STRING')

class AzureDeviceHandler(AbstractDeviceHandler):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.cl = IoTHubDeviceClient. \
            create_from_connection_string(CONNECTION_STRING)
        self.cl.on_message_received = self.__class__.message_handler

    @staticmethod
    def message_handler(msg):
        if msg.custom_properties.get('RESTART'):
            print('Received a restart signal...')
            AzureDeviceHandler.get_instance().restart = True

    async def connect(self):
        print('Connecting to Azure IoT...')
        await self.cl.connect()

    async def disconnect(self):
        print('Disconnecting from Azure IoT...')
        await self.cl.shutdown()

    def get_is_connected(self):
        return self.cl.connected

    def get_update_info(self):
        return self.config.get('checkout')

    async def fetch_config_data(self):
        self.config = self.config or {}

        data = await self.cl.get_twin()
        conf = dict(self.config)

        self.config.update(data.get('desired'))

        if conf != self.config:
            self.is_config_updated = True

    async def push_config_data(self, data):
        data = json.loads(json.dumps(data))
        await self.cl.patch_twin_reported_properties(data)


def ofb(word):
    list_of_letters = list(word)
    xs = [] #list of decimal plaintexts
    for i in list_of_letters:
        dec = ord(i)
        xs.append(dec)

    #Affine Encryption with OFB mode
    iv = int("0XAA", 16) #in decimal
    key = int("0X08", 16)
    ss = []
    ys = []
    s0 = (key + 11 * iv) % 256
    y0 = hex(xs[0] & s0)
    ss.append(s0)
    ys.append(y0)

    for i in range(1, len(xs)):
        si = (key + 11 * ss[i - 1]) % 256
        ss.append(si)
        yi = hex(xs[i] ^ ss[i])
        ys.append(yi)
    return xs, ys

def main():
    word_ofb = "smocks"
    xs_ofb, ys_ofb = ofb(word_ofb)

    print("\nOFB plaintext", xs_ofb)
    print("OFB Mode ciphertext in hex =", ys_ofb)

main()


import json
import asyncio
from functools import partial
from typing import Optional, Sequence

from prompt_toolkit.application import Application
from prompt_toolkit.layout.dimension import D
from prompt_toolkit.formatted_text import AnyFormattedText
from prompt_toolkit.layout.containers import HSplit, VSplit
from prompt_toolkit.widgets import Button, Dialog, Label

from cli import config_cli
from utils.static import DialogResult, cli_style
from utils.utils import DialogUtils
from wui_components.jans_cli_dialog import JansGDialog
from wui_components.jans_tab import JansTab
from typing import Any
from wui_components.jans_vetrical_nav import JansVerticalNav
from prompt_toolkit.layout import Window

from utils.multi_lang import _

class ViewProperty(JansGDialog, DialogUtils):
    """The Main UMA-resources Dialog to view UMA Resource Details
    """
    def __init__(
            self,
            app: Application,
            parent,
            data:tuple,
            title: AnyFormattedText='',
            op_type: Optional[str]='replace'
            )-> None:
        """init for `ViewProperty`, inherits from two diffrent classes `JansGDialog` and `DialogUtils`

        JansGDialog (dialog): This is the main dialog Class Widget for all Jans-cli-tui dialogs except custom dialogs like dialogs with navbar
        DialogUtils (methods): Responsable for all `make data from dialog` and `check required fields` in the form for any Edit or Add New

        Args:
            app (Generic): The main Application class
            parent (widget): This is the parent widget for the dialog
            data (tuple): selected line data
            title (AnyFormattedText, optional): The Main dialog title. Defaults to "".
        """
        super().__init__(app)
        self.property_name, self.value = data[0], data[1]
        self.app = app
        self.myparent = parent
        self.op_type = op_type
        self.value_content = HSplit([],width=D())
        self.tab_widget = None
        self.widgets = []
        self.buttons = [Button(text=_("Cancel"), handler=self.cancel), Button(text=_("Save"), handler=self.save)]
        self.prepare_properties()
        self.create_window()

    def cancel(self) -> None:
        """method to invoked when canceling changes in the dialog (Cancel button is pressed)
        """

        self.future.set_result(DialogResult.CANCEL)

    def save(self) -> None:
        """method to invoked when saving the dialog (Save button is pressed)
        """

        if len(self.widgets) == 1:
            item_data = self.get_item_data(self.widgets[0])
            data = item_data['value']

        elif self.tab_widget:
            data = []
            tabn = []
            for tab in self.tab_widget.tabs:
                tabn.append(tab[0])
                if self.tab_widget.tab_content_type == 'object':
                    tab_data = self.make_data_from_dialog({tab[0]: tab[1]})
                else:
                    tab_data_tmp = self.make_data_from_dialog({tab[0]: tab[1]})
                    tab_data = tab_data_tmp[self.property_name]
                data.append(tab_data)
        else:
            data = {}
            for widget in self.widgets:
                item_data = self.get_item_data(widget)
                if item_data:
                    data[item_data['key']] = item_data['value']

        cli_args = {'operation_id': 'patch-properties', 'data': [ {'op':self.op_type, 'path': self.property_name, 'value': data } ]}

        async def coroutine():
            self.app.start_progressing()
            response = await self.app.loop.run_in_executor(self.app.executor, self.app.cli_requests, cli_args)
            self.app.stop_progressing()
            self.myparent.app_configuration = response
            self.future.set_result(DialogResult.ACCEPT)
            await self.myparent.get_appconfiguration()
            self.myparent.oauth_update_properties(start_index=self.myparent.oauth_update_properties_start_index)

        asyncio.ensure_future(coroutine())

    def get_widgets(
            self,
            properties:dict,
            values: dict=None,
            styles: dict=None
            ) -> list:
        """Returns list of widgets for properties

        Args:
            properties (dict): properties to get widget
            values (dict): values of properties
            styes (dict): styles for widgets
        """

        if not values:
            values = {self.property_name: self.value}
        if not styles:
            styles = {'widget_style':'', 'string': cli_style.edit_text, 'boolean': cli_style.check_box}

        widgets = []
        for item_name in properties:
            item = properties[item_name]
            if item['type'] in ('integer', 'string'):
                widgets.append(
                    self.app.getTitledText(
                        item_name,
                        name=item_name,
                        value=str(values.get(item_name,'')),
                        text_type=item['type'],
                        style=styles['string'],
                        widget_style=styles['widget_style']
                    )
                )

            elif item['type'] == 'boolean':
                widgets.append(
                    self.app.getTitledCheckBox(
                        item_name,
                        name=item_name,
                        checked=values.get(item_name, False),
                        style=styles['boolean'],
                        widget_style=styles['widget_style']
                        )
                    )

            elif item['type'] == 'array' and item['items'].get('enum'):
                widgets.append(
                    self.app.getTitledCheckBoxList(
                        item_name,
                        name=item_name,
                        values=item['items']['enum'],
                        current_values=values.get(item_name, []),
                        style=styles['boolean'],
                        widget_style=styles['widget_style']
                        )
                    )

            elif item['type'] == 'array' and item['items'].get('type') in ('string', 'integer'):
                titled_text = self.app.getTitledText(
                                    item_name,
                                    name=item_name,
                                    height=4,
                                    text_type = item['items']['type'],
                                    value='\n'.join(values.get(item_name, [])),
                                    style=styles['string'],
                                    widget_style=styles['widget_style']
                                )
                titled_text.jans_list_type = True
                widgets.append(titled_text)

            elif item['type'] == 'object' :
                # if item_name not in  ['clientAuthMapSchema','dateFormatterPatterns'] :
                self.this_value = self.value.get(item_name,{}) #values.get(item_name, [])
                # if this_value:
                propert_widget = JansVerticalNav(
                                myparent=self.app,
                                headers=[_("Property"), _("Value")],
                                preferred_size= [0,0],
                                on_display=self.app.data_display_dialog,
                                data=[[key, value] for key, value in self.this_value.items()],
                                all_data=[{key: val} for key, val in self.this_value.items()],
                                on_delete=self.delete_property,
                                on_enter=self.view_property,
                                selectes=0,
                                headerColor=cli_style.navbar_headcolor,
                                entriesColor=cli_style.navbar_entriescolor,
                                hide_headers = False,
                                max_height=20,
                                jans_name=item_name,
                            )

                property_button = HSplit([
                    self.app.getButtonWithHandler(text=f"Add {item_name}",
                                                  name=item_name,
                                                  handler=self.add_property,
                                                  jans_help='add Property')
                    ])

                widgets.append(self.app.getTitledWidget(widget=propert_widget,
                                         title=str(item_name),
                                         name=item_name,
                                         style='green',
                                         other_widgets= property_button))

        return widgets

    def view_property(self, **params: Any) -> None:
        """This method view the properties in Dialog to edit
        """
        data_property, data_value = params['passed'][0], params['passed'][1]
        self.property_field = self.app.getTitledText(
                        data_property,
                        name=data_property,
                        value=str(data_value),
                    )
        body = HSplit([
           self.property_field
            ])
        buttons = [Button(text=_("Cancel")), Button(text=_("Save"),handler=self.save_nasted)]
        self.nasted_dialog = JansGDialog(self.app, title=str(data_property), body=body,buttons=buttons)
        self.nasted_dialog.data_property = data_property
        self.nasted_dialog.data_value = data_value

        self.app.show_jans_dialog(self.nasted_dialog)

    def save_nasted(self,dialog):
        self.this_value[dialog.data_property] = self.property_field.me.text
        self.future.set_result(DialogResult.ACCEPT)

    def add_property(self,item_name):

        body = HSplit([
                self.app.getTitledText(
                    title=_("Property"),
                    name='Property',
                    style=cli_style.edit_text_required
                ),
                self.app.getTitledText(
                    title=_("Value"),
                    name='Value',
                    style=cli_style.edit_text_required
                ),
        ])

        save_button = Button(_("Save"), handler=self.save_property)
        save_button.keep_dialog = True
        canncel_button = Button(_("Cancel"))
        buttons = [save_button, canncel_button]
        dialog = JansGDialog(self.app, title=str(item_name), body=body, buttons=buttons)
        dialog.item_name=item_name
        self.app.show_jans_dialog(dialog)

    def delete_property(self, **kwargs: Any) -> None:
        selects = kwargs['selected']
        jans_name = kwargs['jans_name']

        def do_delete_property(result):
            self.value[jans_name].pop(selects[0])
            self.prepare_properties()
            self.dialog.body=HSplit([self.value_content], padding=1,width=100)
            self.app.layout.focus(self.dialog.body)

        dialog = self.app.get_confirm_dialog(
            message = _(f"Are you sure want to delete {selects}:"),
            confirm_handler=do_delete_property
            )

        self.app.show_jans_dialog(dialog)

    def save_property(self, dialog):

        new_data = self.make_data_from_dialog(tabs={dialog.title: dialog.body})

        self.value[dialog.item_name][new_data['Property']]= new_data['Value']

        self.prepare_properties()
        self.dialog.body=HSplit([self.value_content], padding=1,width=100)
        dialog.future.set_result(True)

        self.app.layout.focus(self.dialog.body)

    def add_tab_element(
        self,
        properties:dict,
        values: dict
        ) -> None:
        """Adds element to tab widget
            Args:
            properties (dict): properties of element to add
            values (dict): values of properties
        """

        tab_name = '#{}'.format(len(self.tab_widget.tabs)+1)
        tab_widgets = self.get_widgets(properties, values=values, styles={'widget_style': cli_style.tab_selected, 'string': cli_style.tab_selected, 'boolean': cli_style.tab_selected})
        self.tab_widget.add_tab(tab_name, HSplit(tab_widgets, style=cli_style.tab_selected))
        if not values:
            self.tab_widget.set_tab(tab_name)

    def delete_tab_element(self) -> None:
        """Deletes currenlt oelemnt form tab widget
        """
        cur_tab = self.tab_widget.cur_tab
        cur_tab_name = self.tab_widget.tabs[cur_tab][0]
        self.tab_widget.remove_tab(cur_tab_name)

    def prepare_properties(self):
        """This method build the main value_content to edit the properties
        """
        if self.property_name in self.myparent.schema['properties']:
            properties = self.myparent.schema['properties'][self.property_name]
        else:
            properties={}
            properties['type'] = 'string'

        if properties['type'] in ('string', 'integer', 'boolean'):
            self.widgets = self.get_widgets({self.property_name: properties})

        elif properties['type'] == 'array':
            if properties['items'].get('type') in ('string', 'integer', 'boolean'):
                self.widgets = self.get_widgets({self.property_name: properties})

            elif properties['items'].get('type') == 'array':
                self.tab_widget = JansTab(self)
                self.tab_widget.tab_content_type = 'array'
                item_property = {self.property_name: properties['items']}
                for entry_value in self.value:
                    self.add_tab_element(item_property, {self.property_name: entry_value})

                self.value_content = self.tab_widget
                add_entry_partial = partial(self.add_tab_element, item_property, {})
                self.buttons.append(Button(_("Add"), handler=add_entry_partial))
                self.buttons.append(Button(_("Delete"), handler=self.delete_tab_element))

            elif properties.get('properties'):
                self.tab_widget = JansTab(self)
                self.tab_widget.tab_content_type = 'object'
                for entry_value in self.value:
                    self.add_tab_element(properties['properties'], entry_value)
                self.value_content = self.tab_widget
                add_entry_partial = partial(self.add_tab_element, properties['properties'], {})
                self.buttons.append(Button(_("Add"), handler=add_entry_partial))
                self.buttons.append(Button(_("Delete"), handler=self.delete_tab_element))

        elif properties['type'] == 'object':
            self.widgets = self.get_widgets(properties['properties'], values=self.value)

        if not self.tab_widget:
            self.value_content = HSplit(self.widgets, width=D())

    def create_window(self) -> None:
        """Creates dialog window
        """

        self.dialog = Dialog(
            title=self.property_name,
            body= HSplit([self.value_content], padding=1,width=100,style='class:outh-uma-tabs'),
            buttons=self.buttons,
            with_background=False,
        )

    def __pt_container__(self)-> Dialog:
        """The container for the dialog itself

        Returns:
            Dialog: View Property
        """

        return self.dialog


# Una clase en Python para representar gráficas, mostrando
# aspectos y funcionalidades esenciales de las gráficas

class Graph(object):

    def __init__(self, graph_dict=None):
        # Si no se provee de un diccionario,
        # entonces se genera uno vacío
        if graph_dict == None:
            graph_dict = {}
        self.__graph_dict = graph_dict

    def vertices(self):
        # Regresa los vértices de la gráfica
        return list(self.__graph_dict.keys())

    def edges(self):
        # Regresa los vértices de la gráfica
        return self.__generate_edges()

    def add_vertex(self, vertice):
        # Si 'vertice' no está en el diccionario de la gráfica,
        # ent. una llave con nombre 'vertice' y una lista vacía
        # como valor se añade al diccionario.
        # Si 'vertice' ya forma parte del diccionario, no
        # se realiza ninguna acción
        if vertice not in self.__graph_dict:
            self.__graph_dict[vertice] = []

    def add_edge(self, arista):
        # Suponemos que  'arista' es de tipo tupla o lista
        (v1, v2) = tuple(arista)
        if v1 in self.__graph_dict:
            self.__graph_dict[v1].append(v2)
        else:
            self.__graph_dict[v1] = [v2]

    def __generate_edges(self):
        # Un método estático generando las aristas del objecto 'graph'
        # que se pasó como argumento a la clase.
        aristas = []
        for v in self.__graph_dict:
            for ady in self.__graph_dict[v]:
                if (ady, v) not in aristas and (v, ady) not in aristas:
                    aristas.append((v, ady))
        return aristas

    def __str__(self):
        res = "vertices: "
        for k in self.__graph_dict:
            res += str(k) + " "
        res += "\naristas: "
        for edge in self.__generate_edges():
            res += str(edge) + " "
        return res

if __name__ == "__main__":

    g = { "a" : ["d"],
          "b" : ["c"],
          "c" : ["b", "c", "d", "e"],
          "d" : ["a", "c"],
          "e" : ["c"],
          "f" : []
        }

    graph = Graph(g)

    print("Vértices de la gráfica:")
    print(graph.vertices(),"\n")

    print("Aristas de la gráfica:")
    print(graph.edges(),"\n")

    print("Añadir un vértice:","\n")
    graph.add_vertex("z")

    print("Vértices de la gráfica :")
    print(graph.vertices(),"\n")

    print("Añadir una arista:","\n")
    graph.add_edge(("a","a"))

    print("Vértices de la gráfica:")
    print(graph.vertices(),"\n")

    print("Aristas de la gráfica:")
    print(graph.edges(),"\n")

    print('Añadir una arista ("x","y") con vértices nuevos:',"\n")
    graph.add_edge(("x","y"))

    print("Vértices de la gráfica:")
    print(graph.vertices(),"\n")

    print("Aristas de la gráfica:")
    print(graph.edges(),"\n")


from odoo import api, fields, models

class ProductMppt(models.Model):
    _name = 'product.mppt'
    _description = "Product MPPT"
    _order = 'mppt_number, input_number'

    name = fields.Char(string="String", compute='_compute_name', store=True)
    product_tmpl_id = fields.Many2one(comodel_name='product.template', string="Product", required=True)

    mppt_number = fields.Integer(string="MPPT Number")
    input_number = fields.Integer(string="MPPT Number")
    enabled = fields.Boolean(string="Enabled", default=True)

    @api.depends('mppt_number', 'input_number')
    def _compute_name(self):
        for rec in self:
            rec.name = f"{chr(rec.mppt_number + 65)}{rec.input_number + 1}"


import datetime
import time

import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from pageObjects.GeneralObjects import GeneralObjects
from pageObjects.LoginPage import LoginPage
from PyTests.TestData.LoginPageData import LoginPageData
from utilities.BaseClass import BaseClass

@pytest.fixture(params=LoginPageData.testhr_login_data)
def login_data(request):
    return request.param

class TestOne(BaseClass):
    def test_pages_finance(self, setup, login_data):
        log = self.get_logger()
        log.info(login_data["account"])
        log.info("Attempting Login.")

        loginpage = LoginPage(self.driver)
        loginpage.username_box().send_keys(login_data["account"])
        loginpage.password_box().send_keys(login_data["password"])
        homepage = loginpage.login_button()
        log.info("Succesfully logged in.")
        log.info("Navigating to finance-pages.")

        homepage.menu_label_finance()
        homepage.menu_label_msp_invoices()
        titlepageinvoices = self.driver.find_element(
            By.XPATH, "(//h1[normalize-space()='Invoices'])[1]"
        ).text
        assert titlepageinvoices == "Invoices"
        log.info("Succesfully verified invoices-page.")

        generalobjects = GeneralObjects(self.driver)
        generalobjects.sign_out_button()

class TestTwo(BaseClass):
    def test_pages_administration(self, setup, login_data):
        log = self.get_logger()
        log.info(login_data["account"])
        log.info("Attempting Login.")

        loginpage = LoginPage(self.driver)

        loginpage.username_box().send_keys(login_data["account"])
        loginpage.password_box().send_keys(login_data["password"])
        homepage = loginpage.login_button()
        log.info("Succesfully logged in.")
        log.info("Navigating to administration-pages.")

        homepage.menu_label_administration()
        accountdetailspage = homepage.menu_label_account_details()
        titleaccountdetailspage = accountdetailspage.account_details_title().text
        assert titleaccountdetailspage == "Account details"
        log.info("Succesfully verified account details page.")

        accountdetailspage.account_details_save_button()
        message = accountdetailspage.account_details_updated_message().text
        assert message == "Account details updated."
        log.info("Succesfully updated account details.")

        tagmanagerpage = homepage.menu_label_tag_manager()
        titletagmanagerpage = tagmanagerpage.page_title().text
        assert "Tag manager" in titletagmanagerpage
        log.info("Succesfully verified tag manager page.")

        generalobjects = GeneralObjects(self.driver)
        generalobjects.sign_out_button()

class TestThree(BaseClass):
    def test_pages_employees(self, setup, login_data):
        log = self.get_logger()
        log.info(login_data["account"])
        log.info("Attempting Login.")

        loginpage = LoginPage(self.driver)
        loginpage.username_box().send_keys(login_data["account"])
        loginpage.password_box().send_keys(login_data["password"])
        homepage = loginpage.login_button()
        log.info("Succesfully logged in.")
        log.info("Navigating to employees pages.")

        homepage.menu_label_employees()
        homepage.menu_label_import()
        titleimportpage = self.driver.find_element(
            By.XPATH, "//h1[.='Import employees']"
        ).text
        assert titleimportpage == "Import employees"
        log.info("Succesfully verified import-page.")

        homepage.menu_label_create_report()
        titlecreatereportpage = self.driver.find_element(
            By.XPATH, "(//h1[normalize-space()='Create report'])[1]"
        ).text
        assert titlecreatereportpage == "Create report"
        log.info("Succesfully verified report-page.")

        homepage.menu_label_profiles_overview()
        titleprofilesoverview = self.driver.find_element(
            By.XPATH, "(//h1[.='Overview'])"
        ).text
        assert titleprofilesoverview == "Overview"
        log.info("Succesfully verified overview-page.")

        generalobjects = GeneralObjects(self.driver)
        generalobjects.sign_out_button()

class TestFour(BaseClass):
    def test_pages_mobility_policies(self, setup, login_data):
        log = self.get_logger()
        log.info(login_data["account"])
        log.info("Attempting Login.")

        loginpage = LoginPage(self.driver)
        loginpage.username_box().send_keys(login_data["account"])
        loginpage.password_box().send_keys(login_data["password"])
        homepage = loginpage.login_button()
        log.info("Succesfully logged in.")
        log.info("Navigating to mobility-pages.")
        homepage.menu_label_mobility()
        homepage.menu_label_mobility_policies()
        titlemobilitypolicies = self.driver.find_element(
            By.XPATH, "//span[.='Mobility policies']"
        ).text
        assert titlemobilitypolicies == "Mobility policies"
        log.info("Succesfully verified mobility policies-page.")

        homepage.menu_label_expenses()
        titleexpenses = self.driver.find_element(By.XPATH, "//h1[.='Expenses']").text
        assert titleexpenses == "Expenses"
        log.info("Succesfully verified expenses-page.")

        generalobjects = GeneralObjects(self.driver)
        generalobjects.sign_out_button()

class TestFive(BaseClass):
    def test_user_detail(self, setup, login_data):
        log = self.get_logger()
        log.info(login_data["account"])
        log.info("Attempting Login.")

        loginpage = LoginPage(self.driver)
        loginpage.username_box().send_keys(login_data["account"])
        loginpage.password_box().send_keys(login_data["password"])
        homepage = loginpage.login_button()
        log.info("Succesfully logged in.")
        log.info("Navigating to employee overview.")
        homepage.menu_label_employees()
        hrprofilesoverview = homepage.menu_label_profiles_overview()
        log.info("Opening Auto 10 User 10's profile by clicking on name.")
        userdetailpage = hrprofilesoverview.profile_overview_click_name()
        wait = WebDriverWait(self.driver, 10)
        wait.until(EC.presence_of_element_located((By.XPATH, "//button[.='Personal']")))
        log.info("Attempting to verify presence of all relevant elements.")
        userdetailpage.userdetail_verify_presence_personal_elements()
        log.info("Succesfully verified page elements.")
        log.info("Opening employment subtab.")
        userdetailpage.userdetail_select_employment_tab()
        userdetailpage.userdetail_verify_presence_employment_elements()
        log.info("Successfully verified employment subtab.")
        log.info("Opening financial info subtab.")
        userdetailpage.userdetail_select_financialinfo_tab()
        userdetailpage.userdetail_verify_presence_financialinfo_elements()
        log.info("Succesfully verified financial info subtab.")
        log.info("Opening identifiers subtab.")
        userdetailpage.userdetail_select_identifiers_tab()
        userdetailpage.userdetail_verify_presence_identifiers_elements()
        log.info("Succesfully verified securex subtab.")
        log.info("Attempting to navigate to the next user.")
        userdetailpage.userdetail_next_previous()
        log.info("Succesfully navigated to the next user detail.")
        log.info("Returning to profiles overview.")

        userdetailpage.userdetail_return_to_overview()
        log.info("Attempting to open profile through view-option.")
        userdetailpage.profile_overview_view_profile()
        wait.until(EC.presence_of_element_located((By.XPATH, "//button[.='Personal']")))
        userinfotitle = self.driver.find_element(By.XPATH, "//h5[.='User info']").text
        assert userinfotitle == "User info"

        generalobjects = GeneralObjects(self.driver)
        generalobjects.sign_out_button()

class TestSix(BaseClass):
    def test_ruleset_overview(self, setup, login_data):
        log = self.get_logger()
        log.info(login_data["account"])
        log.info("Attempting Login.")

        loginpage = LoginPage(self.driver)
        loginpage.username_box().send_keys(login_data["account"])
        loginpage.password_box().send_keys(login_data["password"])
        homepage = loginpage.login_button()
        log.info("Succesfully logged in.")
        log.info("Navigating to ruleset overview.")
        homepage.menu_label_mobility()
        ruleengineoverview = homepage.menu_label_rule_engine()
        rulesetoverviewtitle = str(ruleengineoverview.ruleset_overview_title().text)
        assert "Expense rule engine" in rulesetoverviewtitle

        generalobjects = GeneralObjects(self.driver)
        generalobjects.sign_out_button()


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""A point connected to an xy plot."""
from misura.canon.logger import get_module_logging
logging = get_module_logging(__name__)
import veusz.widgets
import veusz.document as document
import veusz.setting as setting
import numpy as np
import utils

def translateCoord(ax, vc):
    return [ax.plottedrange[0] + c * (ax.plottedrange[1] - ax.plottedrange[0]) for c in vc]

class Intercept(utils.OperationWrapper, veusz.widgets.Line):
    typename = 'intercept'
    description = 'Intercept Line'
    allowusercreation = True

    def __init__(self, parent, name=None):
        veusz.widgets.Line.__init__(self, parent, name=name)

        self.addAction(veusz.widgets.widget.Action('up', self.actionUp,
                                                   descr='Update Intercept Line',
                                                   usertext='Update Intercept Line'))

        self.settings.positioning = 'relative'
        self.settings.mode = 'point-to-point'

        # xy : {idx:dp1, idx:dp2, ...}
        self.crossings = {}

    @classmethod
    def addSettings(klass, s):
        """Construct list of settings."""
        veusz.widgets.Line.addSettings(s)

        s.add(setting.Bool('showLabels', True,
                           descr='Show Labels',
                           usertext='Show datapoint labels',
                           formatting=True),
              1)
        s.add(setting.Str(
            'labelText', '%(xlabel)s=%(x)i \\\\%(ylabel)s=%(y)E',
            descr='Output labels text',
            usertext='Output labels text'),
            2)

    def intercept_xy(self, obj):
        """Intercept obj xy for all line length"""
        doc = self.document
        self.doc = doc

        # Translate end points coords
        xax = self.parent.getChild(obj.settings.xAxis)
        ox, ox2 = translateCoord(xax, [self.x, self.x2])
        yax = self.parent.getChild(obj.settings.yAxis)
        oy, oy2 = translateCoord(yax, [self.y, self.y2])

        logging.debug('limits', ox, oy2, ox2, oy2)

        # Get the data from the plot obj
        vx = doc.data[obj.settings.xData].data
        vy = doc.data[obj.settings.yData].data
        # Line angle
        ang = np.arctan((oy2 - oy) / (ox2 - ox))
        logging.debug('Angle', ang * 180 / np.pi)
        # Rotation matrix
        rot = np.matrix([
            [np.cos(ang), np.sin(ang)],
            [-np.sin(ang), np.cos(ang)]
        ])
        # Rotate the data
        r = np.asarray(rot * np.array([vx, vy]))
        # Rotate the points
        rp = np.asarray(rot * np.array([[ox], [oy]]))
        rox = rp[0][0]
        roy = rp[1][0]
        # Find where the rotated array crosses the x axis
        crossing = np.diff(np.sign(r[1] - roy))
#		print 'Diff sign',crossing,np.abs(crossing).sum()
        crossings = np.where(crossing != 0)[0]
        logging.debug('Crossings', crossings)
        # Find valid crossing
        cx = []
        found = {obj: {}}
        for c in crossings:
            if not (min(ox, ox2) < vx[c] < max(ox, ox2) or min(oy, oy2) < vy[c] < max(oy, oy2)):
                logging.debug('ignoring crossing', c, vx[c], vy[c])
                continue
            # Avoid very similar entries
            if c + 1 in cx or c - 1 in cx:
                logging.debug('Ignoring too near crossing', c, vx[c], vy[c])
                continue
            cx.append(c)
            # Must create a new DataPoint widget for this crossing
            name = 'intercept_%s_%s_%i' % (self.name, obj.name, c)
            dpset = {'name': name, 'xy': obj.name,
                     'xAxis': obj.settings.xAxis, 'yAxis': obj.settings.yAxis,
                     'xPos': float(vx[c]), 'yPos': float(vy[c]), 'coordLabel': '', 'showLabel': False}
            if self.settings.showLabels == True:
                lblname = 'lbl_' + name
                dpset['showLabel'] = True
                dpset['coordLabel'] = lblname
                self.ops.append(
                    document.OperationWidgetAdd(self.parent, 'label', name=lblname))
            self.ops.append(
                document.OperationWidgetAdd(self.parent, 'datapoint', **dpset))
            found[obj][c] = (name, vx[c], vy[c])
        # Update crossings dictionary
        self.crossings.update(found)
        return True

    def actionUp(self, x=None, y=None, x2=None, y2=None):
        logging.debug('INTERCEPT LINE UP')
        doc = self.document
        s = self.settings
        self.ops = []

        # Settings coerence
        aligned = self.toset(self, 'positioning', 'relative')
        aligned = aligned and self.toset(self, 'mode', 'point-to-point')
        if not aligned:
            logging.debug('Not aligned: apply ops', self.ops)
            doc.applyOperation(
                document.OperationMultiple(self.ops, descr='InterceptUp'))
            self.ops = []

        x = s.xPos[0] if x is None else x
        y = s.yPos[0] if y is None else y
        x2 = s.xPos2[0] if x2 is None else x2
        y2 = s.yPos2[0] if y2 is None else y2
        logging.debug(x, y, x2, y2)
        self.x = x
        self.y = y
        self.x2 = x2
        self.y2 = y2

        # Delete old datapoints and their labels
        for xy, fd in self.crossings.iteritems():
            for c, (name, dpx, dpy) in fd.iteritems():
                dp = self.parent.getChild(name)
                if dp.labelwidget is not None:
                    self.ops.append(
                        document.OperationWidgetDelete(dp.labelwidget))
                self.ops.append(document.OperationWidgetDelete(dp))

        self.apply_ops('interceptDelete')

        # Iterate over all curves in the same graph
        self.crossings = {}  # xy : {idx1:dp1, idx2:dp2, ...}
        for obj in self.parent.children:
            if obj.typename != 'xy':
                continue
            self.intercept_xy(obj)

        # Create everything
        self.apply_ops('interceptCreate')

        # Then update current datapoints
        for xy, fd in self.crossings.copy().iteritems():
            for c, (name, dpx, dpy) in fd.iteritems():
                dp = self.parent.getChild(name)
                # Updata datapoint position
                if not self.settings.showLabels:
                    lbl = dp.labelwidget
                    if lbl is not None:
                        self.ops.append(document.OperationWidgetDelete(lbl))
                dp.actionUp(dpx, dpy)
        # Create everything
        self.apply_ops('interceptLabels')
        return True

    def updateControlItem(self, cgi, pt1, pt2):
        """If control items are moved, update line."""
        # Call the line method

        veusz.widgets.Line.updateControlItem(self, cgi, pt1, pt2)
        self.actionUp()

document.thefactory.register(Intercept)


import tensorflow as tf
import os
import numpy as np

#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
AUTOTUNE = tf.data.experimental.AUTOTUNE
tf.keras.backend.set_floatx('float32')

n = 20
def odd_generator(n):
    some_numbers = range(0,n,2)
    for i in some_numbers:
        yield [1.],[i+1]

def even_generator(n):
    some_numbers = range(0,n,2)
    for i in some_numbers:
        yield [0.],[i]

training = True
buffer_size = n
batch_size = 4
steps_per_epoch = int(n/batch_size)

x = tf.data.Dataset.from_generator(odd_generator,args=[n],output_types=(tf.float32,tf.float32),output_shapes=((1),(1)))#.repeat(1)
y = tf.data.Dataset.from_generator(even_generator,args=[n],output_types=(tf.float32,tf.float32),output_shapes=((1),(1)))#.repeat(1)

ds = tf.compat.v1.data.experimental.sample_from_datasets([x,y])

if training:
    #pass
    #ds = ds.repeat(int(buffer_size/batch_size))
    ds = ds.shuffle(buffer_size=buffer_size)
#ds = ds.map(lambda y,x: tuple((int(y),int(x))),num_parallel_calls=AUTOTUNE)
ds = ds.batch(batch_size,drop_remainder=True)

ds = ds.repeat(steps_per_epoch)
ds = ds.prefetch(buffer_size=AUTOTUNE)

#########################################################
#########################################################

x = tf.data.Dataset.from_generator(odd_generator,args=[n],output_types=(tf.float32,tf.float32),output_shapes=((1),(1)))#.repeat(1)
y = tf.data.Dataset.from_generator(even_generator,args=[n],output_types=(tf.float32,tf.float32),output_shapes=((1),(1)))#.repeat(1)

#v_ds = tf.compat.v1.data.experimental.sample_from_datasets([x,y])
v_ds = x.concatenate(y)

if training:
    pass
    #v_ds = v_ds.repeat(int(buffer_size/batch_size))
    #v_ds = v_ds.shuffle(buffer_size=buffer_size)
#v_ds = v_ds.map(lambda y,x: tuple((int(y),int(x))),num_parallel_calls=AUTOTUNE)
v_ds = v_ds.batch(batch_size,drop_remainder=False)

v_ds = v_ds.repeat(steps_per_epoch)
#v_ds = v_ds.prefetch(buffer_size=AUTOTUNE)

#########################################################
#########################################################

for i,x in ds:
    print(x)

inp = tf.keras.layers.Input((1))
layer = tf.keras.layers.Dense(1,activation='sigmoid')(inp)
out = layer

model = tf.keras.Model(inputs=inp,outputs=out)

bce=tf.keras.losses.BinaryCrossentropy(from_logits=False)
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1.0e-5,clipnorm=1.0),loss='binary_crossentropy',metrics=['binary_accuracy','mse'],run_eagerly=True)

model.fit(ds,validation_data=v_ds,epochs=3)
#model.fit(ds)#,validation_data=v_ds,validation_steps=2,verbose=2)


from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import codecs
import json

access_token = "YOUR ACCESS_TOKEN"
access_token_secret = "YOUR ACCESS_TOKEN"
consumer_key = "YOUR CONSUMER_KEY"
consumer_secret = "YOUR CONSUMER_SECRET"

class StdOutListener(StreamListener):

    def on_data(self, raw_data):
        data = json.loads(raw_data)
        print(json.dumps(data, ensure_ascii=False))

    def on_error(self, status):
        print (status)

if __name__ == '__main__':

    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)
    stream.filter(languages=["tr"], track=["word1", "word2", "word3", "word4", "word5", "more..."])


#
# @lc app=leetcode id=66 lang=python3
#
# [66] Plus One
#

# @lc code=start
from typing import List

class Solution:
    # def plusOne(self, digits: List[int]) -> List[int]:
    #     """
    #     Accepted
    #     111/111 cases passed (37 ms)
    #     Your runtime beats 39.95 % of python3 submissions
    #     Your memory usage beats 5.48 % of python3 submissions (13.9 MB)
    #     """
    #     s = ""
    #     for i in digits:
    #         s += str(i)

    #     return map(int, str(int(s) + 1))

    def plusOne(self, digits: List[int]) -> List[int]:
        """
        Accepted
        111/111 cases passed (29 ms)
        Your runtime beats 88.4 % of python3 submissions
        Your memory usage beats 43.88 % of python3 submissions (13.8 MB)
        """
        if digits == []:
            return []

        if digits[-1] + 1 < 10:
            return digits[:-1] + [digits[-1] + 1]

        if len(digits) == 1 and digits[-1] + 1 >= 10:
            return [1, digits[-1]+1-10]
        return self.plusOne(digits[:-1]) + [digits[-1]+1-10]

# @lc code=end


#!/usr/bin/env python

import matplotlib
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')

import numpy as np

if __name__ == '__main__':
    data = []

    fig, ax = plt.subplots(2)
    #ax[0].set_xlabel('input')
    #ax[0].set_ylabel('scalar')

    # do function
    # f(x) = x^3 + 4x^2 + 3x - 1
    x = np.linspace(-4, 2, 1000)
    y = x**3 + 4*x**2 + 3*x - 1
    ax[0].plot(x, y)

    # do gradient
    # f'(x) = 3x^2 + 8x + 3
    x_pos = []
    y_pos = []
    x_direct = []
    y_direct = []

    y = 0
    for x in [-4, -3.5, -3, -2.5, -2, -1.5, -1, -.5, 0, .5, 1, 1.5, 2]:
        x_pos.append(x)
        y_pos.append(0)

        x_direct.append(3*x*x + 8*x + 3)
        y_direct.append(0)

    # scale everything so biggest arrow is 1
    m = max([abs(x) for x in x_direct])
    #print('x_direct: ', x_direct)
    x_direct = [x/m for x in x_direct]
    #print('x_direct: ', x_direct)

    ax[1].quiver(x_pos, y_pos, x_direct, y_direct)

    # save it all
    plt.savefig('dim1.png')
    plt.close(fig)


import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as chrome_options

@pytest.fixture
def get_chrome_options():
    options = chrome_options()
    options.add_argument('chrome')# use headlees if oyu do noy need a browoser ui
    options.add_argument('--start-maximized')
    options.add_argument('--window-size=1920,1080')
    return options

@pytest.fixture
def get_webdriver(get_chrome_options):
    options= get_chrome_options
    driver= webdriver.Chrome(options=options)
    #D:\github\Andreev_qa\PYTHON+SELENIUM\chromedrive

    return driver

@pytest.fixture(scope='function')
def setup(request, get_webdriver):
    driver = get_webdriver
    url = 'https://www.macys.com/'
    if request.cls is not None:
        request.cls.driver = driver
    driver.get(url)
    yield driver
    driver.quit()