import unittest
import subprocess
from service.request import get, post, put
from urllib.error import HTTPError
from random import randint
from threading import Thread

VALID_CREDIT_CARD = ''.join([f'{randint(0, 9)}' for _ in range(16)])

INVALID_CREDIT_CARD = 'haiwdhiawhidawihdhiaw'

class TestWebService(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        # reset all tables first
        subprocess.run(['python', 'setup.py', 'reset', '2'])
        # run app server
        cls.server_proc = subprocess.Popen(['python', 'main.py'])

    @classmethod
    def tearDownClass(cls):
        cls.server_proc.terminate()

    # Test1: A query about a product returns the correct product attributes.
    def test_query_product(self):
        expected = {
            'id': 1,
            'quantity': 2,
            'description': 'apple',
            'price': 10
        }
        self.assertDictEqual(get('/market/query/1')['data'], expected)

    # Test2: Buying a product with sufficient stock in the server succeeds and the quantity
    # in stock is updated
    def test_buy_product(self):
        expected_resp = {
            'cost': 30,
            'status': 'Success'
        }
        resp = post('/market/buy/2', {
            'credit_card': VALID_CREDIT_CARD,
            'amount': 2
        })['data']
        self.assertDictEqual(expected_resp, resp)

        # after buy
        expected_resp = {
            'id': 2,
            'quantity': 0,
            'description': 'banana',
            'price': 15
        }
        self.assertDictEqual(get('/market/query/2')['data'], expected_resp)

    # Buying a product with insufficient stock in the server fails and the quantity in
    # stock remains unchanged
    def test_buy_product_insufficent(self):
        expected_resp = {
            'cost': 0,
            'status': 'Failure (insufficent quantity)'
        }
        resp = post('/market/buy/3', {
            'credit_card': VALID_CREDIT_CARD,
            'amount': 3
        })['data']
        self.assertDictEqual(expected_resp, resp)

        # remain unchanged
        expected_resp = {
            'id': 3,
            'quantity': 2,
            'description': 'orange',
            'price': 20
        }
        self.assertDictEqual(get('/market/query/3')['data'], expected_resp)

    # Test4: Replenishing a product updates the server’s quantity in stock
    def test_replenish_product(self):
        expected_resp = {
            'quantity': 5,
            'status': 'Success'
        }
        resp = put('/market/replenish/4', {'amount': 3})['data']
        self.assertDictEqual(expected_resp, resp)

        # query a product should show the new quantity
        expected_resp = {
            'quantity': 5,
            'id': 4,
            'description': 'milk',
            'price': 25
        }
        self.assertDictEqual(get('/market/query/4')['data'], expected_resp)

    # Test5: When the product ID does not exist, the server returns the 404 status code.
    def test_product_id_non_exist(self):
        with self.assertRaises(HTTPError) as e:
            get('/market/query/999')
            self.assertEqual(e.exception.status, 404)

    # Test6: When some required input data are missing or invalid, the server returns the
    # 400 status code
    def test_invalid_or_missing_arguments(self):
        # test buy without credit card
        with self.assertRaises(HTTPError) as e:
            post('/market/buy/5', {'amount': 1})
            self.assertEqual(e.exception.status, 400)

        # test invalid credit card
        with self.assertRaises(HTTPError) as e:
            post('/market/buy/5', {
                'amount': 1,
                'credit_card': INVALID_CREDIT_CARD
            })
            self.assertEqual(e.exception.status, 400)

        # test invalid amount
        with self.assertRaises(HTTPError) as e:
            post('/market/buy/5', {
                'amount': 'infinite',
                'credit_card': VALID_CREDIT_CARD
            })
            self.assertEqual(e.exception.status, 400)

    # Test7: If two requests for buying the same product arrive almost simultaneously and
    # the quantity in stock is insufficient for the second request, the server must not
    # mistakenly fulfill the second request
    def test_buy_product_simultaneously(self):

        statues = [None] * 2

        def buy_two_product(index):
            status = post('/market/buy/6', {
                'amount': 2,
                'credit_card': VALID_CREDIT_CARD
            })['data']['status']
            nonlocal statues
            statues[index] = status

        threads = [ Thread(target=buy_two_product, args=(i, )) for i in range(2) ]
        for thread in threads:
            thread.start()

        for thread in threads:
            thread.join()

        self.assertNotEqual(statues[0], statues[1])

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


import random
from acts.base_test import BaseTestClass

CONSERVATIVE_MAX_ATTEN_VALUE = 10
MIN_ATTEN_VALUE = 0

class AttenuatorSanityTest(BaseTestClass):
    def __init__(self, controllers):
        BaseTestClass.__init__(self, controllers)
        self.tests = ("test_attenuator_validation",
                      "test_attenuator_get_max_value", )
        self.number_of_iteration = 2

    def test_attenuator_validation(self):
        """Validate attenuator set and get APIs works fine.
        """
        for atten in self.attenuators:
            self.log.info("Attenuator: {}".format(atten))
            try:
                atten_max_value = atten.get_max_atten()
            except ValueError as e:
                self.log.error(e)
                self.log.info("Using conservative max value.")
                atten_max_value = CONSERVATIVE_MAX_ATTEN_VALUE

            atten_value_list = [MIN_ATTEN_VALUE, atten_max_value]
            for i in range(0, self.number_of_iteration):
                atten_value_list.append(
                    int(random.uniform(0, atten_max_value)))

            for atten_val in atten_value_list:
                self.log.info("Set atten to {}".format(atten_val))
                atten.set_atten(atten_val)
                current_atten = int(atten.get_atten())
                self.log.info("Current atten = {}".format(current_atten))
                assert atten_val == current_atten, "Setting attenuator failed."

        return True

    def test_attenuator_get_max_value(self):
        """Validate attenuator get_max_atten APIs works fine.
        """
        for atten in self.attenuators:
            try:
                atten_max_value = atten.get_max_atten()
            except ValueError as e:
                self.log.error(e)
                return False
        return True


#  Write a python program to in the same interface as above and create a action when the button is click it will
#  display some text.

from tkinter import *

def functodisplay():

    print("Message Displayed")

widget = Button(None, text="CLICK TO DISPLAY", command = functodisplay)

widget.pack(side = BOTTOM, expand = YES, fill=Y)

widget.mainloop()


# --------------------------------------------------------------------------
# Name:        Word Break II
# Author(s):   Phu Tran
# --------------------------------------------------------------------------
"""
    Given a non-empty string s and a dictionary wordDict containing a list
    of non-empty words, add spaces in s to construct a sentence where each
    word is a valid dictionary word. Return all such possible sentences.

    Note:
      1. The same word in the dictionary may be reused multiple times in the segmentation.
      2. You may assume the dictionary does not contain duplicate words.

    Example 1:
      Input:
        s = "catsanddog"
        wordDict = ["cat", "cats", "and", "sand", "dog"]
      Output:
        [
          "cats and dog",
          "cat sand dog"
        ]

    Example 2:
      Input:
        s = "pineapplepenapple"
        wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
      Output:
        [
          "pine apple pen apple",
          "pineapple pen apple",
          "pine applepen apple"
        ]
      Explanation: Note that you are allowed to reuse a dictionary word.

    Example 3:
      Input:
        s = "catsandog"
        wordDict = ["cats", "dog", "sand", "and", "cat"]
      Output:
        []
"""

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: List[str]
        """
        memo = {}
        def dfs(i): # return all possibilities in s[i:]
            if i in memo:
                return memo[i]
            else:
                res = []
                for word in wordDict:
                    if i + len(word) == len(s) and word == s[i:i+len(word)]: # reaching the end
                        res.append(word)
                    if i + len(word) < len(s) and word == s[i:i+len(word)]:
                        following_res = dfs(i + len(word)) # getting the suffix and add to the result
                        for following in following_res:
                            res.append(word + " " + following)
                memo[i] = res
                return res

        return dfs(0)

'''other faster methods (from other submissions)
##################################################
def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: List[str]
        """
        def fetch_ans(mp, p, s):
            if p >= len(s):
                return [""]
            ans = []
            for i in mp[p]:
                w = s[p:i]
                for w2 in fetch_ans(mp, i, s):
                    w2 = (" " + w2) if len(w2)>0 else ""
                    ans.append(w+w2)
            return ans

        def func(set_words, s):
            mp = defaultdict(lambda : [])
            word_i = [len(s)]
            mp[len(s)] = [len(s)]
            for i in xrange(len(s)-1, -1, -1):
                for j in word_i:
                    if s[i:j] in set_words and mp.has_key(j):
                        mp[i].append(j)
                if mp.has_key(i):
                    word_i.append(i)
            return fetch_ans(mp, 0 , s)
        return func(set(wordDict), s)

##################################################
def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: List[str]
        """
        n = len(s)
        if not n:
            return []
        dp = [[] for _ in range(n)]
        letters1 = set(c for c in s)
        letters2 = set(c for word in wordDict for c in word)
        if not letters2.issuperset(letters1):
            return []
        dic = set(wordDict)
        for i in range(0, n):
            for j in range(0, i + 1):
                cur_word = s[j:i + 1]
                if cur_word in dic:
                    if j == 0:
                        dp[i].append(cur_word)
                    else:
                        for sentence in dp[j - 1]:
                            dp[i].append(sentence + ' ' + cur_word)
        return dp[n - 1]
##################################################
def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: List[str]
        """

        memo = defaultdict(list)
        wordset = set(wordDict)
        result = self.recursive(s,wordset,memo)
        return [" ".join(sentence) for sentence in result]
    def recursive(self, s, wordset, memo):
        if not s:
            return [[]]
        if s in memo:
            return memo[s]
        for i in range(1, len(s)+1):
            word = s[:i]
            if word in wordset:
                for subsentence in self.recursive(s[i:], wordset, memo):
                    memo[s].append([word]+subsentence)
        return memo[s]
 ##################################################
 def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: List[str]
        """
        memo = defaultdict(list)
        wordset = set(wordDict)
        return [" ".join(sentence) for sentence in self.recursive(s, wordset, memo)]

    def recursive(self, s, wordset, memo):
        if not s:
            return [[]]
        if s in memo:
            return memo[s]
        for i in range(1, len(s)+1):
            if s[:i] in wordset:
                for subsentence in self.recursive(s[i:],wordset,memo):
                    memo[s].append([s[:i]]+subsentence)
        return memo[s]

'''


#%%
import torch
from torch.utils.data.dataset import Dataset
import torchvision
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
from sklearn.model_selection import train_test_split
# %%
#* Importing dataset
dataset_train = pd.read_csv('../data/train.csv')
dataset_test = pd.read_csv('../data/test.csv')
print('Training data length:', len(dataset_train))
# %%
#* Having a look at the dataset
targets_np = dataset_train.label.values
features_np = dataset_train.loc[:,dataset_train.columns!='label'].values # values range to 255, so to normalize
X_train, X_test, y_train, y_test = train_test_split(features_np,targets_np,test_size=0.2, random_state=42)
#features_train = torch.from_numpy(X_train)
#target_train = torch.from_numpy(y_train)
#features_test = torch.from_numpy(X_test)
#target_test = torch.from_numpy(y_test)
print('Training Features Shape',X_train.shape)
print('Training Labels Shape',y_train.shape)
print('Testing Features Shape',X_test.shape)
print('Testing Labels Shape',y_test.shape)
#Viz of an image
plt.imshow(features_np[0].reshape(28,28),cmap='gray') # images are 28x28
plt.title('Label: '+str(targets_np[0]))
plt.show()
#%%
i=100
plt.imshow(X_test[i].reshape(28,28),cmap='gray') # images are 28x28
plt.title('Label: '+str(y_test[i]))
plt.show()
# %%
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data import DataLoader, Dataset
import torchvision.transforms as tt

def get_default_device():
    """Returns the default Device (cuda if gpu, else cpu"""
    if torch.cuda.is_available(): return torch.device('cuda')
    else: torch.device('cpu')

def to_device(data,device):
    """Shifts Data to the input device"""
    if isinstance(data,(list,tuple)): return [to_device(x,device) for x in data]
    return data.to(device, non_blocking=True)

class DeviceDataLoader():

    def __init__(self, dl, device) -> None:
        self.dl = dl
        self.device = device

    def __iter__(self):
        for b in self.dl:
            yield to_device(b,self.device)

    def __len__(self): return len(self.dl)

#* Creating a custom dataset overriding torchvision dataset
class MyDataset(Dataset):
    def __init__(self, df_features, df_labels, transform=None) -> None:
        self.features = df_features
        self.labels = df_labels
        self.transform = transform

    def __getitem__(self, index):
        data = self.features[index]
        image = data.reshape(28,28).astype(np.uint8)
        label = self.labels[index]
        if self.transform:
            image = self.transform(image)
        return (image,label)

    def __len__(self): return len(self.features)

BATCH_SIZE = 16

#* Augmentation - Random affination (rotation with translation), normalization
train_tmfs = tt.Compose([
    tt.ToPILImage(),
    #tt.RandomRotation(30),
    tt.RandomAffine(degrees=30, translate = (0.1,0.1), scale = (0.9,1.1)),
    # Random Affine suits better for this purpose @https://pytorch.org/vision/stable/auto_examples/plot_transforms.html#randomaffine
    tt.ToTensor(),
    tt.Normalize(mean=[features_np.mean()/255], std=[features_np.std()/255],inplace=True)
])
test_tmfs = tt.Compose([
    tt.ToPILImage(),
    #tt.RandomRotation(30),
    tt.RandomAffine(degrees=30, translate = (0.1,0.1), scale = (0.9,1.1)),
    # Random Affine suits better for this purpose @https://pytorch.org/vision/stable/auto_examples/plot_transforms.html#randomaffine
    tt.ToTensor(),
    tt.Normalize(mean=[features_np.mean()/255], std=[features_np.std()/255],inplace=True)
])

#* Setting default Device, GPU
device = get_default_device()
print(device)

#* Creating Dataset
train_set = MyDataset(X_train, y_train, transform=train_tmfs)
test_set = MyDataset(X_test, y_test, transform=test_tmfs)

#* Loading data and then shifting data loader to the selected device
train_dl = DeviceDataLoader(DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True),device)
test_dl = DeviceDataLoader(DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=True),device)
# %%
#* Sanity Check
imgs, lbls = next(iter(test_dl))
print(imgs.shape)
plt.imshow(torch.Tensor.cpu(imgs[0].data.reshape(28,28)),cmap='gray')
print('Label:',lbls[0])
plt.show()
# %%
import torch.nn.functional as F
#* Following Residual Network https://raw.githubusercontent.com/lambdal/cifar10-fast/master/net.svg
NUM_CLASSES = 10

def convolution_block(in_channels, out_channels, pool=False):
    """Returns a sequence of Convolution, Batch Normalization, Rectified Linear Activation (Relu) and Max Pooling if selected"""
    layers = [
        nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1),
        nn.BatchNorm2d(out_channels),
        nn.ReLU(inplace=True)
    ]
    if pool: layers.append(nn.MaxPool2d(2,2)) # 2x2 Max Pooling
    return nn.Sequential(*layers)

class Model(nn.Module):

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

        self.conv1 = convolution_block(1,32)

        self.conv2 = convolution_block(32,64,pool=True)
        self.res1 = nn.Sequential(convolution_block(64,64), convolution_block(64,64))

        self.conv3 = convolution_block(64,128, pool=True)

        self.conv4 = convolution_block(128,256, pool=True)
        self.res2 = nn.Sequential(convolution_block(256,256), convolution_block(256,256))

        self.classifier = nn.Sequential(
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Dropout(0.2), #* added later
            nn.Linear(256, NUM_CLASSES)
        )

    def forward(self, xb):
        out = self.conv1(xb) # Prep
        out = self.conv2(out) # Layer 1 Convolution Block
        out = self.res1(out) + out # Layer 1 Residual Block
        out = self.conv3(out) # Layer 2
        out = self.conv4(out) # Layer 3 Convolution Block
        out = self.res2(out) + out # Layer 3 Residual Block
        out = self.classifier(out)
        return F.log_softmax(out, dim=1)
# %%
model = Model()
to_device(model,device)
# %%
# Sanity Check
for images, labels in train_dl:
    print(images.shape)
    out = model(images)
    print(out.shape)
    break
#%%
'''
Cant find fastai modules
from fastai.basic_data import DataBunch
from fastai.train import Learner
from fastai.metrics import accuracy
'''
#%%
import time
@torch.no_grad()
def loss_batch(model, loss_func, xb,yb, opt=None, metric=None):
    preds = model(xb)
    loss = loss_func(preds,yb)

    if opt is not None:
        loss.backward()
        opt.step()
        opt.zero_grad()

    metric_result = None
    if metric is not None:
        metric_result = metric(preds, yb)

    return loss.item(), len(xb), metric_result

def accuracy(outputs, labels):
    _, preds = torch.max(outputs, dim=1)
    return torch.tensor(torch.sum(preds == labels).item() / len(preds))

def get_lr(optimizer):
    for param_group in optimizer.param_groups:
        return param_group['lr']

def fit_one_cycle(epochs, max_lr, model, train_dl, test_dl,
                    weight_decay = 0, grad_clip = None, opt_func = torch.optim.SGD):

    def evaluate(model, test_dl):
        model.eval()
        outputs = [validation_step(images.to(device),labels.to(device)) for images, labels in test_dl]
        return validation_epoch_end(outputs)

    def training_step(images, labels):
        out = model(images)
        loss = F.cross_entropy(out,labels)
        return loss

    def validation_step(images, labels):
        out = model(images)
        loss = F.cross_entropy(out,labels)
        acc = accuracy(out, labels)
        return {'val_loss': loss.detach(), 'val_acc':acc}

    def validation_epoch_end(outputs):
        batch_losses = [x['val_loss'] for x in outputs]
        epoch_losses = torch.stack(batch_losses).mean()
        batch_accs = [x['val_acc'] for x in outputs]
        epoch_acc = torch.stack(batch_accs).mean()
        return {'val_loss': epoch_losses.item(), 'val_acc':epoch_acc.item()}

    def epoch_end(epoch, result, start_time):
        print("Epoch [{}], last_lr:{:.5f}, train_loss:{:.4f}, val_loss:{:.4f}, val_acc: {:.4f}, epoch_time:{:.4f}".format(
            epoch, result['lrs'][-1], result['train_loss'], result['val_loss'], result['val_acc'], time.time()-start_time
        ))

    torch.cuda.empty_cache()
    results = []
    optimizer = opt_func(model.parameters(), max_lr, weight_decay=weight_decay)
    scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, epochs=epochs,
                                            steps_per_epoch=len(train_dl))

    for epoch in range(epochs):
        epoch_start_time = time.time()
        model.train()
        train_losses = []
        lrs = [] # Learning rates at each point
        #* Training Part
        for batch in train_dl:
            images, labels = batch
            images = images.to(device)
            labels = labels.to(device)

            loss = training_step(images, labels) # Generate Predictions and Calculate the loss
            train_losses.append(loss)
            loss.backward()

            if grad_clip:
                nn.utils.clip_grad_value_(model.parameters(), grad_clip)

            optimizer.step() # Compute Gradients
            optimizer.zero_grad() # Reset to zero

            lrs.append(get_lr(optimizer))
            scheduler.step()

        #* Validation part
        result = evaluate(model, train_dl)
        result['train_loss'] = torch.stack(train_losses).mean().item()
        result['lrs'] = lrs
        epoch_end(epoch, result, epoch_start_time)
        results.append(result)

    return results
# %%
EPOCHS = 10
MAX_LEARNING_RATE = 0.001
GRAD_CLIP = 0.1
WEIGHT_DECAY = 1e-4
OPT_FUNC = torch.optim.Adam
# %%
#%%time
results = []
results += fit_one_cycle(EPOCHS, MAX_LEARNING_RATE, model, train_dl, test_dl, WEIGHT_DECAY, GRAD_CLIP, OPT_FUNC)
# %%
#* Plotting training history
time_taken = '8:19'
fig, axs = plt.subplots(nrows=1,ncols=3,figsize=(30,5))
accuracies = [x['val_acc'] for x in results]
axs[0].plot(accuracies, '-x')
axs[0].title.set_text('Accuracies x Number of Epochs')
axs[0].set_ylabel('Accuracies')
axs[0].set_xlabel('Epoch')
axs[1].plot([x['val_loss'] for x in results], '-x')
axs[1].title.set_text('Loss x Number of Epochs')
axs[1].set_ylabel('Loss')
axs[1].set_xlabel('Epoch')
axs[1].plot([x['train_loss'] for x in results], '-rx')
axs[1].title.set_text('Training Loss x Number of Epochs')
lrs = np.concatenate([x.get('lrs',[]) for x in results])
axs[2].plot(lrs)
axs[2].title.set_text('Learning Rate x Batch Number')
axs[2].set_ylabel('Learning Rate')
axs[2].set_ylabel('Batch Number')
plt.suptitle('Training History')
plt.grid()
plt.show()
#%%
# Normalizing testing images
def normalize_test(X_test):
    X_test = X_test.reshape([-1,28,28]).astype(float)/255
    X_test = (X_test-features_np.mean())/features_np.std()
    return X_test
X_test = normalize_test(X_test)
# expanding dimension of test
X_test = np.expand_dims(X_test,axis=1)
X_test = torch.from_numpy(X_test).float().to(device)
# %%
# Testing some images, sanity checkk
for img, lbl in test_dl:
    ttt=img,lbl
    for i in range(BATCH_SIZE):
        plt.imshow(torch.Tensor.cpu(ttt[0][i].data.reshape(28,28)),cmap='gray')
        plt.show()
        print('Prediction',torch.argmax(model(ttt[0][i].unsqueeze(0)),1).item())
    break
# Seems to working :)
# %%
#* Prepping submission file
submission_np = dataset_test.values
class SubmissionDataset(Dataset):
    def __init__(self, df, transform=None) -> None:
        self.features = df
        self.transform = transform

    def __getitem__(self, index):
        data = self.features[index]
        image = data.reshape(28,28).astype(np.uint8)
        if self.transform:
            image = self.transform(image)
        return image

    def __len__(self): return len(self.features)

submission_tmfs = tt.Compose([
    tt.ToTensor(),
    tt.Normalize(mean=[features_np.mean()/255], std=[features_np.std()/255],inplace=True)
])

submission_set = SubmissionDataset(submission_np,transform=submission_tmfs)
submission_dl = DeviceDataLoader(DataLoader(submission_set, batch_size=1, shuffle=False),device)
#%%
#* Checking image by image in submission set
ctr=0
for img in submission_dl:
    for i in range(1):
        print(img[i].shape)
        plt.imshow(torch.Tensor.cpu(img[i].data.reshape(28,28)),cmap='gray')
        plt.show()
        print('Prediction',int(torch.argmax(model(img[i].unsqueeze(0)),1).item()))
    if ctr>1: break
    ctr+=1
#%%
df_submission = pd.DataFrame(columns=['ImageId','Label'])
prediction = []
for img in submission_dl:
    prediction.append(int(torch.argmax(model(img[0].unsqueeze(0)),1).item()))
df_submission['Label'] = pd.Series(prediction)
#%%
df_submission['ImageId'] = df_submission.Label.index + 1
# %%
#df_submission.to_csv('submission_resnet.csv',index=False)
#%%
#torch.save(model.state_dict(),'resnet_digits_model.pth')


import argparse
import os
import random

import numpy as np
import torch
# from torch.optim import optimizer
from matplotlib import pyplot as plt
from torchvision import datasets, models, transforms
import torch.nn as nn
from torch import optim
import cv2 as cv
from PIL import Image

from tools.model import Net

from tools.flappy_bird_game import FlappyBird
from tqdm import trange

def args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--num_channel", type=int, default=4, help="num of channel of input imgs")
    parser.add_argument("--num_epoch", type=int, default=2000000, help="num of channel of input imgs")
    parser.add_argument("--num_class", type=int, default=2, help="num of action type for player")
    parser.add_argument("--lr", type=float, default=1e-6, help="learning rate")
    parser.add_argument("--img_size", type=int, default=84, help="image size for training")
    parser.add_argument("--epsilon", type=float, default=0.1, help="epsilon value")
    parser.add_argument("--replay_memory_size", type=int, default=10000, help="replay memory maximum size value")
    parser.add_argument("--batch_size", type=int, default=128, help="batch size")
    parser.add_argument("--gamma", type=float, default=0.99, help="gamma for deduction")

    args = parser.parse_args()
    return args

def seed_everything(seed):
    """
    This function we used to fix every part's random seed, to make sure the results are all the same for each run.
    """
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.backends.cudnn.deterministic = True

def train(model, criterion, optimizer_ft, num_epochs):
    arg = args()  # get command line parameters
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")  # set device gpu or cpu

    environment = FlappyBird()
    image, reward, terminal = environment.next_frame(
        0)  # this method will return a frame of image and the reward value, also a bool to indicate if the bird hit the ground or the pipe
    # the parameter for the next_frame method is the action, there are two values to choose: 0 and 1, 0 is not fly while 1 is fly once.

    model.to(device)  # move model to gpu or cpu

    image = cv.cvtColor(cv.flip(np.rot90(image), 0),
                        cv.COLOR_BGR2GRAY)  # convert the image output from pygame frame into proper form
    transform = transforms.Compose([
        transforms.Resize((arg.img_size)),
        transforms.ToTensor(),
    ])  # resize image and convert to tensor.
    # scripted_transforms = torch.jit.script(transforms)
    image = cv.resize(image[:288, :int(512*0.79)], (arg.img_size, arg.img_size))
    image = transform(Image.fromarray(np.uint8(image)))  # image now is a transformed tensor
    image = image.to(device)  # move the image into cuda or cpu
    state = torch.cat(tuple(image for _ in range(4)))[None, :, :, :]

    epsilon_decrements = np.linspace(0.1, 1e-4, arg.num_epoch)
    Loss_list = []
    replay_memory = []  # to save a series of action
    for epoch in trange(num_epochs):
        pred = model(state)[0]  # get the action predict from model

        # here we use epsilon to avoid the model goes failed to train.
        random_action = random.random() <= epsilon_decrements[epoch]
        if random_action:
            action = random.randint(0, 1)
        else:
            action = torch.argmax(pred)  # convert to 0 or 1

        next_image, next_reward, next_terminal = environment.next_frame(
            action)  # step into next frame using the action predict from model.
        # transform the next image into proper tensor and unpack it to a state
        next_image = cv.cvtColor(cv.flip(np.rot90(next_image), 0),
                                 cv.COLOR_BGR2GRAY)
        transform = transforms.Compose([
            transforms.Resize((arg.img_size)),
            transforms.ToTensor(),
        ])
        next_image = cv.resize(next_image[:288, :int(512*0.79)], (arg.img_size, arg.img_size))
        next_image = transform(Image.fromarray(np.uint8(next_image)))
        next_image = next_image.to(device)
        next_state = torch.cat((state[0, 1:, :, :], next_image))[None, :, :, :]

        # current_pred = pred
        # next_pred = model(next_image)

        # add the pair to buffer (Replay Buffer)
        replay_memory.append([state, action, reward, next_state, terminal])
        if len(replay_memory) > arg.replay_memory_size:
            del replay_memory[0]  # delete pairs out of limit

        # random sample training data from buffer
        batch = random.sample(replay_memory, min(len(replay_memory), arg.batch_size))
        state_batch, action_batch, reward_batch, next_state_batch, terminal_batch = zip(*batch)

        # unpack batches
        state_batch = torch.cat(tuple(state for state in state_batch))
        action_batch = torch.from_numpy(
            np.array([[1, 0] if action == 0 else [0, 1] for action in action_batch], dtype=np.float32))
        reward_batch = torch.from_numpy(np.array(reward_batch, dtype=np.float32)[:, None])
        next_state_batch = torch.cat(tuple(state for state in next_state_batch))

        # put these batchs into gpu or cpu
        state_batch = state_batch.to(device)
        action_batch = action_batch.to(device)
        reward_batch = reward_batch.to(device)
        next_state_batch = next_state_batch.to(device)

        current_prediction_batch = model(state_batch)  # do inference on current state
        next_prediction_batch = model(next_state_batch) # get the prediction of action of next state

        y_batch = torch.cat(
            tuple(reward if terminal else reward + arg.gamma * torch.max(prediction) for reward, terminal, prediction in
                  zip(reward_batch, terminal_batch, next_prediction_batch)))  # set y to reward if dead, or to nest_states's q value times gamma aff reward

        q_value = torch.sum(current_prediction_batch * action_batch, dim=1)  # calculate Q value
        optimizer_ft.zero_grad()  # set gradient as zero
        # y_batch = y_batch.detach()
        loss = criterion(q_value, y_batch)  # calculate loss
        loss.backward()   # back prop to calculate the gradient
        optimizer_ft.step()  # use gradient descent to update the parameters of the model

        state = next_state  # update state
        Loss_list.append(loss)  # save this epoch's loss to memory

        print("Epoch: {}/{}, {}, Loss: {}, Epsilon {}, Reward: {}, Q-value: {}".format(
            epoch + 1,
            arg.num_epoch,
            ["KEEP", "JUMP"][action],
            loss,
            epsilon_decrements[epoch],
            reward,
            torch.max(pred)))  # Print the training log

    torch.save(model.state_dict(), "./model_save/flappy_bird.pt")  # save the well trained model

    # show the loss curve
    x = range(0, num_epochs)
    y = Loss_list
    plt.subplot(2, 1, 2)
    plt.plot(x, y, '.-')
    plt.xlabel('Train loss vs. epoches')
    plt.ylabel('Train loss')
    plt.show()
    plt.close()

##########

if __name__ == '__main__':
    arg = args()  # get command line parameters

    # model = models.resnet18()  # load resnet18 from pytorch
    # model = models.mobilenet_v3_small()
    # model.features[0][0] = nn.Conv2d(arg.num_channel, 16, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
    # # # model.conv1 = nn.Conv2d(arg.num_channel, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3),
    # # #                         bias=False)  # change the input img channel size at the first conv layer
    # model.classifier[3] = nn.Linear(1024, arg.num_class)  # The last layer of the nn, which output num_class values
    # model.fc = nn.Linear(512, arg.num_class)  # The last layer of the nn, which output num_class values
    model = Net()

    optimizer_ft = optim.SGD(model.parameters(), lr=arg.lr, momentum=0.9)  # SGD optimizer
    # exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=20, gamma=0.5)

    criterion = nn.MSELoss()  # MSE loss function
    num_epochs = arg.num_epoch  # number of epoch

    model_ft = train(model, criterion, optimizer_ft, num_epochs)  # call the training function


##
# Author        :   Fowzy Alsaud
# Assignment    :   # 5 Part 2
# Date          :   Nov, 25th, 2021 - 11/25/2021
# Description   :   Find the duplication parenthesis from the expression.
##

### Input test:
    #   str = '((x+y))+z'
    #       >> duplication parenthesis? NO so it's TRUE expression
    #   strs = (x+y)
    #       >> duplication parenthesis? NO so it's FALSE expression
    #   strs = '((x+y)+((z)))'
    #       >> duplication? YES so it's TRUE expression

# Experssion is false by default
expression=False
# Taking an input from the user
usrInput = input(str())
# Count left side Parenthesis
leftParenthesis = 0
# Count right side Parenthesis
rightParenthesis = 0
# reading the user input
for i in usrInput:
    if (i == '('):
        leftParenthesis+=1
    if(i == ')'):
        rightParenthesis+=1

# So if we have duplication of parenthesis then it should be an even number and is TRUE else is FALSE
if leftParenthesis%2 == 0 and rightParenthesis%2 == 0:
    expression=True
    print(expression)
else:
    print(expression)


import numpy as np
import matplotlib.pyplot as plt
#円周率の読み込み
import math
#ベッセル関数の読み込み
from scipy.special import jv

#円筒銅線の材料パラメーター

#電気伝導率σ
sigma = 1.0
#透磁率μ
mu = 1.0

#角周波数
omega = 10
#電流値
I=1.0
#銅線の半径
r_0=10

x = np.arange(-1*r_0,r_0 , 0.2) #x軸の描画範囲の生成。0から10まで0.05刻み。
y = np.arange(-1*r_0,r_0 , 0.2) #y軸の描画範囲の生成。0から10まで0.05刻み。

k= complex((-1j*omega*mu*sigma)**0.5)

#print(k)
X, Y = np.meshgrid(x, y)
r=np.sqrt(X**2+Y**2) #半径の定義

Z =k*I/(2*math.pi)* jv(0,k*r)/jv(1,k*r_0) # 表示する計算式の指定。等高線はZに対して作られる。
print(Z)
plt.pcolormesh(X, Y, Z, cmap='hsv') # 等高線図の生成。cmapで色付けの規則を指定する。
#plt.pcolor(X, Y, Z, cmap='hsv') # 等高線図の生成。cmapで色付けの規則を指定する。

pp=plt.colorbar (orientation="vertical") # カラーバーの表示
pp.set_label("Label", fontname="Arial", fontsize=24) #カラーバーのラベル

plt.xlabel('X', fontsize=24)
plt.ylabel('Y', fontsize=24)

plt.show()


from tabulate import tabulate
from pathlib import Path
import time
import sys

class PathwayToGlory:
    unchecked_pycharm_paths = [
                '/home/user/.java/.userPrefs/jetbrains/pycharm',
                '/var/lib/snapd/sequence/pycharm-professional.json',
                '~/.local/share/applications/jetbrains-pycharm.desktop',
                '~/.gnome/apps/jetbrains-pycharm.desktop',
                '~/.PyCharm*/',
                '/opt/pycharm*/',
                '/usr/local/bin/pycharm'
    ]

    def __init__(self):
        print('Checking Jetbrains Paths . . .')
        time.sleep(1)

    def get_paths(self, pycharm=None, webstorm=None):
        existing_paths = []

        if pycharm:
            for i in self.unchecked_pycharm_paths:
                if Path(i).exists():
                    existing_paths.append(Path(i))
                else:
                    continue
            return existing_paths
        elif webstorm:
            return 'Suan webstorm yok malesef'
        else:
            return 'Secenek giriniz: PyCharm veya Webstorm hangisi amk ?????'

class JetbrainsDeletion(PathwayToGlory):
    def __init__(self):
        super(JetbrainsDeletion, self).__init__()

        print('\n')
        print('###########################################################')
        print('Jetbrains Deletion')
        print('###########################################################')
        time.sleep(.5)

        self.paths = self.get_paths(pycharm=True)
        if self.paths:
            print('Matches found.')
            i = input("Do you want to delete? (y/n): ")
            self.question(i)
        else:
            print('Dosyalar bulunamadi')

    def question(self, answer):
        if answer.lower() == 'yes' or answer.lower() == 'y':
            print('Dosyalar siliniyor...')
            self.deletion()
        elif answer.lower() == 'no' or answer.lower() == 'n':
            return None
        else:
            print('Sorry, I didn\'t understand you.')

    def deletion(self):
        paths = self.paths

        removed_pycharm_paths = []

        for i in paths:
            removable_list = []

            if Path(i).is_file():
                # silme suresi
                start_time = time.time()
                removable_list.append(Path(i))
                Path(i).unlink()
                end_time = time.time() - start_time

                # add process time to list
                removable_list.append(end_time)

                # check file after delete
                if Path(i).is_file():
                    removable_list.append('File not exists')
                else:
                    removable_list.append('deleted')

                # sutune ekleme
                removed_pycharm_paths.append(removable_list)

                # delete to removable_list
                removable_list = []
            elif Path(i).is_dir():
                # silme suresi
                start_time = time.time()
                removable_list.append(Path(i))
                Path(i).rmdir()
                end_time = time.time() - start_time

                # add process time to list
                removable_list.append(end_time)

                # check file after delete
                if Path(i).is_file():
                    removable_list.append('File not exists')
                else:
                    removable_list.append('deleted')

                # sutune ekleme
                removed_pycharm_paths.append(removable_list)

                # delete to removable_list
                removable_list = []
            else:
                removable_list.append(Path(i))
                # sutune ekleme
                removed_pycharm_paths.append(removable_list)
                removable_list.append(0)
                removable_list.append('File not exists')

                # delete to removable_list
                removable_list = []

        print(
            tabulate(
                removed_pycharm_paths,
                headers=['Path', 'process_time', 'status'],
                tablefmt='orgtbl'
            )
        )

if __name__ == '__main__':
    JetbrainsDeletion()


class MROError(Exception):

    """Cannot resolve MRO."""

    def __str__(self):
        return "%s: cannot resolve MRO" % self.args[0]

def mro(target_name, get_base_names, *args, **kwargs):
    """Resolve MRO for an item.

    target_name -- The name of the target item.
    get_base_names -- A callable to return the base names of an item. It should
                      have the interface:
                      [base1, ...] = get_base_names(name, *args, **kwargs)
    *args and **kwargs -- Optional arguments for get_base_names.

    Return a list e.g. [target_name, name, ...] with the correct method
    resolution order.

    """
    results = {}  # {name: mro_list, ...}
    base_names_of = {}  # {name: base_names_list, ...}
    dependents_of = {}
    stack = [target_name]  # list of names not yet in results
    while target_name not in results:
        name = stack.pop()
        if name in results:
            continue
        base_names_of[name] = get_base_names(name, *args, **kwargs)
        if base_names_of[name]:
            # "name" has parents
            if all([n in results for n in base_names_of[name]]):
                # All parents resolved. Time to merge them.
                results[name] = [name]
                # Walk the mro of each parent, breadth 1st.
                # Generate a list of selection sequences.
                seqs = []
                queue = list(base_names_of[name])
                while queue:
                    base_name = queue.pop(0)
                    for i in range(len(results[base_name])):
                        res = results[base_name][i:]
                        if res not in seqs:
                            seqs.append(res)
                    for result in results[base_name][1:]:
                        if result not in queue:
                            queue.append(result)
                # A successful candidate is one that is no longer a parent in
                # any of the selection sequences.
                while seqs:
                    cand_name = None
                    for seq in seqs:
                        cand_name = seq[0]
                        if not any(cand_name in s[1:] for s in seqs):
                            results[name].append(cand_name)
                            break
                        cand_name = None
                    if cand_name is None:
                        raise MROError(target_name)
                    for seq in list(seqs):
                        if cand_name == seq[0]:
                            seqs.remove(seq)
            else:
                # Some parents not resolved.
                # Put "name" and unresolved parents in stack.
                stack.append(name)
                dependents = dependents_of.get(name, []) + [name]
                for base_name in base_names_of[name]:
                    if base_name not in results:
                        if base_name in dependents:
                            raise MROError(target_name)
                        dependents_of[base_name] = dependents
                        stack.append(base_name)
        else:
            # "name" has no parents
            results[name] = [name]
    return results[target_name]

class _Test:

    """Self tests. Print results in TAP format.

    Ordering obtained from http://www.python.org/download/releases/2.3/mro/.

    """

    def __init__(self):
        self.base_names_of = {}
        self.test_num = 0
        self.test_plan = "1..11"

    def get_base_names(self, name):
        """Return base names of name."""
        return self.base_names_of[name]

    def good(self, key, cond):
        """Print ok or not ok."""
        self.test_num += 1
        if cond:
            print("ok %d - %s" % (self.test_num, key))
        else:
            print("not ok %d - %s" % (self.test_num, key))

    def test(self, key, actual, expect):
        """Assert equal."""
        self.good(key, actual == expect)

    def run(self):
        """Run tests."""
        print(self.test_plan)

        # Test good cases
        self.base_names_of["O"] = []
        self.test("zero", mro("O", self.get_base_names), ["O"])

        self.base_names_of["A1"] = ["O"]
        self.base_names_of["A2"] = ["A1"]
        self.base_names_of["A3"] = ["A2"]
        self.test(
            "single", mro("A3", self.get_base_names), ["A3", "A2", "A1", "O"]
        )

        self.base_names_of["B1"] = ["O"]
        self.base_names_of["C1"] = ["O"]
        self.base_names_of["X"] = ["C1", "A1"]
        self.base_names_of["Y"] = ["C1", "B1"]
        self.base_names_of["Z"] = ["Y", "X"]
        self.test(
            "diamond-1",
            mro("Z", self.get_base_names),
            ["Z", "Y", "X", "C1", "B1", "A1", "O"],
        )

        self.base_names_of["P"] = ["C1", "A1"]
        self.base_names_of["Q"] = ["B1", "C1"]
        self.base_names_of["R"] = ["Q", "P"]
        self.test(
            "diamond-2",
            mro("R", self.get_base_names),
            ["R", "Q", "B1", "P", "C1", "A1", "O"],
        )

        self.base_names_of["P"] = ["A1", "A2"]
        self.test(
            "triangle", mro("P", self.get_base_names), ["P", "A2", "A1", "O"]
        )

        self.base_names_of["P"] = ["A1", "O"]
        self.test(
            "triangle-2", mro("P", self.get_base_names), ["P", "A1", "O"]
        )

        self.base_names_of["P"] = ["O", "A1"]
        self.test(
            "triangle-3", mro("P", self.get_base_names), ["P", "A1", "O"]
        )

        self.base_names_of["D1"] = ["O"]
        self.base_names_of["E1"] = ["O"]
        self.base_names_of["K"] = ["D1", "A1"]
        self.base_names_of["L"] = ["D1", "B1", "E1"]
        self.base_names_of["M"] = ["A1", "B1", "C1"]
        self.base_names_of["N"] = ["M", "L", "K"]
        self.test(
            "complex",
            mro("N", self.get_base_names),
            ["N", "M", "L", "K", "D1", "A1", "B1", "C1", "E1", "O"],
        )

        # Test bad cases
        self.base_names_of["CYCLIC"] = ["CYCLIC"]
        try:
            mro("CYCLIC", self.get_base_names)
        except MROError as exc:
            self.test("cyclic", str(exc), str(MROError("CYCLIC")))
        else:
            self.good("cyclic", False)

        self.base_names_of["CYCLIC1"] = ["CYCLIC3"]
        self.base_names_of["CYCLIC2"] = ["CYCLIC1"]
        self.base_names_of["CYCLIC3"] = ["CYCLIC2"]
        try:
            mro("CYCLIC3", self.get_base_names)
        except MROError as exc:
            self.test("cyclic3", str(exc), str(MROError("CYCLIC3")))
        else:
            self.good("cyclic3", False)

        self.base_names_of["A1B1"] = ["A1", "B1"]
        self.base_names_of["B1A1"] = ["B1", "A1"]
        self.base_names_of["BAD"] = ["A1B1", "B1A1"]
        try:
            mro("BAD", self.get_base_names)
        except MROError as exc:
            self.test("bad", str(exc), str(MROError("BAD")))
        else:
            self.good("bad", False)

if __name__ == "__main__":
    _Test().run()


import pytest

from app.database.schemas.products_schemas import Product
from app.tests.basic_operations import BasicOperations
from app.tests.config import admin_user, base_url

user_data = admin_user

basic_operations = BasicOperations()

@pytest.mark.parametrize('status', [
    200, 400
])
def test_get_products(token, status, get_user):
    basic_operations.set_values(
        token=token,
        status=status,
        second_token=get_user,
        url=base_url,
        path="products/",
        schema=Product
    )
    basic_operations.get_items()

@pytest.mark.parametrize('product_name, status', [
    ("fanta", 200),
    ("sdkljfls;l", 200),  # not find and return empty []
    ("fanta", 400)  # invalid user
])
def test_search_products(token, get_user, status, product_name):
    basic_operations.set_values(
        token=token,
        status=status,
        second_token=get_user,
        url=base_url,
        path=f"products/search/{product_name}",
        schema=Product
    )
    basic_operations.get_items()


from django.utils import timezone
# import serializers
from rest_framework import serializers
from patients.models import Patient, PatientReport, PatientDependentReport, ONLINE
from accounts.models import User
from accounts.serializers import UserInfoSerializer
from doctors.models import Doctor

from utils.payment_module import Payment

class DependeeInfoSerializer(serializers.ModelSerializer):
    age = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = PatientDependentReport
        fields = [
            'id',
            'dependent_names',
            'dependent_relationship',
            'dependent_bithdate',
            'age',
            'gender',
            'dependent_blood_group',
            # 'chronic_diseases',
            'dependent_alergies',
            'phone_number',
            'email',
            'address',
            'created_at',
        ]

    def get_age(self, obj):
        if obj.dependent_bithdate:
            return  timezone.now().year - obj.dependent_bithdate.year
        return None

class PatientInfoSerializer(serializers.ModelSerializer):
    personal_information = serializers.SerializerMethodField()
    dependents_profile = DependeeInfoSerializer(
        source="patient_dependents", many=True, read_only=True)

    class Meta:
        model = Patient
        fields = [
            # 'id',
            # 'patient_username',
            'blood_group',
            'alergies',
            'chronic_diseases',
            'habits',
            'current_prescription',
            'is_pregnant',
            'created_at',
            'personal_information',
            'dependents_profile',
        ]

    def get_personal_information(self, obj):
        user = User.objects.get(username=obj)
        serializer = UserInfoSerializer(user, context=self.context)

        return serializer.data

class PatientReportSerializer(serializers.ModelSerializer):
    consultated_by_doctor = serializers.UUIDField(required=False, allow_null=True)
    patient_username = serializers.UUIDField(required=False, allow_null=True)

    class Meta:
        model = PatientReport
        fields = [
            'id',
            'patient_username',
            'pain_area',
            'symptoms',
            'consultated_by_doctor',
            'consultation_type',
            'results',
            'prescription',
            'recommended_tests',
            'recommendation',
            'created_at',
        ]
    def create(self, validated_data):
        patient_id = validated_data.pop('patient_username', None)
        doctor = validated_data.pop('consultated_by_doctor', None)

        if not patient_id:
            try:
                user_id = self.context['request'].user.id
                patient = Patient.objects.get(patient_username__id=str(user_id))
            except Patient.DoesNotExist:
                raise serializers.ValidationError("Patient not found")

        elif patient_id and not doctor:
            doctor = self.context['request'].user.id
            patient = Patient.objects.get(id=str(patient_id))
        else:
            # AI consultation
            try:
                patient = Patient.objects.get(id=str(patient_id))
            except User.DoesNotExist:
                raise serializers.ValidationError("Patient not found")

        if not doctor:
            doctor, created = User.objects.get_or_create(username="Dr Emile", user_type=User.DOCTOR)
            consultated_by = Doctor.objects.get(user=doctor)
        else:
            # consultated_by = validated_data.get('consultated_by_doctor')
            try:
                consultated_by = Doctor.objects.get(user__id=str(doctor))
                if not validated_data.get('consultation_type'):
                    validated_data['consultation_type'] = ONLINE
            except Doctor.DoesNotExist:
                raise serializers.ValidationError("Only doctors can consult patients")

        if consultated_by.user == patient.patient_username:
            raise serializers.ValidationError("You can't consult yourself.")

        instance = PatientReport.objects.create(patient_username=patient, consultated_by_doctor=consultated_by, **validated_data)
        return instance

class PatientDependentReportSerializer(serializers.ModelSerializer):
    # user = serializers.CharField(read_only=True)
    consulted_by_doctor = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    dependent_relationship = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    patient_username = serializers.UUIDField(required=False, allow_null=True)

    class Meta:
        model = PatientDependentReport
        fields = [
            'id',
            'patient_username',
            "dependent_names",
            "dependent_relationship",
            "dependent_bithdate",
            "phone_number",
            "address",
            "email",
            "dependent_blood_group",
            "dependent_alergies",
            'dependent_symptoms',
            'consulted_by_doctor',
            'consultation_type',
            'dependent_results',
            'dependent_prescription',
            'dependent_recommended_tests',
            'dependent_recommendation',
            'created_at',
        ]

    def create(self, validated_data):
        user_id = self.context['request'].user.id
        account_holder = validated_data.pop('patient_username', None)

        if not account_holder:
            # AI consultation
            doctor, created = User.objects.get_or_create(username="Dr Emile", user_type=User.DOCTOR)
            consultated_by = Doctor.objects.get(user=doctor)

            patient = Patient.objects.get(patient_username__id=user_id)

        elif account_holder:
            consultated_by = self.context['request'].user.id
            try:
                consultated_by = Doctor.objects.get(user__id=str(consultated_by))
                patient = Patient.objects.get(id=str(account_holder))
                if not validated_data.get('consultation_type'):
                    validated_data['consultation_type'] = ONLINE
            except Patient.DoesNotExist:
                raise serializers.ValidationError("Patient not found")
            except Doctor.DoesNotExist:
                raise serializers.ValidationError("Only doctors can consult patients")
        else:
            raise serializers.ValidationError("A dependee should have dependents who is the account holder")

        # if not validated_data.get('consultated_by_doctor'):
        #     doctor, created = User.objects.get_or_create(username="Dr Emile", user_type=User.DOCTOR)
        #     consultated_by = Doctor.objects.get(user=doctor)
        # else:
        #     consultated_by = validated_data.get('consultated_by_doctor')

        # patient = Patient.objects.get(patient_username=user)
        instance = PatientDependentReport.objects.create(
            patient_username=patient, consulted_by_doctor=consultated_by, dependent_relationship=self.context['request'].GET.get("choice"), **validated_data)
        return instance

class PatientSerializer(serializers.ModelSerializer):
    patient_previous_reports = PatientReportSerializer(
        source="patient_reports", many=True, read_only=True)
    patient_dependents_repports = PatientDependentReportSerializer(
        source="patient_dependents", many=True, read_only=True)
    # patient_personal_information = serializers.SerializerMethodField()
    patient_profile = serializers.SerializerMethodField()
    class Meta:
        model = Patient
        fields = [
            'id',
            # "patient_personal_information",
            "patient_profile",
            'patient_previous_reports',
            'patient_dependents_repports',
        ]

    # def get_patient_personal_information(self, obj):
    #     serializer = UserInfoSerializer(obj.patient_username)
    #     return serializer.data

    def get_patient_profile(self, obj):
        serializer = PatientInfoSerializer(obj.patient_username, context=self.context)
        return serializer.data

class PatientEditProfileSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(read_only=True)

    def validate(self, attrs):
        if self.context['request'].user.gender == User.MALE:
            if attrs.get('is_pregnant'):
                raise serializers.ValidationError("You can't be pregnant")
        return super().validate(attrs)

    class Meta:
        model = Patient
        fields = [
            'id',
            'patient_username',
            'blood_group',
            'alergies',
            'chronic_diseases',
            'habits',
            'current_prescription',
            'is_pregnant',
        ]

class PatientPaymentStatusSerializer(serializers.Serializer):
    reference_key = serializers.CharField(required=True)
    kind = serializers.CharField(required=True)
    phone_number = serializers.CharField(required=True, max_length=10)

    def validate(self, data):
        if data.get('kind').upper() not in ['CASHIN', 'CASHOUT']:
            raise serializers.ValidationError("Invalid kind")
        return data

class PatientCashInSerializer(serializers.Serializer):
    phone_number = serializers.CharField(required=True, max_length=10)
    amount = serializers.IntegerField(required=True)

    def validate(self, data):
        if not data.get('phone_number').isdigit() :
            raise serializers.ValidationError("Enter a valid phone number please")
        return data


class ClaseGenerica:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

    def __str__(self):
        attrs = ["{}={}".format(k, v) for (k, v) in self.__dict__.items()]
        classname = self.__class__.__name__
        return "%s: %s" % (classname, ",".join(attrs))

# Codigo de pruebas
c = ClaseGenerica(foo='bar', x=3, y=4, z=5)

assert(c.foo == "bar")
assert(c.x == 3)
assert(c.y == 4)
assert(c.z == 5)
print(c)            # Salida esperada: ClaseGenerica: x=3,y=4,z=5,foo=bar. La lista de miembros no tiene porque ir en ese orden


REVERSED_DIRECTIONS = [
    (-1, -2), (1, -2),
    (-2, -1), (2, -1)
]  # x是上下, y是左右

class Solution:
    """
    @param grid: a chessboard included 0 and 1
    @return: the shortest path
    """

    def shortestPath2(self, grid):
        if not grid or not grid[0]:
            return -1

        m, n = len(grid), len(grid[0])

        # state：dp[i][j]代表从0 0 到i j的最少步数
        dp = [[float('inf')] * n for _ in range(m)]

        # initialize：起点是0
        dp[0][0] = 0

        # function
        for j in range(n):  # 必须先写n，因为向右走固定
            for i in range(m):
                # 如果是barrier，直接跳过
                if grid[i][j] == 1:
                    continue
                # 然后看前一步谁最小, 注意，x是上下，y是左右，我们看前一步
                for dx, dy in REVERSED_DIRECTIONS:
                    pre_x, pre_y = i + dx, j + dy
                    # check the range:
                    if 0 <= pre_x < m and 0 <= pre_y < n:
                        # 打擂台选最小
                        dp[i][j] = min(dp[i][j], dp[pre_x][pre_y] + 1)

        # answer
        if dp[m - 1][n - 1] == float('inf'):
            return -1
        return dp[m - 1][n - 1]


from django.db import models
from django.db.models.signals import post_save
from datetime import date
from .Azurefunctions import *

# Create your models here.

class VinNumber(models.Model):
    vinNumber = models.CharField(max_length=100, primary_key=True)
    vedFile = models.FileField()

class EcuName(models.Model):
    ecuName = models.CharField(max_length=100, primary_key=True)

class ScomoID(models.Model):
    scomoID = models.CharField(max_length=100, primary_key=True)
    ecuName = models.ForeignKey(EcuName, on_delete=models.CASCADE)

class ContentFile(models.Model):
    FileName = models.CharField(max_length=200, primary_key=True)
    BrowsFile = models.FileField()
    FileType = models.CharField(max_length=200)
    Date = models.DateTimeField()
    ScomoID = models.ForeignKey(ScomoID, on_delete=models.CASCADE)

class FwVersion(models.Model):
    sourceVersion = models.CharField(max_length=100)
    TargetVersion = models.CharField(max_length=100)
    scomoID = models.ForeignKey(ScomoID, on_delete=models.CASCADE)

class CampaignDetail(models.Model):
    campaignName = models.CharField(max_length=300, primary_key=True)
    CampaignType = models.CharField(max_length=300)
    startdate = models.DateField()
    endDate = models.DateField()
    vinNumber = models.ManyToManyField(VinNumber)
    ecuNames = models.ManyToManyField(EcuName)
    scomoID = models.ManyToManyField(ScomoID)
    packageFile = models.ManyToManyField(ContentFile)
    fwversion = models.ManyToManyField(FwVersion)

class dynamichmi(models.Model):
    campaignName = models.ForeignKey(CampaignDetail, on_delete=models.CASCADE)
    xmlfile = models.FileField()

class DiscardedVin(models.Model):
    discardedVin_id = models.AutoField(primary_key=True)
    vin = models.CharField(max_length=300)
    campaignName = models.ForeignKey(CampaignDetail, on_delete=models.CASCADE)

def launchCampaign1(CampaignDetail_id_object, vin_number_list):
    dataStructureDict = {}
    Final_dict = {}
    ecu_mapping = {'IVI': 'RDO', 'METER': 'TDB', 'HUD': 'HMD', 'IVC': 'TCU', 'ADAS': 'DAS'}
    for value in CampaignDetail_id_object:
        startDate = value.startdate
        end_date = value.endDate
        vinNumber_twinList = []
        for vin in vin_number_list:
            vinNumber_twinList.append(get_twin(vin))
        flag = 0
        scomo_set = set()
        for s in value.scomoID.all():
            temp = {}
            s.scomoID_name = s.scomoID.replace('.', '_').lower()
            scomo_name_fileref = s.scomoID_name + "_fileref"
            scomo_name_fileref = scomo_name_fileref.lower()

            # ecuname.
            scomo_id_object = ScomoID.objects.all().filter(scomoID=s.scomoID)
            for values in scomo_id_object:
                ecu_name_object = values.ecuName
                ecu_name_without_map = ecu_name_object.ecuName

            # scomo_id package file name.
            file_name = ""
            for values in value.packageFile.all():
                if values.ScomoID.scomoID == s.scomoID:
                    file_name = values.FileName

            # firmware sorce and target version
            source_version = ""
            target_version = ""
            for values in value.fwversion.all():
                if values.scomoID.scomoID == s.scomoID:
                    source_version = values.sourceVersion
                    target_version = values.TargetVersion

            # update twin according to reported property
            temp[s.scomoID_name] = target_version
            temp[scomo_name_fileref] = file_name
            ecu_name = ecu_mapping[ecu_name_without_map]
            dataStructureDict[ecu_name] = temp

            for k in vinNumber_twinList:
                source_version_fromDevice = get_reported_property(k, ecu_name, s.scomoID_name)
                if source_version != source_version_fromDevice:
                    flag = 1
                    scomo_set.add(s.scomoID_name)

        if flag == 0:
            update_twin(dataStructureDict, vin_number_list)
            return True
        if flag == 1:
            return False

# signal function
def save_post(sender, instance, **kwargs):
    vin_number = instance.vinNumber
    DiscardedVinObjects = DiscardedVin.objects.filter(vin=vin_number)
    vin_list = [vin_number]
    if DiscardedVinObjects:
        for value in DiscardedVinObjects:
            startdate = value.campaignName.startdate
            enddate = value.campaignName.endDate
            if startdate <= date.today() <= enddate:
                list_obj = [value.campaignName]
                if launchCampaign1(list_obj, vin_list):
                    vin_number_object = VinNumber.objects.all().filter(vinNumber=vin_number)
                    for vin_object in vin_number_object:
                        value.campaignName.vinNumber.add(vin_object)
                    DiscardedVinObjects.delete()

# signals
post_save.connect(save_post, sender=VinNumber)


import numpy as np
from collections import Counter

def filter_canditates(canditates,search_value,column):
	if len(canditates) ==1:
		return canditates
	for c_id in range(len(canditates)-1,-1,-1):
		if canditates[c_id][column] != search_value:
			canditates = np.delete(canditates, c_id, 0)
	return canditates
oxygen_test = ''
co2_test = ''
with open('input.txt') as f:
	lines = f.readlines()
	binary_input = np.array([list(line.rstrip()) for line in lines])
	oxy_canditates=binary_input
	co2_canditates=binary_input
	for column in range(len(binary_input[0])):
		counted_binary_co2 = Counter(co2_canditates[:,column])
		counted_binary_oxy = Counter(oxy_canditates[:,column])
		search_value_co2 = str(int(not counted_binary_co2['0'] <= counted_binary_co2['1']))
		search_value_oxy = str(int(not counted_binary_oxy['0'] > counted_binary_oxy['1']))
		co2_canditates = filter_canditates(co2_canditates,search_value_co2,column)
		oxy_canditates = filter_canditates(oxy_canditates,search_value_oxy,column)

co2 = int(''.join(co2_canditates[0]),2)
oxygen = int(''.join(oxy_canditates[0]),2)
print(co2,oxygen)
print(co2*oxygen)


"""Lead Field computation functions."""

# Authors: Mainak Jas <mainakjas@gmail.com>
#
# License: BSD (3-clause)

import os
import zipfile
from mne.datasets.utils import _fetch_file

def fetch_omega_dataset(base_path):
    src_url = ('https://www.dropbox.com/sh/feqtjna1ymok445/'
               'AACStCwNgIlG3VcePkkTALgBa?dl=1')

    data_path = os.path.join(base_path, 'sample_BIDS_omega')
    target = os.path.join(base_path, 'sample_BIDS_omega.zip')

    if not os.path.exists(data_path):
        if not os.path.exists(target):
            _fetch_file(src_url, target)
        zf = zipfile.ZipFile(target, 'r')
        print('Extracting files. This may take a while ...')
        zf.extractall(path=data_path)
        os.remove(target)
    return os.path.abspath(data_path)


# The logic in these functions are adapted from the forward() implementations of various
# Causal LM models in the Transformers library. Each model has some variation on
# the way logits and labels are preprocessed for the loss and it is not currently
# abstracted to a callable function.
import torch

def _preprocess_impl_XGLMForCausalLM(model, lm_logits, labels):
    # shift labels and add a pad token to the end
    shift_labels = labels.new_zeros(labels.shape)
    shift_labels[:, :-1] = labels[:, 1:].clone()
    shift_labels[:, -1] = model.config.pad_token_id
    return lm_logits, shift_labels

def _preprocess_impl_GPT2LMHeadModel(model, lm_logits, labels):
    # Shift so that tokens < n predict n
    shift_logits = None if lm_logits is None else lm_logits[..., :-1, :].contiguous()
    shift_labels = labels[..., 1:].contiguous()
    return shift_logits, shift_labels

def _preprocess_impl_GPTNeoForCausalLM(model, lm_logits, labels):
    # Compute loss in fp32 to match with mesh-tf version
    # https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179
    lm_logits = None if lm_logits is None else lm_logits.to(torch.float32)

    # Shift so that tokens < n predict n
    shift_logits = None if lm_logits is None else lm_logits[..., :-1, :].contiguous()
    shift_labels = labels[..., 1:].contiguous()
    return shift_logits, shift_labels

def _preprocess_impl_GPTJForCausalLM(model, lm_logits, labels):
    # Shift so that tokens < n predict n
    shift_logits = None if lm_logits is None else lm_logits[..., :-1, :].contiguous()
    shift_labels = labels[..., 1:].contiguous()
    return shift_logits, shift_labels

_preprocess_impl = {
    "XGLMForCausalLM": _preprocess_impl_XGLMForCausalLM,
    "GPT2LMHeadModel": _preprocess_impl_GPT2LMHeadModel,
    "GPTNeoForCausalLM": _preprocess_impl_GPTNeoForCausalLM,
    "GPTJForCausalLM": _preprocess_impl_GPTJForCausalLM
}

def preprocess_logits_and_labels_for_crossentropy(model, lm_logits, labels):
    model_type = type(model).__name__

    if model_type in _preprocess_impl:
        impl = _preprocess_impl[model_type]
        lm_logits, labels = impl(model, lm_logits, labels)

    return lm_logits, labels


class Book():
    def __init__(self, author, name, year, item):
        self.author = author
        self.name = name
        self.year = year
        self.item = item

    def __repr__(self):
        return (self.name)

def main():
    book1 = Book('red', 'final', 1982, 'fictono')
    print(repr(book1))
    print(book1.author, book1.year)
    print(str(book1))

if __name__ == '__main__':
    main()


from ortools.sat.python import cp_model

class DiGraphSolver:

    def __init__(self, desc):
        self.model  = cp_model.CpModel()
        self.status = cp_model.UNKNOWN
        self.timing = None

        # AddCircuit needs a numeric index for each node.
        # Here's two lazy key->index / index->key lookups.
        self.keys = {k: i for i, k in enumerate(desc.nodes.keys()) }
        self.revs = {i: k for k, i in self.keys.items() }

        # Determine the objective of the problem
        self.min_maxing = desc.steps in ['min', 'max']
        self.find_max   = desc.steps == 'max'
        self.step_count = desc.steps if not self.min_maxing else None

        # Determine the start and stop nodes
        self.start = self.keys[desc.start]
        self.stop = self.keys[desc.stop]

        # Store the nodes dict in it's indexed form.
        self.nodes = {self.keys[head]: [self.keys[t] for t in tails] for head,tails in desc.nodes.items()}

        self.arcs = []
        self.vars = []
        self.result = []

    def setup(self):
        # AddCircuit uses a list of directed arcs as tuples: each is (head, tail, boolVariable)
        # where the  boolVar truth value represents if the arc is used or not used.
        # List comprehension: for each head(node), create an arc for each of it's tails.
        self.arcs = [
            (head,tail, self.model.NewBoolVar(f'{head}:{tail}')) for head, tails in self.nodes.items() for tail in tails
        ]

        # vars is a list of all the arcs defined in the problem.
        self.vars = [arc[2] for arc in self.arcs]

        # Add self loops for all *optional* nodes (because AddCircuit requires a Hamiltonian Circuit)
        # for this example, that's everywhere except for 'start' and 'stop'
        # We just use the keys of self.revs (the index values).
        loops = [(n, n, self.model.NewBoolVar(f'{n}:{n}')) for n in self.revs if n not in [self.start, self.stop]]
        self.arcs += loops

        # connect the stop variable to the start variable as a dummy arc to complete the hamiltonian circuit.
        # Because start and stop are not self-closing (non-optional), we don't need to set truth values.
        loop = (self.stop, self.start, self.model.NewBoolVar(f'loop'))
        self.arcs.append(loop)

        # Now add the circuit as a constraint.
        self.model.AddCircuit(self.arcs)

        # Now set the objective.
        if self.min_maxing:
            if self.find_max:
                 self.model.Maximize(sum(self.vars))  # look for the longest network.
            else:
                self.model.Minimize(sum(self.vars))   # look for the shortest network.
        else:
            self.model.Add(sum(self.vars) == self.step_count)

    def solve(self) -> bool:
        cp_solver = cp_model.CpSolver()
        cp_solver.parameters.max_time_in_seconds = 1
        cp_solver.parameters.num_search_workers = 12
        self.status = cp_solver.Solve(self.model)
        return self.summarise(cp_solver)

    def summarise(self, cp_solver) -> bool:
        if self.status in (cp_model.OPTIMAL, cp_model.FEASIBLE):
            self.store(cp_solver)
            return True
        else:
            if self.status == cp_model.INFEASIBLE:
                print(f"Challenge for {self.step_count} arc{'s ' if self.step_count > 1 else ' '}is infeasible after {cp_solver.WallTime()}s.")
            else:
                print(f"Solver ran out of time.")
            return False

    def store(self, cp_solver):
        self.timing = cp_solver.WallTime()
        used = [arc for arc in self.arcs if cp_solver.Value(arc[2])]
        arc = None, self.start
        while True:
            arc = next((link for link in used if link[0] == arc[1]), None)
            self.result.append(self.revs[arc[0]])
            if arc[1] == self.start:
                break
        self.step_count = len(self.result) - 1

    def show(self):
        print(f"{'-'.join(self.result)}")

class RandomDigraph:
    """
        define a problem.
        51 nodes, labelled 'a' ... 'Z'
        start at 'a', stop at 'Z'
        Each node other than 'Z' has a 4 outgoing arcs (random but not going to 'a')
    """
    def __init__(self):
        from random import sample  #
        names = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        arcs = 4
        self.steps = 1
        self.start = 'a'
        self.stop = 'Z'
        but_first = set(names) ^ set(self.start)
        self.nodes = {v: sample(but_first - set(v), arcs) for v in names}
        self.nodes[self.stop] = []

    def print_nodes(self):
        for key, value in self.nodes.items():
            print(f'{key}: {value}')

def solve_with_steps(problem, steps, show) -> int:
    problem.steps = steps
    solver = DiGraphSolver(problem)
    solver.setup()
    if solver.solve() and show:
        solver.show()
    return solver.step_count

def solve_az_paths_of_a_random_digraph():
    problem = RandomDigraph()
    problem.print_nodes()
    print()
    min_steps = solve_with_steps(problem, 'min', True)
    max_steps = solve_with_steps(problem, 'max', False)
    for p in range(min_steps+1, max_steps+1):
        solve_with_steps(problem, p, True)

if __name__ == '__main__':
    solve_az_paths_of_a_random_digraph()


from argparse import ArgumentParser
from ast import Bytes
from pika import BlockingConnection, ConnectionParameters
from sys import exit as sys_exit
from os import _exit as os_exit
from decimal import Decimal
from numpy.random import normal
from time import sleep
import random

def init_parser() -> ArgumentParser:
    parser = ArgumentParser(
        usage="%(prog)s -w/--mean_wait [TIME] -e/--error [RATE]",
        description="Consume text messages of variable size up to 100 \
            characters. Waits a random period of time normally distributed \
            around a given mean before sending out the consumed message. \
            Provides configurable error rate to simulate message failures."
    )

    parser.add_argument(
        "-v", "--version", action="version",
        version=f"{parser.prog} version 1.0.0"
    )
    parser.add_argument("-w", "--mean_wait", type=int, required=True,
                        choices=range(0, 181), metavar="[0-180]",
                        help="mean amount in seconds to randomly wait before \
                             sending")
    parser.add_argument("-e", "--error", type=Decimal, required=True,
                        metavar="decimal from [0-1] inclusive",
                        help="percentage of message sends that should result \
                             in failure")

    return parser

def is_error(rate) -> bool:
    return random.random() < rate

def test_error_range(args, parser) -> None:
    if args.error < 0 or args.error > 1:
        parser.error("Error must be a decimal value between 0 and 1 \
                     inclusive.")

def main() -> None:
    parser = init_parser()
    args = parser.parse_args()

    test_error_range(args, parser)

    # consider switching to async SelectConnection
    connection = BlockingConnection(ConnectionParameters("localhost", 5672))
    channel = connection.channel()

    channel.queue_declare(queue="emergency", durable=True)
    channel.queue_declare(queue="emergency-failures", durable=True)

    def callback(ch, method, properties, body) -> Bytes:
        # normally distributed, where loc is the mean
        # this can be between 0 and 180 seconds
        wait_time = normal(loc=args.mean_wait)

        # normalized values can sometimes be negative
        if wait_time < 0:
            wait_time = 0
        sleep(wait_time)

        if not is_error(args.error):
            ch.basic_ack(delivery_tag=method.delivery_tag)
            print(" [x] Acked %r" % body)
        else:
            print(" [o] Rejected: %r" % body)
            ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
            ch.basic_publish(exchange="", routing_key="emergency-failures",
                             body=body)

    channel.basic_consume(queue="emergency", on_message_callback=callback,
                          auto_ack=False)

    try:
        channel.start_consuming()
    finally:
        connection.close()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted by user!')
        try:
            sys_exit(0)
        except SystemExit:
            os_exit(0)


import bcsv, binascii, csv, html, importlib, json, os, os.path, sys

in_path = sys.argv[1]
out_dir = sys.argv[2]
specs_file = sys.argv[3]
specs = importlib.import_module(specs_file.replace('.py', ''))

csv_dir = out_dir + '/csv'
json_dir = out_dir + '/json'
html_dir = out_dir + '/html'

if not os.path.exists(csv_dir):
	os.makedirs(csv_dir)
if not os.path.exists(json_dir):
	os.makedirs(json_dir)
if not os.path.exists(html_dir):
	os.makedirs(html_dir)

for filename, row_class in specs.lookup.items():
	bits = []
	bits.append('<!DOCTYPE html>')
	bits.append('')
	bits.append('')
	objs = []

	bits.append('
%s
' % filename)

	b = bcsv.File(row_class)
	with open('%s/%s' % (in_path, filename), 'rb') as f:
		b.load(f.read())

	csvw = csv.writer(open('%s/%s.csv' % (csv_dir, filename.replace('.bcsv', '')), 'w'))

	bits.append('
')
	bits.append('
')
	for field in row_class.fields():
		bits.append('%s	' % field)
	csvw.writerow(row_class.fields())
	bits.append('
')
	for row in b.rows:
		bits.append('
')
		obj = {}
		crow = []
		for field in row_class.fields():
			value = getattr(row, field)
			if isinstance(value, bytes):
				htmlValue = binascii.hexlify(value).decode('ascii')
				dataValue = htmlValue
			elif isinstance(value, tuple):
				htmlValue = "%s" % (html.escape(value[1], True), html.escape(value[0]))
				dataValue = value
			else:
				htmlValue = repr(value)
				dataValue = htmlValue
			bits.append('%s	' % htmlValue)
			crow.append(dataValue)
			obj[field] = dataValue
		bits.append('
')
		objs.append(obj)
		csvw.writerow(crow)
	bits.append('
')

	bits.append('')
	bits.append('')

	with open('%s/%s.html' % (html_dir, filename.replace('.bcsv', '')), 'w') as f:
		for line in bits:
			f.write(line)
			f.write('\n')
	with open('%s/%s.json' % (json_dir, filename.replace('.bcsv', '')), 'w') as f:
		json.dump(objs, f, indent=4)


class StockSpanner:

    def __init__(self):
        self.stack = []

    def next(self, price: int) -> int:
        curr = 1

        while self.stack and self.stack[-1][0] <= price:
            prior, streak = self.stack.pop()
            curr += streak
        self.stack.append((price, curr))
        return curr

# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)


# coding: utf-8
from django.contrib.auth import logout
from social_auth.models import UserSocialAuth
from github import Github
from models import UserProfile
from django.http import HttpResponseRedirect, HttpResponse
from sockets import ChatNamespace
from socketio import socketio_manage

def disconnect(request):
    logout(request)
    return HttpResponseRedirect('/chat/index.html')

def login(request):
    if request.user.is_authenticated():
        github_user = get_github_user(request.user)
        try:
            request.user.first_name = github_user.name
            if github_user.email:
                request.user.email = github_user.email
            request.user.save()

            profile = request.user.get_profile()
            #update avatar_url of github
            profile.avatar_url = github_user.avatar_url

            profile.save()
        except UserProfile.DoesNotExist:
            #create userprofile
            UserProfile.objects.create(user=request.user,
                avatar_url=github_user.avatar_url)
    return HttpResponseRedirect('/chat/index.html')

def get_github_user(user):
    instance = UserSocialAuth.objects.filter(provider='github').get(user_id=user)
    userGitHub = Github(instance.tokens['access_token'])
    return userGitHub.get_user()

def socketio(request):
    socketio_manage(request.environ,
        {
            '': ChatNamespace,
        }, request=request
    )
    return HttpResponse()


import numpy as np
import vispy.plot as vp

def main():
    points = np.random.randn(10, 2)

    fig = vp.Fig(show=False)
    fig[0, 0].plot(points, width=0, face_color=(.8, .4, .2, .5), edge_color=None, marker_size=100.)

    fig.show(run=True)

if __name__ == '__main__':
    main()


import json
import numpy as np

PREDICTION_THRESHOLD = 0.5

def gaussian(x, mu=10, sigma=1.5):
    return np.exp(-((x - mu) ** 2) / (2 * sigma ** 2))

def softmax(x):
    """
    :param x: array of predictions
    :return: array of predictions after softmax activation
    """
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=1, keepdims=True)

def relu(x):
    """
    :param x: array of predictions
    :return: array of predictions after relu activation
    """
    return np.maximum(0, x)

def sign(x):
    """
    :param x: array of predictions
    :return: array of predictions after sign activation
    """
    return np.sign(x)

def sigmoid(x):
    """
    :param x: array of predictions
    :return: array of predictions after sigmoid activation
    """
    return 1 / (1 + np.exp(-x))

def leaky_relu(x):
    """
    :param x: array of predictions
    :return: array of predictions after leaky relu activation
    """
    return np.maximum(0.1 * x, x)

class NeuralNetwork:
    def __init__(self, model, weights, biases):
        self.weights = []
        self.biases = []  # New line
        self.activations = []
        for i in range(len(model)):
            self.weights.append(np.array(weights[i]).reshape(model[i][0], model[i][1]))
            self.biases.append(biases[i])  # Update this line
            if model[i][2] == 'relu':
                self.activations.append(relu)
            elif model[i][2] == 'sigmoid':
                self.activations.append(sigmoid)
            elif model[i][2] == 'sign':
                self.activations.append(sign)
            elif model[i][2] == 'leaky_relu':
                self.activations.append(leaky_relu)
            elif model[i][2] == 'softmax':
                self.activations.append(softmax)
            elif model[i][2] == 'gaussian':
                self.activations.append(gaussian)
            else:
                raise Exception(f"Unknown activation function {model[i][2]}")

    def propagate(self, data):
        input_data = data
        z = None
        for i, weights in enumerate(self.weights):
            z = np.dot(input_data, weights) + self.biases[i]  # Updated line
            if self.activations[i] != 0:
                z = self.activations[i](z)
            input_data = z
        return np.ravel(z)

def load_network(filename):
    with open(filename, 'r') as file:
        data = json.load(file)

    weights = np.array(data['weights'][0])
    biases = data['biases'][0]
    activation_name = data['activations'][0]
    model = [[weights.shape[0], weights.shape[1], activation_name]]

    return model, [weights], [biases]

def load_test(test_file):
    with open(test_file, 'r') as file:
        lines = file.readlines()
        data = [list(map(int, line.strip())) for line in lines]
    return data

def runnet(network, output_file, X_test):
    # Run the test data through the network
    predictions = []
    for x in X_test:
        z = network.propagate(x)
        # predict using the threshold
        predictions.append(1 if z > PREDICTION_THRESHOLD else 0)

    # Write the predictions to the output file
    with open(output_file, "w") as file:
        for prediction in predictions:
            file.write(f"{prediction}\n")

# Main function
def main():
    saved_data_file = "wnet0.txt"
    testnet0 = "testnet0.txt"
    output_file = "predictions0.txt"

    # initialize the model, weights, activations and biases
    model, weights, biases = load_network(saved_data_file)

    # create the network
    network = NeuralNetwork(model, weights, biases)
    X_test = load_test(testnet0)
    # Run the test data through the network and save predictions to output file
    runnet(network, output_file, X_test)
    print("Predictions saved to predictions0.txt")

if __name__ == '__main__':
    main()


n = int(input())
time_list = list(map(int, input().split(' ')))

time_list.sort()

whole_time = 0
private_time = 0

for time in time_list:
    private_time += time
    whole_time += private_time

print(whole_time)


# -*- coding: utf-8 -*-
"""
Created on Wed Jul 27 16:03:56 2022

@author: Jared
"""

import os
from multiprocessing import Process
from multiprocessing.pool import Pool

def task(arg=":-)"):
    print(f"Bello\n{arg}", flush=True)

def f(x):
    return x*x

if __name__ == '__main__':
    # Define a task to run in a new process
    # arr = "hi :)"
    # p = Process(target=task(arr))

    # Start the task in a new process
    # p.start()

    # Wait for task to complete
    # p.join()

    # Pools are used to automatically manage worker processes
        # Worker processes: processes that are kept around for reuse rather than creating and destroying a bunch of processes

    # Create a process pool
    # Like when opening files, you have to pool.close() at the end to release resources. You can use with statements, too! :D
    with Pool(processes=4, initializer=f, initargs=[2]) as pool:
    # processes: number of owkrers to create and manage within the pool
    # initializer: name of function you want to run
    # initargs: arguments to the specified function
    # maxtasksperchild: number of tasks each worker can execute
        # child processes often accumulate resources without releasing them, so this argument is a good failsafe

    # Issue tasks for execution
        results = pool.map(task, range(4))

    array = [1,2,3,4,5,6,7,8]
    step = 1
    test = [array[i:i + step] for i in range(0, len(array), step)]
    print(test)


import speech_recognition as sr

r = sr.Recognizer()
count = 0
words = ['kill', 'rob', 'hands up']
print('Analyzing and processing Audio input based on NLP')
print('Listening.....')
while True:

    with sr.Microphone() as source:

        audio = r.listen(source)

    try:
        text = r.recognize_google(audio)
        #print('you said:\n' + text)
        if text.find('kill')>-1 or text.find('down')>-1 or text.find('fast')>-1 or text.find('all the money')>-1 or text.find('hands')>-1:
        	count=count+1
        	print(count)
        	if(count==2):
        		break

    except Exception as e:
        print('Not recognized')

print("There might be potential danger")


#! /usr/bin/env python

import datetime
import urllib

url = 'https://en.wikipedia.org/wiki/Succession_of_the_Justices_of_the_Supreme_Court_of_the_United_States?action=raw'

url_contents = urllib.urlopen(url).read()

associates = []
chiefs = []
for group in url_contents.split('|-'):
    if group.find(', ') != -1:
        if group.find('italic;') != -1:
            chief_justice = True
        else:
            chief_justice = False
        for line in group.strip().split('\n'):
            if line.startswith('| '):
                text = line.split('| ', 1)[1]
                text = text.replace('[[', '').replace(']]', '')
                if text.find('{{') == -1 and text != '\xe2\x80\x93':
                    if chief_justice:
                        chiefs.append(text)
                    else:
                        associates.append(text)

def chunkify(l, n):
    for i in range(0, len(l), n):
        yield l[i:i+n]

for i in list(chunkify(chiefs, 3)):
    print(i)

for i in list(chunkify(associates, 3)):
    print(i)


from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class EdgeSquare(QGraphicsRectItem):
    def __init__(self, width, height, _parent=None):
        super(QGraphicsRectItem, self).__init__(_parent)

        self.setPen(QtGui.QPen(Qt.blue, 0))
        self.setBrush(QBrush(Qt.blue))
        self.setFlag(self.ItemSendsScenePositionChanges, True)

        self.setRect(0, 0, width, height)

class VertexText(QGraphicsTextItem):
    def __init__(self, text, parent):
        super(QGraphicsTextItem, self).__init__(text)

        self.__text = text

        self.setParentItem(parent)
        self.setDefaultTextColor(QColor(QtCore.Qt.black))

    def text(self):
        return self.__text

class VertexGui(QGraphicsRectItem):
    def __init__(self, width, height, text="Untitled"):
        super(VertexGui, self).__init__()

        self.__text = VertexText(text, self)

        self.setPen(QtGui.QPen(Qt.black, 5))
        self.setBrush(QtGui.QBrush(Qt.lightGray))
        self.setFlags(self.ItemIsSelectable | self.ItemIsMovable | self.ItemIsFocusable)

        self.setRect(0, 0, width, height)

    def text(self):
        return str(self.__text.text())

    def center_text(self, width, height):
        rect = self.__text.boundingRect()
        lw, lh = rect.width(), rect.height()
        lx = (width - lw) / 2
        ly = (height - lh) / 2
        self.__text.setPos(lx, ly)

    def setRect(self, x, y, width, height):
        super(VertexGui, self).setRect(x, y, width, height)

        self.center_text(width, height)


plotIndex = np.random.randint(0, 255, 6)

for i in range(6):
    plt.subplot(2, 3, i+1)
    mars_image = mars_data[:,plotIndex[i]].reshape((n_pixel_x, n_pixel_y))
    plt.imshow(mars_image, interpolation="nearest", aspect="auto")
    plt.xlabel("V%i" % (plotIndex[i]+1))

plt.tight_layout()
plt.show()


import dgl
import torch
import numpy as np
from sklearn.metrics import f1_score
from transformers import TrainingArguments, DataCollatorWithPadding
from transformers import RobertaTokenizer
from transformers.utils import logging
from datasets import load_dataset,load_metric,load_from_disk
from models.diffuser_app import DiffuserForSequenceClassification
from models.diffuser_utils import DiffuserConfig
from graphtrainer import graphTrainer

logging.set_verbosity_debug()
logger = logging.get_logger()

def preprocess_function(examples):
    return tokenizer(examples['text'], padding = 'max_length', truncation=True, max_length = 1024)

def compute_metrics(eval_pred):
    predictions, labels = eval_pred
    predictions = np.argmax(predictions, axis=1)
    acc = metric_acc.compute(predictions=predictions, references=labels)["accuracy"]
    f1_score = metric_f1.compute(predictions=predictions, references=labels)["f1"]
    return {"accuracy": acc, "f1_score": f1_score }

metric_acc = load_metric('./metrics/accuracy')
metric_f1 = load_metric('./metrics/f1')

imdb = load_dataset("imdb")
# tokenizer = RobertaTokenizer.from_pretrained("./roberta-tokenizer", max_length = 1024)
tokenizer = RobertaTokenizer(tokenizer_file = "./roberta-tokenizer/tokenizer.json",
                             vocab_file     = "./roberta-tokenizer/vocab.json",
                             merges_file    = "./roberta-tokenizer/merges.txt",
                             max_length     = 1024)

tokenized_imdb = imdb.map(preprocess_function, batched=True)
tokenized_imdb = tokenized_imdb.map(remove_columns=["text"])
# tokenized_imdb = load_from_disk("/home")

data_collator = DataCollatorWithPadding(tokenizer=tokenizer)

config = DiffuserConfig.from_json_file("./models/config.json")
config.num_labels = 2

model =  DiffuserForSequenceClassification(config = config).cuda()

training_args = TrainingArguments(
    output_dir = "./save_imdb",
    learning_rate = 3e-5,
    per_device_train_batch_size = 2,
    per_device_eval_batch_size = 2,
    num_train_epochs = 20,
    weight_decay = 0.01,
    evaluation_strategy = "steps",
    eval_steps = 2000,
    logging_steps = 500,
    save_steps = 500,
    seed = 42,
    warmup_steps = 200,
    gradient_accumulation_steps = 8,
    prediction_loss_only=True
)

steps_per_train_epoch       = int(len(tokenized_imdb['train'])/(training_args.per_device_train_batch_size*torch.cuda.device_count()*training_args.gradient_accumulation_steps ))
training_args.eval_steps    = int(steps_per_train_epoch)
training_args.logging_steps = int(steps_per_train_epoch/5)
training_args.save_steps    = int(steps_per_train_epoch)

trainer = graphTrainer(
    model = model,
    config = config,
    args = training_args,
    train_dataset = tokenized_imdb["train"],
    eval_dataset = tokenized_imdb["test"],
    tokenizer = tokenizer,
    data_collator = data_collator,
    compute_metrics = compute_metrics
)

trainer.train()


import os
from pathlib import Path
from typing import Dict, Tuple

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.metrics import mean_squared_error, r2_score

__THIS_PATH = Path(os.path.dirname(os.path.realpath(__file__)))
ARTIFACTS_PATH = __THIS_PATH / ".." / "artifacts"

def generate_data() -> Tuple[np.array, np.array, np.array, np.array]:
    """
    Generates a dataset extracted from the diabetes dataset in sklearn.

    Returns:
        diabetes_X_train: the training dataset
        diabetes_y_train: The output corresponding to the training set
        diabetes_X_test: the test dataset
        diabetes_y_test: The output corresponding to the test set
    """
    # Load the diabetes dataset
    diabetes_X, diabetes_y = load_diabetes(return_X_y=True)

    # Use only one feature
    diabetes_X = diabetes_X[:, np.newaxis, 2]

    # Split the data into training/testing sets
    diabetes_X_train = diabetes_X[:-20]
    diabetes_X_test = diabetes_X[-20:]

    # Split the targets into training/testing sets
    diabetes_y_train = diabetes_y[:-20].reshape(-1, 1)
    diabetes_y_test = diabetes_y[-20:].reshape(-1, 1)

    print(
        f"# Training Samples: {len(diabetes_X_train)}; # Test samples: {len(diabetes_X_test)};"
    )
    return diabetes_X_train, diabetes_y_train, diabetes_X_test, diabetes_y_test

def get_scores(y: np.array, y_predicted: np.array) -> Dict[str, float]:
    r2 = r2_score(y, y_predicted)
    mse = mean_squared_error(y, y_predicted)
    rmse = mean_squared_error(y, y_predicted, squared=False)

    return {"r2": r2, "mse": mse, "rmse": rmse}

def evaluate(model, X: np.array, y: np.array, y_predicted: np.array) -> None:
    """
    Calculates evaluation metrics, print them along with a plot showing the fitted model.
    Returns:
        scores: mse and R2 score of the predicted outputs
    """
    # The coefficients
    print(f"Slope: {model.W}; Intercept: {model.b}")

    scores = get_scores(y, y_predicted)
    # The mean squared error
    mse = scores["mse"]
    print(f"Mean squared error: {mse:.2f}")
    # The coefficient of determination: 1 is perfect prediction
    r2 = scores["r2"]
    print(f"Coefficient of determination: {r2:.2f}")

    # Plot outputs
    plt.scatter(X, y, color="black")
    plt.plot(X, y_predicted, color="blue", linewidth=3)

    plt.xticks(())
    plt.yticks(())

    plt.show()

    if r2 >= 0.4:
        print("****** Success ******")
    else:
        print("****** Failed ******")


usuario = []
n = 0
maior = 0
menor = 0
print('\033[33m=== CRIE SEU VETOR DE 10 POSIÇÕES E DESCUBRA O MAIOR E MENOR ELEMENTO ===\033[m')
while n < 10:
    num = (int(input(f'Informe o {n + 1}º número: ')))
    usuario.append(num)
    n += 1
    if n == 1:
        maior = menor = num
    else:
        if num > maior:
            maior = num
        if num < menor:
            menor = num
print('-' * 60)
print(f'\033[34mForam estes os números informados: {usuario}\033[m')
print(f'\033[32mO maior número informado é: {maior}. E o menor é: {menor}\033[m')