from torch.utils.data import DataLoader
from tqdm import tqdm

from yolov3.datasets import *
from yolov3.utils.boxes import non_max_suppression, xywh2xyxy, mv_filtering
from yolov3.utils.visualization import draw_detections

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def make_dirs(inference_dir, classes):
    """
    Makes the following dirs:
    inference_dir
        - none/
        - class_1
            - none
            - class_2
            - class_3
            ...
        - class_2
            - none
            - class_1
            - class_3
            ...
        ...
    :param inference_dir: path of the inference directory
    :param classes: classes list
    """
    os.makedirs(os.path.join(inference_dir, "none"), exist_ok=True)
    for c in classes:
        os.makedirs(os.path.join(inference_dir, c), exist_ok=True)
        for k in classes:
            if k != c:
                os.makedirs(os.path.join(inference_dir, c, k), exist_ok=True)
        os.makedirs(os.path.join(inference_dir, c, 'none'), exist_ok=True)
        os.makedirs(os.path.join(inference_dir, 'none', c), exist_ok=True)

def save_no_gt(img_path, inference_dir, filename, classes, img_size, img_detection):
    """
    Draws and saves the image with its predictions to one of the following folders:
        - inference/none/ if no detection was obtained
        - inference/none/class_k if the k-th class was found
    :param img_path: image path
    :param inference_dir: inference directory
    :param filename: file name of the output image
    :param classes: class names list
    :param img_size: image size
    :param img_detection: tensor with image detections
    """
    if img_detection is None or len(img_detection) == 0:
        out_path = os.path.join(inference_dir, 'none', f"{filename}.png")
        draw_detections(img_path, out_path, img_detection, classes, img_size)
    else:
        detected_classes = img_detection.t()[-1]
        for detected_class in detected_classes:
            cls = classes[int(detected_class)]
            out_path = os.path.join(inference_dir, 'none', cls, f"{filename}.png")
            draw_detections(img_path, out_path, img_detection, classes, img_size)

def save_detection(img_path, img_detection, ground_truth, inference_dir, filename, classes, img_size):
    gt_classes = ground_truth.t()[1]
    for gt_class in gt_classes:
        if gt_class >= len(classes):
            save_no_gt(img_path, inference_dir, filename, classes, img_size, img_detection)
        else:
            g_cls = classes[int(gt_class)]
            if img_detection is None or len(img_detection) == 0:
                out_path = os.path.join(inference_dir, g_cls, 'none', f"{filename}.png")
                draw_detections(img_path, out_path, img_detection, classes, img_size, gt=ground_truth)
            else:
                detected_classes = img_detection.t()[-1]
                for detected_class in detected_classes:
                    cls = classes[int(detected_class)]
                    if cls == g_cls:
                        out_path = os.path.join(inference_dir, cls, f"{filename}.png")
                    else:
                        out_path = os.path.join(inference_dir, g_cls, cls, f"{filename}.png")
                    draw_detections(img_path, out_path, img_detection, classes, img_size, gt=ground_truth)

def detect_singleview(model, parser, views=None, classes=None):
    """
    Inference for single view data
    :param model: model object
    :param parser: parser object
    :param views: views to include in coco dataset
    :param classes: class names list. If parser points to a annotation file, classes will be taken from there. Otherwise
    it will be taken from this list. If no annotation file is provided and neither this parameter, classes will be
    taken from the model
    """
    annotations = None
    if parser.inference["annotation_file"] is not None:
        with open(parser.inference["annotation_file"], 'r') as f:
            coco = json.load(f)
        annotations = coco['annotations']
        categories = sorted(coco['categories'], key=lambda key: key['id'])
        classes = [c['name'] for c in categories]
    else:
        if classes is None:
            classes = model.classes
    save_structured = annotations is not None and parser.inference["save_structured"]
    if save_structured and classes is not None:
        make_dirs(parser.inference_dir, classes)

    if parser.inference["weights_file"].endswith(".weights"):
        model.load_darknet_weights(parser.inference["weights_file"])
    else:
        model.load_state_dict(torch.load(parser.inference["weights_file"]))

    model.eval()
    with_gt = parser.inference["with_gt"] and annotations is not None
    dataloader_params = {"batch_size": parser.inference["batch_size"], "shuffle": False,
                         "num_workers": parser.workers}
    if with_gt:
        dataset = COCODatasetFromMV(parser.inference["dir"],
                                    annotations_file=parser.inference["annotation_file"],
                                    augment=False,
                                    multiscale=False,
                                    normalized_labels=parser.inference["normalized"],
                                    img_size=parser.img_size,
                                    views=views,
                                    padding_value=1)
        dataloader_params["collate_fn"] = dataset.collate_fn
    else:
        dataset = ImageFolder(parser.inference["dir"], img_size=parser.img_size)
    dataloader_params["dataset"] = dataset
    dataloader = torch.utils.data.DataLoader(**dataloader_params)

    n_imgs = parser.inference["max_images"]
    img_counter = 0

    parser.inference_dir = os.path.join(parser.inference_dir, "sv")
    os.makedirs(parser.inference_dir, exist_ok=True)

    for data in tqdm(dataloader, desc="Detecting objects and saving images"):
        # Configure input
        targets = None
        gt = None
        if not with_gt:
            img_paths, imgs = data
        else:
            img_paths, _, imgs, targets = data
            targets = targets.to(device)

        imgs = imgs.to(device)
        # Get detections
        with torch.no_grad():
            detections = model(imgs)
            detections = non_max_suppression(detections, parser.inference["conf_thres"],
                                             parser.inference["nms_thres"])

        for batch_id, (img_path, img_detection) in enumerate(zip(img_paths, detections)):
            if targets is not None:
                t = [t for t in targets if t[0] == batch_id]
                if len(t) > 0:
                    gt = torch.stack(t)
            filename = img_path.split("/")[-1].split(".")[0]
            if save_structured and gt is not None:
                if targets.size(0) == 0:
                    save_no_gt(img_path, parser.inference_dir, filename, classes, parser.img_size, None)
                else:
                    save_detection(img_path, None, gt, parser.inference_dir, filename, classes, parser.img_size)
            else:
                out_path = os.path.join(parser.inference_dir, f"{filename}.png")
                draw_detections(img_path, out_path, None, classes, parser.img_size, gt=gt)

        img_counter += len(img_paths)
        if 0 < n_imgs <= img_counter:
            break

def detect_multiview(model, dataset, f_matrices, parser):
    annotations = None
    classes = parser.inference["classes"]
    if parser.inference["annotation_file"] is not None:
        with open(parser.inference["annotation_file"], 'r') as f:
            coco = json.load(f)
        annotations = coco['annotations']
        categories = sorted(coco['categories'], key=lambda key: key['id'])
        classes = [c['name'] for c in categories]
    save_structured = annotations is not None and parser.inference["save_structured"]
    with_gt = parser.inference["with_gt"] and annotations is not None

    dataloader_params = {"batch_size": parser.inference["batch_size"], "shuffle": False,
                         "num_workers": parser.workers}
    if with_gt:
        dataloader_params["collate_fn"] = dataset.collate_fn
    else:
        dataset = ImageFolder(parser.inference["dir"], img_size=parser.img_size)

    dataloader_params["dataset"] = dataset
    dataloader = torch.utils.data.DataLoader(**dataloader_params)

    if save_structured:
        make_dirs(parser.inference_dir, classes)

    if parser.inference["weights_file"].endswith(".weights"):
        model.load_darknet_weights(parser.inference["weights_file"])
    else:
        model.load_state_dict(torch.load(parser.inference["weights_file"]))

    model.eval()

    n_imgs = parser.inference["max_images"]
    img_counter = 0
    views = dataset.views
    for img_paths, _, imgs, targets in tqdm(dataloader, desc="Detecting objects and saving images"):
        # NOTE: THIS ONLY WORKS WITH MVCOCO DATASET
        # Get detections
        view_outputs = {v: None for v in views}
        imgs, targets = imgs.to(device), targets.to(device)

        for i, v in enumerate(views):
            view_imgs = imgs[:, i, ...]
            view_imgs.requires_grad = False
            view_targets = targets[:, i, :]
            with torch.no_grad():
                view_outputs[v] = model(view_imgs)
                # view_outputs[v] = non_max_suppression(view_outputs[v], conf_thres=conf_thres, nms_thres=nms_thres)
            view_targets[:, 2:] = xywh2xyxy(view_targets[:, 2:])
            view_targets[:, 2:] *= parser.img_size

        detections = mv_filtering(view_outputs, f_matrices, conf_thres=parser.inference["conf_thres"],
                                  p_value=parser.inference["p_value"],
                                  nms_thres=parser.inference["nms_thres"])

        for j, v_img_paths in enumerate(img_paths):
            for i, v in enumerate(views):
                v_img_path = v_img_paths[i]
                filename = v_img_path.split("/")[-1].split(".")[0]
                out_path = os.path.join(parser.inference_dir, f"{filename}.png")
                draw_detections(v_img_path, out_path, detections[v][j], classes, parser.img_size)

        img_counter += len(img_paths)
        if 0 < n_imgs <= img_counter:
            break


# 19.	Create an acronym or an abbreviation for the name 'Coding For All'.
expected = 'CFA'
mystring = 'Coding For All'

# Solution 01
acronym = ''
for piece in mystring.split():
    acronym += piece[0]
print(f"Solution 01 result = {acronym == expected}")

# Solution 02
acronym = ''.join([piece[0] for piece in mystring.split()])
print(f"Solution 02 result = {acronym == expected}")


from typing import Optional
from pydantic import BaseModel, EmailStr, Field
from datetime import datetime

# Base models

class PostBase(BaseModel):
    title: str
    content: str
    published: bool = True

class UserBase(BaseModel):
    email: EmailStr

# Request models

class PostCreate(PostBase):
    # userid is set from token
    pass

class UserCreate(UserBase):
    password: str

class VoteCreate(BaseModel):
    post_id: int
    vote: bool

# Response models

class User(UserBase):
    id: int
    created_at: datetime

    class Config:
        from_attributes = True

class Post(PostBase):
    id: int
    created_at: datetime
    user: User

    class Config:
        from_attributes = True

class PostAndVotes(BaseModel):
    post: Post = Field(validation_alias="Post")
    votes: int

    class Config:
        populate_by_name = True
        from_attributes = True

class Vote(BaseModel):
    user_id:int
    post_id:int

    class Config:
        from_attributes = True

class Token(BaseModel):
    access_token: str
    token_type: str

class TokenData(BaseModel):
    user_id: Optional[int]


from datetime import datetime
from app.core.service import BaseService
from app.models.food_type import FoodTypes
from app.schemas.food_type import FoodTypesResponse
from fastapi import HTTPException, status, Response
from sqlalchemy import and_

class FoodTypesService(BaseService):

    def get_by_id(self, id:int):
        food_type = self.db.query(FoodTypes).filter(FoodTypes.id == id).first()

        if not food_type:
            raise HTTPException(
                    status.HTTP_404_NOT_FOUND,
                    [{
                            'error' : True,
                            'message': f"Food type with id: {id} does not exist",
                            'code': 'ER0034'
                        }]
                )

        return food_type

    def create(self, name: str):
        food_type = self.db.query(FoodTypes).filter(and_(FoodTypes.name == name, FoodTypes.deleted_at.is_(None))).first()

        if food_type:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail=f"Loại thức ăn đã tồn tại"
                )

        max_id = self.db.execute("""
                select max(id) from food_types
                """).first()
        if not max_id.max:
            generate = 1
        else:
            generate = max_id.max + 1

        prefix = 'LTA-'
        if generate < 10:
            code = f'{prefix}{0}{generate}'
        else:
            code = f'{prefix}{generate}'

        new_food_type = FoodTypes(
            code=code,
            name=name
        )
        self.db.add(new_food_type)
        self.db.commit()
        self.db.refresh(new_food_type)

        return new_food_type

    def get_all(self):
        food_types = self.db.query(FoodTypes)

        food_types = food_types.filter(FoodTypes.deleted_at.is_(None))

        return food_types.order_by(FoodTypes.code).all()

    def update_food_type(self, id:int, name: str):
        food_type = self.get_by_id(id)
        if name:
            food_type_exist = self.db.query(FoodTypes).filter(and_(FoodTypes.name == name, FoodTypes.deleted_at.is_(None))).first()
            if food_type_exist:
                if food_type.id != food_type_exist.id:
                    raise HTTPException(
                    status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                    detail=f"Dữ liệu loại thức ăn đã tồn tại",
                    )
            self.db.query(FoodTypes).filter(FoodTypes.id == id).update({"name": name}, synchronize_session=False)

        self.db.commit()

        return food_type

    def soft_delete_food_type(self, id: int):
        self.get_by_id(id)
        current_time = datetime.now()

        self.db.query(FoodTypes).filter(FoodTypes.id == id).update({"deleted_at": current_time}, synchronize_session=False)

        self.db.commit()


from keras.models import Sequential
from keras.layers import LSTM, Dense
from keras.utils import np_utils
from keras import optimizers
from sklearn.model_selection import train_test_split
# from sklearn.utils import shuffle
import numpy as np
from tensorflow import set_random_seed

from ..algorithm_utils import Algorithm, TQDMNotebookCallback

class SimpleLSTM(Algorithm):
    def __init__(self, name_suffix='', n_timestamps=7, n_features=5, n_classes=3, shuffle=True,
                 n_units=[16, 16], lstm_dropout=0.2, rec_dropout=0.2, lr=0.001,
                 ignore_features=[], **kwargs):
        kwargs['batch_size'] = kwargs.get('batch_size', 16)
        kwargs['epochs'] = kwargs.get('epochs', 50)
        super().__init__('simple_lstm', f'SimpleLSTM{name_suffix}', f'SLSTM{name_suffix}',
                         **kwargs)
        self.name_suffix = name_suffix
        self.ignore_features = ignore_features
        self.n_timestamps = n_timestamps
        self.n_features = n_features - len(self.ignore_features)
        self.n_classes = n_classes
        self.n_units = n_units
        self.lr = lr
        self.lstm_dropout = lstm_dropout
        self.rec_dropout = rec_dropout
        self.shuffle = shuffle

    def can_handle_time_dim(self):
        return True

    def __call__(self):
        np.random.seed(self.seed)
        set_random_seed(self.seed)
        model = Sequential()
        for i, layer_units in enumerate(self.n_units):
            is_last_one = i == len(self.n_units) - 1
            model.add(LSTM(
                layer_units, input_shape=(self.n_timestamps, self.n_features), stateful=False,
                dropout=self.lstm_dropout, recurrent_dropout=self.rec_dropout,
                return_sequences=not is_last_one))
        model.add(Dense(self.n_classes, activation='softmax'))
        # rmsprop, adadelta, adam
        optimizer = optimizers.Adam(lr=self.lr)
        model.compile(loss='categorical_crossentropy', optimizer=optimizer,
                      metrics=['categorical_accuracy'])
        return model

    def transform(self, X=None, y=None):
        if X is not None:
            # _X = X.reshape((*X.shape, 1))
            kept_features = [f for f in range(X.shape[2]) if f not in self.ignore_features and
                             (f-self.n_features-len(self.ignore_features)) not in self.ignore_features]
            _X = X[:, :, kept_features]
        if y is not None:
            _y = np_utils.to_categorical(y + 1)
        if X is None:
            return _y
        if y is None:
            return _X
        return _X, _y

    def undo_transform(self, X=None, y=None):
        if X is not None:
            # _X = X.reshape(X.shape[:2])
            _X = X
        if y is not None:
            _y = y - 1  # y.argmax(axis=1) - 1
        if X is None:
            return _y
        if y is None:
            return _X
        return _X, _y

    def fit(self, X, y, **kwargs):
        np.random.seed(self.seed)
        set_random_seed(self.seed)
        # For statefule training (would require seperating by company)
        # for i in range(self.sk_params['epochs']):
        #     history = self.model.fit(X, y, epochs=1, batch_size=self.sk_params['batch_size'],
        #                              verbose=0, shuffle=False)
        #     self.model.reset_states()
        #     print(f'Epoch {i}: '
        #           f'{"; ".join([f"{m}={history.history[m]}" for m in history.history])}')
        val_split = kwargs.get('validation_split', 0.2)
        if not self.shuffle:
            kwargs['validation_split'] = val_split
            X, y = self.transform(X, y)
        else:
            # FIXME: Don't shuffle before splitting train and val set
            X, y = self.transform(X, y)
            X, X_val, y, y_val = train_test_split(
                X, y, test_size=val_split, shuffle=False, stratify=None,
                random_state=self.seed)
            # X, y = shuffle(X, y, random_state=self.seed)
            # X_val, y_val = shuffle(X_val, y_val, random_state=self.seed)
            kwargs['validation_split'] = 0
            kwargs['validation_data'] = (X_val, y_val)

        return super().fit(X, y, shuffle=self.shuffle, verbose=0,
                           callbacks=[TQDMNotebookCallback()], **kwargs)

    def predict(self, X, **kwargs):
        pred = super().predict(self.transform(X), **kwargs)
        return self.undo_transform(y=pred)

    def clone(self, **kwargs):
        return SimpleLSTM(
            name_suffix=self.name_suffix, n_timestamps=self.n_timestamps, shuffle=self.shuffle,
            n_features=self.n_features + len(self.ignore_features), n_classes=self.n_classes,
            n_units=self.n_units, lstm_dropout=self.lstm_dropout, rec_dropout=self.rec_dropout,
            lr=self.lr, ignore_features=self.ignore_features,
            batch_size=self.sk_params['batch_size'], epochs=self.sk_params['epochs'],
            **kwargs)


from django.shortcuts import render
from django.http import HttpResponse

speakers = [
    {
        'id': 1,
        'name': 'John Smith',
        'email': 'john.smith@gmail.com',
    },
    {
        'id': 2,
        'name': 'Kenneth Kabwe',
        'email': 'kenneth.kabwe@gmail.com',
    },
    {
        'id': 3,
        'name': 'William Buto',
        'email': 'william.buto@gmail.com',
    }
]

def update_speaker (request, id:int):
    speaker = list(filter(lambda c: c['id'] == id, speakers))[0]
    return render (request, 'update_speaker.html', { 'speaker': speaker} )


import random
import time

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def initalize_sort(unsorted_list):
    temp = unsorted_list.copy()
    temp = sorted(temp)
    i = 0
    while mongo_sort(temp, unsorted_list) == False:
        print(bcolors.FAIL + "Warning: no match on search result " + str(i) + bcolors.ENDC)
        i = i + 1

    print(bcolors.OKBLUE + "Whiiie: match on search result " + str(i) + bcolors.ENDC)

def mongo_sort(sorted_list, unsorted_list):
    random.shuffle(unsorted_list)
    if unsorted_list == sorted_list:
        print(str(unsorted_list) + "==" + str(sorted_list) + "\n")
        return True
    else:
        print(str(unsorted_list) + "=!" + str(sorted_list) + "\n")
        return False

def main():
    while True:
        unsorted_list = ['python','c','ada','ruby','pascal','basic']
        initalize_sort(unsorted_list)
        time.sleep(2)

if __name__ == '__main__':
    main()


import unittest

from tests.contrib.operators.test_bigquery_operator_system_helper import GCPBigQueryTestHelper
from tests.contrib.utils.base_gcp_system_test_case import SKIP_TEST_WARNING, TestDagGcpSystem
from tests.contrib.utils.gcp_authenticator import GCP_BIGQUERY_KEY

@unittest.skipIf(TestDagGcpSystem.skip_check(GCP_BIGQUERY_KEY), SKIP_TEST_WARNING)
class BigQueryExampleDagsSystemTest(TestDagGcpSystem):
    """
    System tests for Google BigQuery operators

    It use a real service.
    """

    def __init__(self, method_name="runTest"):
        super().__init__(method_name, dag_id="example_bigquery", gcp_key=GCP_BIGQUERY_KEY)
        self.helper = GCPBigQueryTestHelper()

    def setUp(self):
        super().setUp()
        self.gcp_authenticator.gcp_authenticate()
        try:
            self.helper.create_repository_and_bucket()
        finally:
            self.gcp_authenticator.gcp_revoke_authentication()

    def test_run_example_dag(self):
        self._run_dag()

    def tearDown(self):
        self.gcp_authenticator.gcp_authenticate()
        try:
            self.helper.delete_bucket()
        finally:
            self.gcp_authenticator.gcp_revoke_authentication()
        super().tearDown()


num_list = list(map(int, input().split()))
list = []

num = int(num_list[0])
num2 = int(num_list[1])

for i in range(num):
    s = input()
    list.append(s)

list.reverse()

a = 0
b = 0
for i in range(num_list[0]):
    b = num2 // int(list[i])
    num2 = num2 % int(list[i])
    a = a + b

print(a)


import argparse
full_steps_per_rotation = 200
microsteps = 16

parser = argparse.ArgumentParser(description='Calculate the number of steps to rotate a stepper motor.')
parser.add_argument("steps_per_mm", type=float, help="The number of steps per mm")
args = parser.parse_args()

steps_per_mm = args.steps_per_mm

rotation_distance = full_steps_per_rotation * microsteps / steps_per_mm

print(rotation_distance)


datafile = "data.txt"

def get_priority(char: str) -> int:
    ascii = ord(char)
    if ascii in range(65, 91):
        return ascii - 38
    elif ascii in range(97, 123):
        return ascii - 96
    else:
        return 0

with open(datafile) as f:
    lines = f.read().splitlines()
    sum = 0
    for i in range(0, len(lines), 3):
        first = set(lines[i])
        second = set(lines[i + 1])
        third = set(lines[i + 2])

        common = next(iter(first.intersection(second, third)))
        sum += get_priority(common)
    print(sum)


# Q: 对于一个二进制流，设计空间复杂度为o(n)的算法，试估算当流进n位二进制时，流中所包含的1的个数，设内存只能存放k位二进制数。
# A: 利用滑动窗口的思想解决

def count_ones(stream, n, k):
    window = stream[:k]
    ones_count = 0
    for i in range(0, k):
        ones_count += int(window[i:i+1])
    total_ones_count = ones_count

    for i in range(k, n):
        # 移动窗口，将最左侧的二进制位移除窗口
        tmp = window[1:k]

        # 将下一个二进制位添加到窗口中
        tmp += stream[i:i+1]

        # 更新当前的1的计数
        # for j in range(0, k):
        #     tmp_count = 0
        #     tmp_count += int(tmp[j:j+1])
        #     total_ones_count += tmp_count
        total_ones_count += int(tmp[k-1:k])

    return total_ones_count

LEN = 16
WINDOW_LEN = 4
print(count_ones(b'1001001001001000', LEN, WINDOW_LEN))


import re
import statistics

towers = {}
for line in open('d07.txt').read().splitlines():
    f, ch = re.findall(r'(\w+) \((\d+)', line)[0], re.findall(r' (\w+)', line)
    towers[f[0]] = [int(f[1]), None, ch]

for tower, elems in towers.items():
    for child in elems[2]:
        towers[child][1] = tower

# P1
for tower, elems in towers.items():
    if not elems[1]:
        print(tower)
        break

# P2
def wsum(t):
    res = towers[t][0] + sum([wsum(ch) for ch in towers[t][2]])
    towers[t].append(res)
    return res

def balance(t, target = None):
    weights = [towers[ch][3] for ch in towers[t][2]]
    med = statistics.median(weights)
    for ch in towers[t][2]:
        if towers[ch][3] != med: return balance(ch, med)
    return towers[t][0] - (towers[t][3] - target)

wsum(tower)
print(balance(tower))


import threading
from queue import Queue
import requests
import time
from lxml import etree

START_URL = 'http://qianmu.iguye.com/2018USNEWS世界大学排名'
link_queue =  Queue()
threads = []
DOWNLOADER_NUM = 20

def fetch(url):
    r = requests.get(url)
    return r.text.replace('\t','')

def parse(html):

    html = etree.HTML(html)
    links = html.xpath('//*[@id="content"]/table/tbody/tr/td[2]/a/@href')
    for link in links:
        if not link.startswith('http://'):
            link = 'http://qianmu.iguye.com/%s' % link
        link_queue.put(link)

def parse_university(html):
    html = etree.HTML(html)
    table = html.xpath('//*[@id="wikiContent"]/div[1]/table/tbody')
    if not table:
        return
    table = table[0]
    keys = table.xpath('./tr/td[1]//text()')
    cols = table.xpath('./tr/td[2]')
    values = [''.join(col.xpath('.//text()')) for col in cols]
    info = dict(zip(keys, values))
    print(info)

def downloader():
    while True:
        link = link_queue.get()
        if link is None:
            break
        parse_university(fetch(link))
        link_queue.task_done()
        print('剩余链接数为%s'%link_queue.qsize())

if __name__ == '__main__':
    start_time = time.time()
    parse(fetch(START_URL))
    for i in range(DOWNLOADER_NUM):
        t = threading.Thread(target=downloader)
        t.start()
        threads.append(t)
    link_queue.join()
    for i in range(DOWNLOADER_NUM):
        link_queue.put(None)
    for t in threads:
        t.join()
    cost_time = time.time() -start_time
    print('一共用了%s秒'%cost_time)


# -*- coding: utf-8 -*-
import os
from flask import Flask, request, Response
from flask_cors import CORS
import yaml
import json

with open('config/dev.yaml', 'r',encoding="utf-8") as f:
    config = yaml.load(f, Loader=yaml.Loader)

app = Flask(__name__, static_folder='static')
cors = CORS(app)

@app.route('/sample', methods=['GET', 'POST'])
def sample_func():

    res = {
        'code': 200,
        'msg': 'success'
    }
    return Response(response=json.dumps(res, indent = 4), status=200, content_type='application/json')

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


from numpy import matrix
import math
size = int(input("enter size of a vector >>> "))

def prepare_for_iterations(matr, answers):
    for i in range(size):
        answers[i] /= matr[i][i]
        for j in range(size):
            if i == j:
                continue
            matr[i][j] /= -matr[i][i]
        matr[i][i] = 0

def add(vec1, vec2):
    vec = []
    for i in range(len(vec1)):
        vec.append(vec1[i] + vec2[i])
    return vec

def subtract(vec1, vec2):
    vec = []
    for i in range(len(vec1)):
        vec.append(vec1[i] - vec2[i])
    return vec

def multiply(matr, vec):
    res = []
    for i in range(len(vec)):
        s = 0
        for j in range(len(vec)):
            s += matr[i][j] * vec[j]
        res.append(s)
    return res

def multiply_matrix(matr1, matr2):
    res = [[0] * size for i in range(size)]
    for i in range(size):
        for j in range(size):
            for k in range(size):
                res[i][j] += matr1[i][k] * matr2[k][j]
    return res

def transpose(matr):
    res = [[0] * size for i in range(size)]
    for i in range(size):
        for j in range(size):
            res[i][j] = matr[j][i]
    return res

def norm(vec):
    res = 0
    for i in vec:
        res += i**2
    return math.sqrt(res)

matr = []
f = open("file.txt")
for _ in range(size):
    matr.append(list(map(float, f.readline().strip().split())))

ans = []
for _ in range(size):
    ans.append(float(f.readline()))

matr2 = []
for i in range(size):
    matr2.append(matr[i][::])
ans2 = ans[::]
prepare_for_iterations(matr2, ans2)

print(matrix(matr2))
print(matrix(ans2).T)

solution = [0] * size
nev_norm = 100000000 #magic don`t touch

iterations = 0
while nev_norm > 1e-6:
    iterations += 1
    print(f"iteration: {iterations}")
    solution = add(multiply(matr2, solution), ans2)
    print(matrix(solution).T)
    print("Residual")
    nev = subtract(ans, multiply(matr, solution))
    print(nev)
    nev_norm = norm(nev)
    print(f"Residual norm = {nev_norm}")


SIZE = int(input())
matrix = []

boat_pos = []
for rows in range(SIZE):
    matrix.append(list(input()))
    if 'S' in matrix[rows]:
        boat_pos = [rows, matrix[rows].index('S')]
        matrix[rows][matrix[rows].index('S')] = '-'

directions = {
    'up': (-1, 0),
    'down': (1, 0),
    'left': (0, -1),
    'right': (0, 1)
}

fish_amount = 0
whirpool = False
while True:
    command = input()
    if command == 'collect the nets':
        matrix[boat_pos[0]][boat_pos[1]] = 'S'
        if fish_amount >= 20:
            print("Success! You managed to reach the quota!")
            break
        else:
            print(f"You didn't catch enough fish and didn't reach the quota! You need {20 - fish_amount} tons of fish more.")

            break
    cur_row = boat_pos[0] + directions[command][0]
    cur_col = boat_pos[1] + directions[command][1]

    cur_row %= SIZE
    cur_col %= len(matrix[0])

    if matrix[cur_row][cur_col] == 'W':
        fish_amount = 0
        whirpool = True
        matrix[cur_row][cur_col] = '-'
        break

    if matrix[cur_row][cur_col].isdigit():
        fish_amount += int(matrix[cur_row][cur_col])
        matrix[cur_row][cur_col] = '-'

    boat_pos = [cur_row, cur_col]

if fish_amount > 0:
    print(f"Amount of fish caught: {fish_amount} tons.")
if whirpool:
    print(
        f"You fell into a whirlpool! The ship sank and you lost the fish you caught. Last coordinates of the ship: [{cur_row},{cur_col}]")
else:
    [print(''.join(x)) for x in matrix]


x=0
y=0
n=int(input())
a=input()
for i in range(0,n):
    if a[i]=='A':
        x=x+1
    else:
        y=y+1
if x>y:
    print("Anton")
elif y>x:
    print("Danik")
else:
    print("Friendship")


from utility.actions import actions
from utility.restrictions import restrictions
from node.Node import Node

class Algorithm:
    def __init__(self) -> None:
        self.actions = actions()
        self.restrictions = restrictions()

    def heuristic(self, current) -> int:
        rows = current.board
        h = 0
        for i in range(len(rows)):
            for j in range(i + 1, len(rows)):
                # Reinas en la misma rows
                if rows[i] == rows[j]:
                    h += 1
                # Reinas en diagonal
                if rows[i] + i == rows[j] + j:
                    h += 1
                if rows[i] - i == rows[j] - j:
                    h += 1
        return h

    def evaluate_path(self, init):
        init_node = Node(init)
        init_node.h = self.heuristic(init_node)
        open_nodes = []
        close_nodes = []
        open_nodes.append(init_node)

        while len(open_nodes) > 0:
            i = 0
            for index, item in enumerate(open_nodes):
                if item.f < open_nodes[0].f:
                    i = index

            current = open_nodes.pop(i)
            if current.h == 0:
                if current.next is None:
                    return current
                while current.next.next is not None:
                    current = current.next
                return current

            close_nodes.append(current)
            successors = []
            for act, res in zip(self.actions, self.restrictions):
                if res(current):
                    successors.append(act(current))

            for succ in successors:
                g = current.g + 1
                best = False

                if succ not in open_nodes:
                    succ.h = self.heuristic(succ)
                    open_nodes.append(succ)
                    best = True
                elif current.g < succ.g:
                    best = True
                if best:
                    succ.next = current
                    succ.g = g
                    succ.f = succ.g + succ.h
        return None


from utils import DiceLoss, DiceLoss2
import torch

# create two random tensors of size (16, 13, 512, 512)

pred = torch.rand(16, 13, 512, 512)
target = torch.rand(16, 13, 512, 512)

loss1 = DiceLoss(pred, target)
loss2 = DiceLoss2(pred, target)

print(loss1, loss2)


# 作业一
# n1 = int(input("Enter a number:"))
# n2 = int(input("Enter a number:"))
# op = input("运算符号(+，-，*，/)：")
# op为字串
# 帮使用者运算
n1 = int(input("请输入n1的数值:"))
n2 = int(input("请输入n2的数值:"))
op = input("请输入 +, -, *, / :")
if op=="+":
    print("得到的数值为：",n1+n2)
elif op =="-":
    print("得到的数值为：",n1-n2)
elif op =="*":
    print("得到的数值为：",n1*n2)
elif op =="/":
    print("得到的数值为：",n1/n2)
else :
    print("输入错误")

# 作业二
# n = int(input("输入一个正整数"))
# 算整数平方根 9=>3, 25=>5, 8=>没有
# 1,2,3,4,5
n =int (input("请输入一正整数:"))
for i in range(n):
    if i * i == n :
        print("平方根为：",i)
        break
else:
    print(n,"没有正整数平方根喔")

# 作业三
# 打印9*9乘法表
for i in range(1,10):
    for j in range(1,10):
        print(i,"*",j,"=",i*j)


import datetime, math
if __name__=="__main__":
    pass
    n_cases = int(input())
    for x in range(n_cases):
        line = input()
        n_files = int(line.split(" ")[0])
        n_gigs = float(line.split(" ")[1])

        files = {}
        for y in range(n_files):
            file_f = input()

            time = file_f.split("M")[0] + "M"
            time = datetime.datetime.strptime(time, "%d/%m/%Y %I:%M %p")

            today = datetime.datetime(2019, 5, 27, 0, 0, 0)
            days = (today - time).days + (today - time).seconds / (24 * 3600)

            days = math.ceil(2 * days) / 2

            size = file_f.split("M ")[1].split(" ")[0] # I need to learn REGEX so bad, but it still works
            size = int(size)
            size /= 1000
            print(size, " ", days)
            score = size * days
            files[score] = (file_f.split(" ")[4], size)

        n_megs = n_gigs * 1000

        to_deplete = n_megs / 4

        while to_deplete > 0:
            min_score = max(files.keys())

            to_deplete -= files[min_score][1]
            print(f"{files[min_score][0]} {min_score:.3f}")
            files.pop(min_score)


import unittest
from AcceptanceTests.Bridges.MarketBridge.MarketProxyBridge import MarketProxyBridge
from AcceptanceTests.Bridges.MarketBridge.MarketRealBridge import MarketRealBridge
from AcceptanceTests.Bridges.UserBridge.UserProxyBridge import UserProxyBridge
from AcceptanceTests.Bridges.UserBridge.UserRealBridge import UserRealBridge
from AcceptanceTests.Tests.ThreadWithReturn import ThreadWithReturn

class UseCaseGetCartNEdit(unittest.TestCase):
    # use-case 2.8
    # get_cart functions has all products of a user from all the stores
    # also check changes in cart are working!
    # Proxies initialized
    proxy_market = MarketProxyBridge(MarketRealBridge())
    proxy_user = UserProxyBridge(UserRealBridge())

    def setUp(self):
        print("set-up")
        # assign system manager & login system manager
        self.proxy_user.appoint_system_manager("Manager", "1234", "0500000000", 1, 1, "Israel", "Beer Sheva",
                                               "Ben Gurion", 1, 1).getData()
        self.admin_id = self.proxy_user.login_guest().getData().getUserID()
        self.proxy_user.login_member(self.admin_id, "Manager", "1234")
        # create 5 users
        self.guest_id1 = self.proxy_user.login_guest().getData().getUserID()
        self.proxy_user.register("testUser1", "1234", "0540000000", 123, 5, "Israel", "Beer Sheva", "Rager", 1, 1)
        self.guest_id2 = self.proxy_user.login_guest().getData().getUserID()
        self.proxy_user.register("testUser2", "1234", "0540000000", 123, 5, "Israel", "Beer Sheva", "Rager", 1, 1)
        self.guest_id3 = self.proxy_user.login_guest().getData().getUserID()
        self.proxy_user.register("testUser3", "1234", "0540000000", 123, 5, "Israel", "Beer Sheva", "Rager", 1, 1)
        self.guest_id4 = self.proxy_user.login_guest().getData().getUserID()
        self.proxy_user.register("testUser4", "1234", "0540000000", 123, 5, "Israel", "Beer Sheva", "Rager", 1, 1)
        self.guest_id5 = self.proxy_user.login_guest().getData().getUserID()
        self.proxy_user.register("testUser5", "1234", "0540000000", 123, 5, "Israel", "Beer Sheva", "Rager", 1, 1)

        # 5 users log-in
        self.user_id1 = self.proxy_user.login_member(self.guest_id1, "testUser1", "1234").getData().getUserID()
        self.user_id2 = self.proxy_user.login_member(self.guest_id2, "testUser2", "1234").getData().getUserID()
        self.user_id3 = self.proxy_user.login_member(self.guest_id3, "testUser3", "1234").getData().getUserID()
        self.user_id4 = self.proxy_user.login_member(self.guest_id4, "testUser4", "1234").getData().getUserID()
        self.user_id5 = self.proxy_user.login_member(self.guest_id5, "testUser5", "1234").getData().getUserID()

        # Create 3 stores
        self.store_id1 = self.proxy_user.open_store("fruits_store", self.user_id1, 123, 1, "Israel", "Beer Sheva",
                                                    "Rager", 1, 00000).getData().getStoreId()
        self.store_id2 = self.proxy_user.open_store("cloths_store", self.user_id1, 123, 1, "Israel", "Beer Sheva",
                                                    "Rager", 1, 00000).getData().getStoreId()
        self.store_id3 = self.proxy_user.open_store("game_store", self.user_id1, 123, 1, "Israel", "Beer Sheva",
                                                    "Rager", 1, 00000).getData().getStoreId()

        # Add products to the stores
        self.p1_id = self.proxy_market.add_product_to_store(self.store_id1, self.user_id1, "apple", 10, "red_fruit", 15,
                                                            ["red"]).getData().getProductId()
        self.proxy_market.add_quantity_to_store(self.store_id1, self.user_id1, self.p1_id, 100)

        self.p2_id = self.proxy_market.add_product_to_store(self.store_id1, self.user_id1, "banana", 100,
                                                            "yellow_fruit", 10, ["yellow"]).getData().getProductId()
        self.proxy_market.add_quantity_to_store(self.store_id1, self.user_id1, self.p2_id, 100)

        self.p3_id = self.proxy_market.add_product_to_store(self.store_id2, self.user_id1, "shirt", 100,
                                                            "basic_clothing", 10, ["basic"]).getData().getProductId()
        self.proxy_market.add_quantity_to_store(self.store_id2, self.user_id1, self.p3_id, 100)

        self.p4_id = self.proxy_market.add_product_to_store(self.store_id2, self.user_id1, "pants", 100,
                                                            "basic_clothing", 10, ["basic"]).getData().getProductId()
        self.proxy_market.add_quantity_to_store(self.store_id2, self.user_id1, self.p4_id, 100)

        self.p5_id = self.proxy_market.add_product_to_store(self.store_id3, self.user_id1, "poker", 100, "gambling", 10,
                                                            ["gambling"]).getData().getProductId()
        self.proxy_market.add_quantity_to_store(self.store_id3, self.user_id1, self.p5_id, 100)

        self.p6_id = self.proxy_market.add_product_to_store(self.store_id3, self.user_id1, "monopoly", 100,
                                                            "board_games", 10, ["board"]).getData().getProductId()
        self.proxy_market.add_quantity_to_store(self.store_id3, self.user_id1, self.p6_id, 100)

    def tearDown(self):
        print("tear-down")
        # delete stores
        self.proxy_market.removeStoreForGood(self.user_id1, self.store_id1)
        self.proxy_market.removeStoreForGood(self.user_id1, self.store_id2)
        self.proxy_market.removeStoreForGood(self.user_id1, self.store_id3)
        # delete users
        self.proxy_user.removeMember("Manager", "testUser1")
        self.proxy_user.removeMember("Manager", "testUser2")
        self.proxy_user.removeMember("Manager", "testUser3")
        self.proxy_user.removeMember("Manager", "testUser4")
        self.proxy_user.removeMember("Manager", "testUser5")
        # remove system manager
        self.proxy_user.removeSystemManger_forTests("Manager")

    def test_cart_info_positive_simple(self):
        print("test_cart_info_positive_simple")
        bags = self.proxy_user.get_cart(self.user_id2).getData().getAllBags()
        self.assertEqual(len(bags), 0, "There should be no bags!")
        # add product to user2's cart
        self.proxy_user.add_product_to_cart(self.user_id2, self.store_id1, self.p1_id, 1)
        bags = self.proxy_user.get_cart(self.user_id2).getData().getAllBags()
        prods = list(bags.values())[0].getAllProducts()
        # user2 should have one bag (from one store)
        # user2 should have one product in the bag
        self.assertEqual(len(bags), 1, "There should only be one one bag.")
        self.assertEqual(len(prods), 1, "There should only be one product in the bag.")
        for prod in prods:
            self.assertEqual(prod.getProductId(), self.p1_id, "The product in the bag should be product1.")

        # teardown stuff - remove the prod from the cart
        self.proxy_user.remove_prod_from_cart(self.user_id2, self.store_id1, self.p1_id)

    def test_cart_info_positive_sequence_complex(self):
        print("test_cart_info_positive_sequence_complex")
        bags = self.proxy_user.get_cart(self.user_id2).getData().getAllBags()
        self.assertEqual(len(bags), 0, "There should be no bags!")
        # add products to cart
        self.proxy_user.add_product_to_cart(self.user_id2, self.store_id1, self.p1_id, 10)
        self.proxy_user.add_product_to_cart(self.user_id2, self.store_id1, self.p2_id, 10)
        self.proxy_user.add_product_to_cart(self.user_id2, self.store_id2, self.p3_id, 10)
        self.proxy_user.add_product_to_cart(self.user_id2, self.store_id2, self.p4_id, 10)
        self.proxy_user.add_product_to_cart(self.user_id2, self.store_id3, self.p5_id, 10)
        self.proxy_user.add_product_to_cart(self.user_id2, self.store_id3, self.p6_id, 10)
        # get all the bags in the cart of user2
        bags = self.proxy_user.get_cart(self.user_id2).getData().getAllBags()
        self.assertEqual(len(bags), 3, "There 3 different bags from 3 different stores.")
        # get all the products in the bags
        prods_all_bags = [list(bags.values())[0].getAllProducts(), list(bags.values())[1].getAllProducts(), list(bags.values())[2].getAllProducts()]
        # 2 products in each bag
        for bag in prods_all_bags:
            self.assertEqual(len(bag), 2, "There should be 2 prods in each bag")

        # remove product1 from cart
        self.proxy_user.remove_prod_from_cart(self.user_id2, self.store_id1, self.p1_id)
        prods1 = list(self.proxy_user.get_cart(self.user_id2).getData().getAllBags().values())[0].getAllProducts()
        self.assertEqual(len(prods1), 1, "We removed product1 from cart!")
        self.proxy_user.update_prod_from_cart(self.user_id2, self.store_id2, self.p3_id, 30)
        prods2 = list(self.proxy_user.get_cart(self.user_id2).getData().getAllBags().values())[1].getAllProducts()
        self.assertEqual(list(prods2.values())[0], 40, "We added 30 more pieces to product3!")

        # remove the rest of the products
        self.proxy_user.remove_prod_from_cart(self.user_id2, self.store_id1, self.p2_id)
        self.proxy_user.remove_prod_from_cart(self.user_id2, self.store_id2, self.p3_id)
        self.proxy_user.remove_prod_from_cart(self.user_id2, self.store_id2, self.p4_id)
        self.proxy_user.remove_prod_from_cart(self.user_id2, self.store_id3, self.p5_id)
        self.proxy_user.remove_prod_from_cart(self.user_id2, self.store_id3, self.p6_id)
        bags = self.proxy_user.get_cart(self.user_id2).getData().getAllBags()
        self.assertFalse(bags, "We removed all the products, bags should be empty.")

    def test_cart_info_threads(self):
        print("test_cart_info_threads")
        # only one buys each time!
        t = []
        # one buys product1
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args =(self.user_id3, self.store_id1, self.p1_id, 100)))
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args = (self.user_id4, self.store_id1, self.p1_id, 100)))
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args =(self.user_id5, self.store_id1, self.p1_id, 100)))
        t.append(ThreadWithReturn(
            target=self.proxy_user.add_product_to_cart, args = (self.user_id2, self.store_id1, self.p1_id, 100)))

        # one buys product3
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args = (self.user_id3, self.store_id2, self.p3_id, 100)))
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args = (self.user_id4, self.store_id2, self.p3_id, 100)))
        t.append(ThreadWithReturn(
            target=self.proxy_user.add_product_to_cart, args = (self.user_id5, self.store_id2, self.p3_id, 100)))
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args =(self.user_id2, self.store_id2, self.p3_id, 100)))

        # one buys product 5
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args=(self.user_id3, self.store_id3, self.p5_id, 100)))
        t.append(ThreadWithReturn(
            target=self.proxy_user.add_product_to_cart, args = (self.user_id4, self.store_id3, self.p5_id, 90)))
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args= (self.user_id5, self.store_id3, self.p5_id, 90)))
        t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart, args = (self.user_id2, self.store_id3, self.p5_id, 90)))

        for th in t:
            th.start()

        for th in t:
            th.join()

        bags= [self.proxy_user.get_cart(self.user_id2).getData().getAllBags(),
               self.proxy_user.get_cart(self.user_id3).getData().getAllBags(),
               self.proxy_user.get_cart(self.user_id4).getData().getAllBags(),
               self.proxy_user.get_cart(self.user_id5).getData().getAllBags()]

        bags_len = 0
        for bag in bags:
            bags_len += len(bag)
        self.assertEqual(bags_len, 3, "only 3 should succeed adding to cart.")

    # def test_add_n_remove_products_from_cart_threads(self):
    #     t = []
    #     for i in range(200):
    #         t.append(ThreadWithReturn(target=self.proxy_user.add_product_to_cart,
    #                               args=(self.user_id3, self.store_id1, self.p1_id, 1)))
    #     for th in t:
    #         th.start()
    #     success = 0
    #     fail = 0
    #     for th in t:
    #         if th.join().getData():
    #             success += 1
    #         else:
    #             fail += 1
    #     self.assertEqual(success,fail, "100 products in store - 100 should succeed to add and 100 should fail!")
    #
    #     t.clear()
    #     t.append(ThreadWithReturn(target=self.proxy_user.remove_prod_from_cart,
    #                               args=(self.user_id3, self.store_id1, self.p1_id)))
    #     t.append(ThreadWithReturn(target=self.proxy_user.remove_prod_from_cart,
    #                               args=(self.user_id3, self.store_id1, self.p1_id)))
    #     t[0].start()
    #     t[1].start()
    #     ans1 = t[0].join()
    #     ans2 = t[1].join()
    #     print(ans1.getData())
    #     print(ans2.getData())
    #     self.assertTrue(ans1.isError() or ans2.isError(), "you can only delete product from cart once!")

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


from math import sqrt

for _ in range(int(input())):
    n = int(input())
    points = list()
    prev = 0
    for i, x in enumerate(map(int, input().split())):
        if i % 2 == 0:
            prev = x
        else:
            points.append((prev, x))
    points.sort()
    ret = 1e9
    for i in range(n):
        x1, y1 = points[i]
        for j in range(max(0, i-8), i):
            x2, y2 = points[j]
            dist = (x1 - x2) ** 2 + (y1 - y2) ** 2
            if dist < ret:
                ret = dist
    print("{0:.4f}".format(sqrt(ret)))


from models.base_model import BaseModel
import tensorflow as tf
from models.utils.cnn_utils import conv_layer, fc_layer, dropout, max_pool, lrn, relu
from tensorflow.contrib.layers import flatten

class AlexNet(BaseModel):
    def __init__(self, sess, conf):
        super(AlexNet, self).__init__(sess, conf)
        self.build_network(self.x)
        if self.conf.mode != 'train_sequence' and self.conf.mode != 'test_sequence' and self.conf.mode != 'grad_cam_sequence':
            self.configure_network()

    def build_network(self, x):
        # Building network...
        with tf.variable_scope('CapsNet'):
            net = lrn(relu(conv_layer(x, kernel_size=7, stride=2, num_filters=96, trainable=self.conf.trainable,
                                      add_reg=self.conf.L2_reg, layer_name='CONV1')))
            net = max_pool(net, pool_size=3, stride=2, padding='SAME', name='MaxPool1')
            net = lrn(
                relu(conv_layer(net, kernel_size=5, stride=2, num_filters=256, trainable=self.conf.trainable,
                                add_reg=self.conf.L2_reg, layer_name='CONV2')))
            net = max_pool(net, pool_size=3, stride=2, padding='SAME', name='MaxPool2')
            net = relu(conv_layer(net, kernel_size=3, stride=1, num_filters=384, trainable=self.conf.trainable,
                                  add_reg=self.conf.L2_reg, layer_name='CONV3'))
            net = relu(conv_layer(net, kernel_size=3, stride=1, num_filters=384, trainable=self.conf.trainable,
                                  add_reg=self.conf.L2_reg, layer_name='CONV4'))
            self.net_grad = relu(
                conv_layer(net, kernel_size=3, stride=1, num_filters=256, trainable=self.conf.trainable,
                           add_reg=self.conf.L2_reg, layer_name='CONV5'))
            net = max_pool(self.net_grad, pool_size=3, stride=2, padding='SAME', name='MaxPool3')
            layer_flat = flatten(net)
            net = relu(fc_layer(layer_flat, num_units=512, add_reg=self.conf.L2_reg,
                                trainable=self.conf.trainable, layer_name='FC1'))
            net = dropout(net, self.conf.dropout_rate, training=self.is_training)
            net = relu(fc_layer(net, num_units=512, add_reg=self.conf.L2_reg,
                                trainable=self.conf.trainable, layer_name='FC2'))
            net = dropout(net, self.conf.dropout_rate, training=self.is_training)
            self.features = net
            self.logits = fc_layer(net, num_units=self.conf.num_cls, add_reg=self.conf.L2_reg,
                                   trainable=self.conf.trainable, layer_name='FC3')
            # [?, num_cls]
            self.prob = tf.nn.softmax(self.logits)
            # [?, num_cls]
            self.y_pred = tf.to_int32(tf.argmax(self.prob, 1))
            # [?] (predicted labels)


"""
Functions for identifying different states features.

Katerina Capouskova 2018, kcapouskova@hotmail.com
"""
import json
import logging
import os
import scipy

import numpy as np
from scipy.stats import stats

from utilities import create_dir

def probability_of_state(clusters, n_clusters, output_path):
    """
    Computes the probability of a state.

    :param clusters: clusters array
    :type clusters: np.ndarray
    :param n_clusters: number of clusters
    :type n_clusters: int
    :param output_path: path to output directory
    :type output_path: str
    :return: dictinory {state: probability}
    :rtype: dict
    """
    logging.basicConfig(
        filename=os.path.join(output_path, 'probability_of_states.log'),
        level=logging.INFO)
    dict = {}
    for n in range(n_clusters):
        separate_cluster = []
        for c in clusters:
            if c == n:
                separate_cluster.append(c)
        p = float(len(separate_cluster))/float(len(clusters))
        dict.update({n: p})
        logging.info('Probability of state: {} is: {}'.format(n, p))
    with open(os.path.join(output_path, 'probability.json'), 'w') as fp:
        json.dump(dict, fp)
    return dict

def mean_lifetime_of_state(clusters, n_clusters, output_path):
    """
    Computes the mean lifetime of a state.

    :param clusters: clusters array
    :type clusters: np.ndarray
    :param n_clusters: number of clusters
    :type n_clusters: int
    :param output_path: path to output directory
    :type output_path: str
    :return: dictinory {state: mean lifetime}
    :rtype: dict
    """
    # Feature of the data: Repetition time in seconds
    TR = 2
    dict = {}
    logging.basicConfig(
        filename=os.path.join(output_path, 'mean_lifetime_of_states.log'),
        level=logging.INFO)
    for n in range(n_clusters):
        state_true = []
        for c in clusters:
            if c == n:
                state_true.append(1)
            else:
                state_true.append(0)
        # create differences list
        diff_list = np.diff(state_true).tolist()
        # detect swithces in and out of states
        out_state = [i for i, j in enumerate(diff_list, 1) if j == 1]
        in_state = [i for i, j in enumerate(diff_list, 1) if j == -1]
        # discard cases where state starts or ends
        if len(in_state) > len(out_state):
            in_state.pop(0)
        elif len(out_state) > len(in_state):
            out_state.pop(-1)
        elif out_state and in_state and out_state[0] > in_state[0]:
            in_state.pop(0)
            out_state.pop(-1)
        else:
            pass
        if out_state and in_state:
            # minus two lists
            c_duration = []
            for i, z in zip(in_state, out_state):
                diff = i - z
                c_duration.append(diff)
        else:
            c_duration = 0
        mean_duration = np.mean(c_duration) * TR
        logging.info('Mean lifetime of state: {} is: {}'.format(n, mean_duration))
        dict.update({n: mean_duration})
    with open(os.path.join(output_path, 'mean_state_lifetime.json'), 'w') as fp:
        json.dump(dict, fp)
    return dict

def students_t_test(group_a, group_b, output_path):
    """
    Computes a student's t-test and p value for two groups.

    :param group_a: clusters array of a first group
    :type group_a: np.ndarray
    :param group_b: clusters array of a second group
    :type group_b: np.ndarray
    :param output_path: path to output directory
    :type output_path: str
    """
    create_dir(output_path)
    logging.basicConfig(
        filename=os.path.join(output_path, 'students_t_test.log'),
        level=logging.INFO)
    t, p = stats.ttest_ind(group_a, group_b)
    logging.info('T-test value: {}, p-value: {}'.format(t, p))
    dict = {'T-test value': t, 'p-value': p}
    with open(os.path.join(output_path, 'students_t_test.json'), 'w') as fp:
        json.dump(dict, fp)
    return t, p

def p_value_stars(p_value):
    """
    Returns the appropriate number of stars for the p_value

    :param p_value: p_value
    :type p_value: int
    :param output_path: path to output directory
    :type output_path: str
    """
    if p_value < 0.0001:
        return "****"
    elif (p_value < 0.001):
        return "***"
    elif (p_value < 0.01):
        return "**"
    elif (p_value < 0.05):
        return "*"
    else:
        return "-"

def distribution_probability_lifetime(clusters, output_path, n_clusters):
    """
    Creates a distribution of probabilities and life times of states

    :param clusters: clusters array
    :type clusters: np.ndarray
    :param output_path: path to output directory
    :type output_path: str
    :param n_clusters: number of clusters
    :type n_clusters: int
    :return: proba_list:array of probabilities, lifetimes_list: array of lifetimes
    :rtype: np.ndarray, np.ndarray
    """
    probas = probability_of_state(clusters, n_clusters, output_path)
    lifetimes = mean_lifetime_of_state(clusters, n_clusters, output_path)
    proba_list = []
    lifetimes_list = []
    for n in range(n_clusters):
        for elem in clusters:
            if elem == n:
                proba_list.append(probas[n])
                lifetimes_list.append(lifetimes[n])
    return np.array(proba_list), np.array(lifetimes_list)

def variance_of_states(reduced_components, output_path):
    """
    Computes the variance in states

    :param reduced_components: array with reduced components and labels
    predicted from clustering
    :type reduced_components: np.ndarray
    :param output_path: path to output directory
    :type output_path: str
    :return: variance: array of variances
    :rtype: np.ndarray
    """
    variance = np.var(reduced_components, axis=1)
    np.savez(os.path.join(output_path, 'variance'), variance)
    return variance

def entropy_of_states(probabilities, output_path, n_clusters):
    """
    Computes the entropy of probabilities of states

    :param probabilities: array with states probabilities
    :type probabilities: np.ndarray
    :param output_path: path to output directory
    :type output_path: str
    :param n_clusters: number of clusters
    :type: n_clusters: int
    :return: entropy: calculated entropy
    :rtype: int
    """
    logging.basicConfig(
        filename=os.path.join(output_path, 'entropy_n_clusters_{}.log'.format(
            n_clusters)),
        level=logging.INFO)
    entropy = scipy.stats.entropy(probabilities)
    logging.info('State {} entropy is {}'.format(n_clusters, entropy))
    dict = {'State': n_clusters, 'entropy': entropy}
    with open(os.path.join(output_path, 'entropy.json'), 'w') as fp:
        json.dump(dict, fp)
    return entropy


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

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

# Importing the dataset
dataset = pd.read_csv(r"F:\Udemy\Machine Learning\Machine Learning A-Z Template Folder\Part 4 - Clustering\Section 25 - Hierarchical Clustering\Mall_Customers.csv")
X = dataset.iloc[:, [3, 4]].values

# Using Dendogram

import scipy.cluster.hierarchy as sch

dendogram = sch.dendrogram(sch.linkage(X,method='ward'))
plt.title('Ddgram')
plt.xlabel('Customer')
plt.ylabel('Distance')
plt.show()

#fitting hierarchial

from sklearn.cluster import AgglomerativeClustering
hc = AgglomerativeClustering(n_clusters=5,affinity='euclidean',linkage='ward')
y_hc = hc.fit_predict(X)

#Visualising

plt.scatter(X[y_hc==0,0],X[y_hc==0,1],s=100, c='red', label='C1')
plt.scatter(X[y_hc==1,0],X[y_hc==1,1],s=100, c='blue', label='C2')
plt.scatter(X[y_hc==2,0],X[y_hc==2,1],s=100, c='green', label='C3')
plt.scatter(X[y_hc==3,0],X[y_hc==3,1],s=100, c='cyan', label='C4')
plt.scatter(X[y_hc==4,0],X[y_hc==4,1],s=100, c='magenta', label='C5')
plt.legend()
plt.show()
plt.scatter


from confluent_kafka import Consumer
from time import sleep
from json import loads
from datetime import datetime
from connect import connect
from table_creation import create_table_if_doesnt_exist

# Kafka configuration
bootstrap_servers = "host.docker.internal:29092"
#bootstrap_servers ='127.0.01:9092'
topic = 'test'
group_id = '0'

# Kafka consumer configuration
consumer_config = {
    'bootstrap.servers': bootstrap_servers,
    'group.id': group_id,
    'auto.offset.reset': 'earliest'
}

# Create Kafka consumer
try:
    print("Establishing connection to kafka server...")

    consumer = Consumer(consumer_config)
    consumer.subscribe([topic])

    print("Connection established!")

except Exception as e:
    print("Error while trying to establish kafka server connection")
    print(str(e))

# Create PostgreSQL database connection using connect.py script:

try:
    print("Establishing connection to PostgreSQL server...")
    sleep(10)
    conn = connect()
    cursor = conn.cursor()

    print("Connection established!")

except Exception as e:
    print("Error while trying to establish PostgreSQL server connection")
    print(str(e))

# Start consuming messages
if __name__ == '__main__':
    create_table_if_doesnt_exist()
    while True:
        msg = consumer.poll(1.0)
        if msg is None:

            continue
        if msg.error():
            print(f"Consumer error: {msg.error()}")
            continue
        try:
            # Parse the message value as the data to be inserted
            data = eval(msg.value().decode('utf-8'))

            print(f"Processing message: {data}")

            insert_query = "INSERT INTO flats VALUES (%s, %s, %s, %s, %s)"
            values = (data['url'], data['location'], data['date'],data['size'],data['price'])
            cursor.execute(insert_query, values)
            conn.commit()

            print("Message processed!")

        except Exception as e:
            print(f"Error processing message: {e}")
            conn.rollback()


# encyption and decryptor (ead)
# code name is :ctv0.1-a(Cesare test version 0.1-Alpha)
# code by RDAITA2
import string
from typing import MutableSequence
def encryption_cesare(msg,key=7):
    msg_encryption=""
    for car in msg:
        if car in string.ascii_uppercase and string.digits and string.punctuation:
            index = ord(car)+ key
            if index >ord('Z')and(100)and('@'):
                index=index - 26
            msg_encryption+=chr(index)
        else:
            msg_encryption+= car
    return msg_encryption

def decryptor_cesare(msg,key=7):
    msg_decryptor=""
    for car in msg:
        if car in string.ascii_uppercase and string.digits and string.punctuation:
            index = ord(car)- key
            if index <  ord('A')and(100)and('@'):
                index=index +26
            msg_decryptor+=chr(index)
        else:
             msg_decryptor+=car
    return msg_decryptor


# https://www.acmicpc.net/problem/16928

from collections import deque

n, m = map(int, input().split())

ladder = {}
snakes = {}

answer = [0 for _ in range(101)]
queue = deque([1])
visited = [0 for _ in range(101)]

# 사다리 정보 저장
for _ in range(n):
    x, y = map(int, input().split())

    ladder[x] = y

# 뱀 정보 저장
for _ in range(m):
    u, v = map(int, input().split())

    snakes[u] = v

def bfs():
    while queue:
        pos = queue.popleft()
        if pos == 100:
            print(answer[pos])
            break
        for i in range(6):
            nloc = pos + i + 1
            if nloc > 100 or nloc < 0:
                continue
            if nloc in ladder.keys():
                nloc = ladder[nloc]
            if nloc in snakes.keys():
                nloc = snakes[nloc]
            if not visited[nloc]:
                queue.append(nloc)
                visited[nloc] = 1
                answer[nloc] = answer[pos] + 1

visited[1] = 1
bfs()


import pandas as pd
import os
import torch
from transformers import BertTokenizer

# Paths
GOOD_TEXTS_PATH = './processed_texts/good_texts.csv'
BAD_TEXTS_PATH = './processed_texts/bad_texts.csv'
NON_TEXTS_PATH = './processed_texts/non_texts.csv'
TOKENIZED_DATA_PATH = './tokenized_data/'

# Load processed data
def load_processed_texts():
    good_texts_df = pd.read_csv(GOOD_TEXTS_PATH)
    bad_texts_df = pd.read_csv(BAD_TEXTS_PATH)
    non_texts_df = pd.read_csv(NON_TEXTS_PATH)

    return good_texts_df['Text'].tolist(), bad_texts_df['Text'].tolist(), non_texts_df['Text'].tolist()

# Tokenize
def tokenize_texts(good_texts, bad_texts, non_texts):
    tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
    max_length = 512  # adjust if necessary

    good_texts_encoded = tokenizer(good_texts, padding="max_length", truncation=True, return_tensors="pt", max_length=max_length)
    bad_texts_encoded = tokenizer(bad_texts, padding="max_length", truncation=True, return_tensors="pt", max_length=max_length)
    non_texts_encoded = tokenizer(non_texts, padding="max_length", truncation=True, return_tensors="pt", max_length=max_length)

    return good_texts_encoded, bad_texts_encoded, non_texts_encoded

# Save tokenized data
def save_tokenized_data(good_texts_encoded, bad_texts_encoded, non_texts_encoded):
    os.makedirs(TOKENIZED_DATA_PATH, exist_ok=True)
    torch.save(good_texts_encoded, os.path.join(TOKENIZED_DATA_PATH, 'good_texts_encoded.pt'))
    torch.save(bad_texts_encoded, os.path.join(TOKENIZED_DATA_PATH, 'bad_texts_encoded.pt'))
    torch.save(non_texts_encoded, os.path.join(TOKENIZED_DATA_PATH, 'non_texts_encoded.pt'))

if __name__ == "__main__":
    good_texts, bad_texts, non_texts = load_processed_texts()
    good_texts_encoded, bad_texts_encoded, non_texts_encoded = tokenize_texts(good_texts, bad_texts, non_texts)
    save_tokenized_data(good_texts_encoded, bad_texts_encoded, non_texts_encoded)


def to_csv(file):
    res = []
    with open(file, 'r') as result:
        for line in result:
            res.append(line.split()[:-1])
    for i in range(len(res)):
        if len(res[i]) >= 3:
            res[i] = [(' ').join(res[i][:-1]), res[i][-1]]
        else:
            res[i] = [res[i][0], res[i][1]]

    with open(''.join(file.split('.')[:-1]) + '.csv', 'w') as out:
        out.write('name, rank\n')
        for line in res:
            out.write("{0}, {1}\n".format(line[0], line[1]))

files = ['data/out-10-0.15.txt', 'data/out-10-0.3.txt', 'data/out-10-0.5.txt', 'data/out-10-0.7.txt',
         'data/out-10-0.85.txt']

for i in files:
    to_csv(i)


from os.path import join as path_join
import torch
import numpy as np
from torch.utils.data import Dataset
from sklearn.model_selection import KFold

def load_data_training(args, net=None):
    """
    Return two datasets for train and val
    """
    if args.debugging:
        X, y, model_type, model_coef = torch.load(path_join(args.data_folder, args.training_data_file),
            map_location=torch.device("cpu"))
    else:
        X, y = torch.load(path_join(args.data_folder, args.training_data_file),
            map_location=torch.device("cpu"))

    if "ODE_simulation" in args.training_data_file:
        X = X.reshape(1,-1,38).permute(0,2,1)
        y = y.reshape(1,-1,12).permute(0,2,1)
        Xtrain = X[:,:,0:-210000]
        ytrain = crop_data(Xtrain, y[:,:,0:-70000], net, args)

        Xval = X[:,:,-210000:]
        yval = crop_data(Xval, y[:,:,-70000:], net, args)
        dataset_train = MyDataset(Xtrain, ytrain, device=args.device, data_type=args.data_type)
        dataset_val = MyDataset(Xval, yval, device=args.device, data_type=args.data_type)
        return dataset_train, dataset_val

    if net is not None and not args.training_data_file.endswith("_v2_training.pt"):
        y = crop_data(X, y, net, args)

    data = MyDataset(X, y, device=args.device, data_type=args.data_type)

    num_batches = X.shape[0]
    val_batches = int(args.validation_fraction * num_batches)
    train_batches = num_batches - val_batches

    if args.use_cv and not args.training_data_file.endswith("_v2_training.pt"):
        split = KFold(args.cv_folds, shuffle=True, random_state=args.seed)
        num_batches = X.shape[0]
        train_idx, val_idx = list(split.split(np.arange(num_batches, dtype=int)))[args.cv_index]
        return data, train_idx, val_idx
    elif args.use_cv :
        assert args.cv_folds == 21
        assert args.cv_folds%3 == 0
        assert args.cv_index < args.cv_folds
        assert args.cv_index >= 0
        cv_folds = args.cv_folds
        cv_index = args.cv_index
        cv_folds_per_area = cv_folds//3
        cv_area_index = cv_index%cv_folds_per_area

        val_area = cv_index//cv_folds_per_area
        X_splitted = X#.split(1)
        y_splitted = y#.split(1)
        val_x_area = X_splitted[val_area].split(X.shape[-1]//cv_folds_per_area,dim=-1)
        val_y_area = y_splitted[val_area].split(y.shape[-1]//cv_folds_per_area,dim=-1)

        X_before_validation = [val_x_area[i] for i in range(cv_area_index)]
        X_after_validation = [val_x_area[i] for i in range(cv_area_index+1,len(val_x_area))]
        y_before_validation = [val_y_area[i] for i in range(cv_area_index)]
        y_after_validation = [val_y_area[i] for i in range(cv_area_index+1,len(val_y_area))]

        train_samples = [(X_splitted[i],y_splitted[i]) for i in range(3) if i != val_area]
        val_sample = [(val_x_area[cv_area_index], val_y_area[cv_area_index])]
        if len(X_before_validation) > 0:
            train_samples.append( (torch.hstack(X_before_validation), torch.hstack(y_before_validation)) )
        if len(X_after_validation) > 0:
            train_samples.append( (torch.hstack(X_after_validation), torch.hstack(y_after_validation)) )

        train_samples = crop_data_v2(train_samples, net, args)
        val_sample    = crop_data_v2(val_sample,    net, args)
        dataset_train = MyDataset_v2(train_samples, args.device, args.data_type)
        dataset_val = MyDataset_v2(val_sample, args.device, args.data_type)
        return dataset_train, dataset_val

    elif args.debugging:
        torch.random.manual_seed(args.seed)
        return torch.utils.data.dataset.random_split(data, [train_batches, val_batches]), model_type, model_coef, (X,y,data)
    else:
        torch.random.manual_seed(args.seed)
        return torch.utils.data.dataset.random_split(data, [train_batches, val_batches])

def load_data_testing(args, net=None):
    """
    Return a dataset for test
    """
    X, y = torch.load(path_join(args.data_folder, args.testing_data_file),
        map_location=torch.device("cpu"))
    if net is not None:
        y = crop_data(X, y, net, args)

    data = MyDataset(X, y, device=args.device, data_type=args.data_type)
    return data

class MyDataset(Dataset):
    def __init__(self, X: torch.Tensor, y: torch.Tensor, device=torch.device('cpu'), data_type=torch.float):
        self.X = X.to(device=device, dtype=data_type)
        self.y = y.to(device=device, dtype=data_type)
        self.device = device
        self.data_type = data_type

    def __len__(self):
        return self.X.shape[0]

    def __getitem__(self, index):
        if torch.is_tensor(index):
            index = index.tolist()
        return self.X[index, :, :], self.y[index, :, :]

class MyDataset_v2(Dataset):
    def __init__(self, samples, device=torch.device('cpu'), data_type=torch.float):
        self.samples = [(X.to(device=device, dtype=data_type),y.to(device=device, dtype=data_type)) for (X,y) in samples]
        self.device = device
        self.data_type = data_type

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

    def __getitem__(self, index:int):
        (X,y) = self.samples[index]
        return X, y

def crop_data(X, y, net, args):
    y_shape = net(torch.zeros((2, X.shape[1], X.shape[2]), dtype=args.data_type, device=args.device)).shape
    reduction = y.shape[-1] - y_shape[-1]
    print(reduction)
    if reduction==0:
        return y
    else:
        return y[:, :, int(reduction/2):(-int(reduction/2))]

def crop_data_v2(samples, net, args):
    samples_out = []
    for (X,y) in samples:
        y_shape = net(torch.zeros((1, X.shape[-2], X.shape[-1]), dtype=args.data_type, device=args.device)).shape
        reduction = y.shape[-1] - y_shape[-1]
        if reduction>0:
            y = y[:, int(reduction/2):(-int(reduction/2))]
        samples_out.append((X,y))
    return samples_out


import math
import Const

def x1(a1, b1):
    return b1 - (math.sqrt(5) - 1) / 2 * (b1 - a1)

def x2(a1, b1):
    return a1 + (math.sqrt(5) - 1) / 2 * (b1 - a1)

def golden_section():
    A = Const.a
    B = Const.b
    counter1 = 0
    counter2 = 2
    X1 = x1(A, B)
    X2 = x2(A, B)
    Y1 = Const.f(X1)
    Y2 = Const.f(X2)
    while B - A > Const.e:
        counter1 += 1
        if X2 < X1:
            X1, X2 = X2, X1
            Y1, Y2 = Y2, Y1
        if Y1 < Y2:
            B = X2
            X2 = x1(A, B)
            Y2 = Const.f(X2)
            counter2 += 1
        elif Y1 > Y2:
            A = X1
            X1 = x2(A, B)
            Y1 = Const.f(X1)
            counter2 += 1
        else:
            A = X1
            B = X2
            X1 = x1(A, B)
            X2 = x2(A, B)
            Y1 = Const.f(X1)
            Y2 = Const.f(X2)
            counter2 += 2
    return {"Локальный минимум": (A + B) / 2, "Количество итераций": counter1, "Количество вычислений": counter2}


import scrapy
from tripadvisor.items import TripadvisorItem

class TripadvisorSpider(scrapy.Spider):
    name = 'tripadvisor'
    allowed_domains = ['tripadvisor.com']
    start_urls = (
        'https://www.tripadvisor.com/Restaurants-g60974-Buffalo_New_York.html',
    )

    def parse(self, response):
        # process each restaurant link
        urls = response.xpath('//h3[@class="title"]/a/@href').extract()
        for url in urls:
            absolute_url = response.urljoin(url)
            request = scrapy.Request(
                absolute_url, callback=self.parse_restaurant)
            yield request

        # process next page
        next_page_url = response.xpath('//a[text()="Next"]/@href').extract_first()
        absolute_next_page_url = response.urljoin(next_page_url)
        request = scrapy.Request(absolute_next_page_url)
        yield request

    def parse_restaurant(self, response):
        item = TripadvisorItem()
        item['name'] = response.xpath(
            '//div[@class="mapContainer"]/@data-name').extract_first()
        item['rating'] = response.xpath(
            '//img[@property="ratingValue"]/@content').extract_first()
        item['latitude'] = response.xpath(
            '//div[@class="mapContainer"]/@data-lat').extract_first()
        item['longitude'] = response.xpath(
            '//div[@class="mapContainer"]/@data-lng').extract_first()
        item['url'] = response.url
        yield item


import discord
from discord.ext import commands
import os
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

bot = commands.Bot(command_prefix='g!', help_command=None)

@bot.command(name="help", description="ve la lista de comandos")
async def help(ctx):
    embed = discord.Embed(title= "help", description=f"lista de comandos", color=discord.Color.blue())
    embed.add_field(name='administracion', value='`say`, `anuncio`, `info`, `user`')

    embed.add_field(name='moderacion', value='`mute` ,`unmute` , `tempmute`, `kick`, `ban`')

    embed.add_field(name='diversion', value='`_8ball`, `avatar`, `kiss`, `mimir`, `cry`, `hug`, `punch`, `sabias`, `poli`, `pat`, `blush`, `nivel`, `l`, `scared`, `drog`', inline=False)
    await ctx.send(embed=embed)

@bot.event
async def on_ready():
    game = discord.Game('Beta v 0.0.4')
    await bot.change_presence(status=discord.Status.idle, activity=game)
    print('Bot cargado')

bot.load_extension("cogs.Misc")
bot.load_extension("cogs.Funny")
bot.load_extension("cogs.Admin")
bot.run(TOKEN)


import re

from analytics.internals.request.PageviewRequest import PageviewRequest
from analytics.internals.request.EventRequest import EventRequest
from analytics.internals.request.TransactionRequest import TransactionRequest
from analytics.internals.request.ItemRequest import ItemRequest
from analytics.internals.request.SocialInteractionRequest import SocialInteractionRequest

class AnalyticsError(Exception):
    pass

class Tracker(object):
    """
    @ivar account_id:
        Google Analytics account ID, e.g. "UA-1234567-8", will be mapped to "utmac" parameter

    @ivar domain_name:
        Host Name, e.g. "www.example.com", will be mapped to "utmhn" parameter

    @ivar allow_hash:
        Whether to generate a unique domain hash, default is true to be consistent
        with the GA Javascript Client

    @ivar custom_variables:
        dict of CustomVariable

    @ivar campaign:
        Campaign
    """

    VERSION = '5.2.2' # As of 15.11.2011
    """
    Google Analytics client version on which this library is built upon,
    will be mapped to "utmwv" parameter.

    This doesn't necessarily mean that all features of the corresponding
    ga.js version are implemented but rather that the requests comply
    with these of ga.js.

    @link http://code.google.com/apis/analytics/docs/gaJS/changelog.html
    """

    config = None
    """
    @type analytics.Config
    """

    def __init__(self, account_id, domain_name, config=None):
        Tracker.config = config

        self.allow_hash = True
        self.custom_variables = {}
        self.campaign = None

        self.account_id = account_id
        self.domain_name = domain_name

    RE_VALID_GA_ACCOUNT_ID = re.compile(r'UA-[0-9]-[0-9]')

    @property
    def account_id(self):
        return self._account_id

    @account_id.setter
    def account_id(self, value):
        if not Tracker.RE_VALID_GA_ACCOUNT_ID.match(value):
            raise ValueError('%s is not a valid Google Analytics account ID.' % value)

        self._account_id = value

    @property
    def domain_name(self):
        return self._domain_name

    @domain_name.setter
    def domain_name(self, value):
        self._domain_name = value

    @property
    def allow_hash(self):
        return self._allow_hash

    @allow_hash.setter
    def allow_hash(self, value):
        self._allow_hash = value

    def add_custom_variable(self, custom_variable):
        """
        Equivalent of _setCustomVar() in GA Javascript client.

        @link http://code.google.com/apis/analytics/docs/tracking/gaTrackingCustomVariables.html
        """
        # Ensure that all required parameters are set
        custom_variable.validate()

        index = custom_variable.index
        self.custom_variables[index] = custom_variable

    @property
    def custom_variables(self):
        return self._custom_variables

    def remove_custom_variable(self, index):
        """
        Equivalent of _deleteCustomVar() in GA Javascript client.
        """
        del self.custom_variables[index]

    @property
    def campaign(self):
        return self._campaign

    @campaign.setter
    def campaign(self, campaign = None):
        """
        Isn't really optional, but can be set to None
        """
        if campaign:
            # Ensure that all required parameters are set
            campaign.validate()

        self._campaign = campaign

    def track_pageview(self, page, session, visitor):
        """
        Equivalent of _trackPageview() in GA Javascript client.

        @link http://code.google.com/apis/analytics/docs/gaJS/gaJSApiBasicConfiguration.html#_gat.GA_Tracker_._trackPageview
        """
        request = PageviewRequest(Tracker.config)
        request.page = page
        request.session = session
        request.visitor = visitor
        request.tracker = self
        request.fire()

    def track_event(self, event, session, visitor):
        """
        Equivalent of _trackEvent() in GA Javascript client.

        @link http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEventTracking.html#_gat.GA_EventTracker_._trackEvent
        """
        # Ensure that all required parameters are set
        event.validate()

        request = EventRequest(Tracker.config)
        request.event = event
        request.session = session
        request.visitor = visitor
        request.tracker = self
        request.fire()

    def track_transaction(self, transaction, session, visitor):
        """
        Combines _addTrans(), _addItem() (indirectly) and _trackTrans() of GA Javascript client.
        Although the naming of "_addTrans()" would suggest multiple possible transactions
        per request, there is just one allowed actually.

        @link http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEcommerce.html#_gat.GA_Tracker_._addTrans
        @link http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEcommerce.html#_gat.GA_Tracker_._addItem
        @link http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEcommerce.html#_gat.GA_Tracker_._trackTrans
        """
        # Ensure that all required parameters are set
        transaction.validate()

        request = TransactionRequest(Tracker.config)
        request.setTransaction(transaction)
        request.setSession(session)
        request.setVisitor(visitor)
        request.setTracker(self)
        request.fire()

        # Every item gets a separate request,
        # see http://code.google.com/p/gaforflash/source/browse/trunk/src/com/google/analytics/v4/Tracker.as#312
        for item in transaction.getItems():
            # Ensure that all required parameters are set
            item.validate()

            request = ItemRequest(Tracker.config)
            request.setItem(item)
            request.setSession(session)
            request.setVisitor(visitor)
            request.setTracker(self)
            request.fire()

    """
      Equivalent of _track_social() in GA Javascript client.

    @link http://code.google.com/apis/analytics/docs/tracking/gaTrackingSocial.html#settingUp
    """
    def track_social(self, social_interaction, page, session, visitor):
        request = SocialInteractionRequest(Tracker.config)
        request.social_interaction = social_interaction
        request.page = page
        request.session = session
        request.visitor = visitor
        request.tracker = self
        request.fire()

    """
      For internal use only. Will trigger an error according to the current
      Config::errorSeverity setting.

    @see Config::errorSeverity
    @param string message
    @param string method
    """

    @classmethod
    def raiseError(cls, message, logger):
        from analytics.Config import Config

        if cls.config:
            errorSeverity = cls.config.getErrorSeverity()
        else:
            errorSeverity = Config.ERROR_SEVERITY_EXCEPTIONS

        if errorSeverity == Config.ERROR_SEVERITY_SILENCE:
            pass
        elif errorSeverity == Config.ERROR_SEVERITY_WARNINGS:
            logger.warning(message)
        elif errorSeverity == Config.ERROR_SEVERITY_EXCEPTIONS:
            raise AnalyticsError(message)


# Variaveis
qnt_ml = 0
valor_total = 0
valor_acompanhamentos = 0
valor_feijoada = 0

# Funções

def destaque(frase):  # Destacar uma frase
    print('=' * 33)
    print(f'{frase}')

def volumeFeijoada():  # Exigencia 1/3
    global valor_volume # Variavel global para armazenar valor
    while True:
        try:
            qnt_ml = float(input('Digite a quantidade da porção (em ml) de feijoada que você deseja: '))
            if 300 <= qnt_ml <= 5000:
                valor_volume = qnt_ml * 0.08
                print(f'O valor apenas da porção é: R$ {valor_volume:.2f}')
                break
            else:
                print('Não trabalhamos com quantidades abaixo de 300ml e nem maior que 5L')
                continue
        except ValueError:
            print('Você digitou um valor inválido, tente novamente!')
            continue
    print('=' * 35)

def opcaoFeijoada():   # Exigencia 2/3
    # Variaveis global para armazenar valor
    global valor_total
    global valor_feijoada
    global multiplicadorOpcao

    while True:
        print('Opções de feijoadas')
        print('b - Básica (Feijão, paiol e costelinha)')
        print('p - Premium (Feijão, paiol, costelinha e partes de porco)')
        print('s - Suprema (Feijão, paiol, costelinha, charque, calabresa e bacon)')
        opcaoFeijoada = input('Digite uma opção de feijoada: ')

        # Verificar Opções validas e somar valores do multiplicador
        if (opcaoFeijoada == 'b'):
            destaque('Você escolheu a feijoada básica.')
            multiplicadorOpcao = 1 # Multiplicador Opção
            valor_feijoada = valor_volume * multiplicadorOpcao
        elif (opcaoFeijoada == 'p'):
            destaque('Você escolheu a feijoada premium.')
            multiplicadorOpcao = 1.25 # Multiplicador Opção
            valor_feijoada = valor_volume * multiplicadorOpcao
        elif (opcaoFeijoada == 's'):
            destaque('Você escolheu a feijoada SUPREMA.')
            multiplicadorOpcao = 1.50  # Multiplicador Opção
            valor_feijoada = valor_volume * multiplicadorOpcao
        else:
            print('Opcão invalida, tente novamente!')
            continue
        break

    print(f'Subtotal: R$ {valor_feijoada:.2f}')
    print('=' * 33)
    valor_total += valor_feijoada

def acompanhamentoFeijoada():  # Exigencia 3/3
    # Variaveis global para armazenar valor
    global valor_total
    global valor_acompanhamentos

    while True:
        print('Deseja mais algum acompanhamento?')
        print('0 - Fechar conta (encerrar pedido)')
        print('1 - 200g de arroz ( + R$ 5,00)')
        print('2 - 150g de farofa especial ( + R$ 6,00)')
        print('3 - 100g de couve cozida ( + R$ 7,00)')
        print('4 - 1 laranja descascada ( + R$ 3,00)')
        try:
            escolha = int(input('>> '))  # Verificações com condições para acrescentar valor dos acompanhamentos
            if (escolha == 0):
                break
            elif (escolha == 1):
                valor_acompanhamentos += 5  # Somar valores dos acomapnhamentos
                valor_total += 5

            elif (escolha == 2):
                valor_acompanhamentos += 6  # Somar valores dos acomapnhamentos
                valor_total += 6

            elif (escolha == 3):
                valor_acompanhamentos += 7  # Somar valores dos acomapnhamentos
                valor_total += 7

            elif (escolha == 4):
                valor_acompanhamentos += 3  # Somar valores dos acomapnhamentos
                valor_total += 3
            else: # Caso usuário digitar uma opção invalida, acima de 4 ou abaixo de 0
                print('Opção invalida, tente novamente!')
                print(f'O valor total atual é: R$ {valor_total:.2f}')
                continue
            print(f'O valor total atual é: R$ {valor_total:.2f}')
        except ValueError: # Caso usuário digitar um caractere invalido (letra)
            print('Você digitou um acompanhamento inexistente, tente novamente!')
            print(f'O valor total atual é: R$ {valor_total:.2f}')
            continue

def encerramento():  # Passando os valores finais para o cliente
    print('=' * 43)
    print('Calculando valores, fechando a conta..')
    print('Detalhamento:')
    print(f'Valor do volume: R$ {valor_volume:.2f}')
    print(f'Opção: {multiplicadorOpcao:.2f}')
    print(f'Valor dos acompanhamentos: R$ {valor_acompanhamentos:.2f}')
    print('Pedido finalizado, total a pagar: R$ {:.2f}'.format(valor_total))
    print('=' * 43)

# Menu Feijoada
print(' '* 14 ,'|   Menu Volume de Feijoada    |')
print(' '* 14 ,'================================')

# inicio - boas vindas
dono = 'Jose Gabriel Lopes'
ru = '4181998'
print('=' * 62)
print(f' Bem Vindo ao Restaurante do {dono} - RU: {ru}')
print('=' * 62)

# Chamando funções para rodar o código

volumeFeijoada()
opcaoFeijoada()
acompanhamentoFeijoada()
encerramento()


import os
import requests
import time

os.system("title Simple text to ASCII")

print("""

Simple text to ASCII | By King Herod

        Input text

""")

text = input(">")

convert = requests.get("http://artii.herokuapp.com/make?text=" + text)

log = open("ascii.txt", "w")
log.write(str(convert.text))
log.close()

print("Converted " + text + " to ASCII\n\nASCII has been logged in ascii.txt")

print("\n\n\nClosing in 10 seconds...")
time.sleep(10)
os.system("exit")


#You are given two non-empty linked lists representing two non-negative integers.
#The digits are stored in reverse order, and each of their nodes contains a single digit.
#Add the two numbers and return the sum as a linked list.
#You may assume the two numbers do not contain any leading zero, except the number 0 itself.

class Solution:
    #change Linked list to List
    def node2list(self, node1: ListNode) -> List: #linked list -> list
        list1 = []
        while node1 != None :
            list1.append(node1.val)
            node1 = node1.next
        return list1

    #change List to Linked List
    def list2node(self, list1: List) -> ListNode:
        result_node = ListNode()
        for i,num in enumerate(list1):
            if i == 0 :
                result_node.val = num
            else :
                node = result_node
                while node.next != None:
                    node = node.next
                node.next = ListNode(num)
        return result_node

    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        l1 = self.node2list(l1)
        l2 = self.node2list(l2)
        l1 = ''.join(map(str, l1))[::-1]
        l2 = ''.join(map(str, l2))[::-1]
        l3 = list(map(int, list(str(int(l1) + int(l2)))[::-1]))

        return self.list2node(l3)


class Node:
    def __init__(self, value, level, column):
        self.value = value
        self.level = level
        self.column = column
        self.left = None
        self.right = None

    def insert(self, value, level):
        if value < self.value:
            if self.left is None:
                self.left = Node(value, level+1, self.column - 1)
            else:
                self.left.insert(value, level+1)
        elif value > self.value:
            if self.right is None:
                self.right = Node(value, level+1, self.column + 1)
            else:
                self.right.insert(value, level+1)

    def get_all(self, all_values):
        all_values.append((self.value, self.column, self.level))
        if self.left is not None:
            self.left.get_all(all_values)
        if self.right is not None:
            self.right.get_all(all_values)

for _ in range(int(input())):
    n = int(input())
    values = list(map(int, input().split()))

    root = Node(values[0], 0, 0)

    for i in range(1, n):
        root.insert(values[i], 0)

    order = list()
    root.get_all(order)

    order.sort(key=lambda x: (x[1], x[2], x[0]))
    order = [z[0] for z in order]

    print(" ".join(map(str, order)))


"""
this is a file that will use the node and linked list class to traverse a linked list
"""

class Node:
    def __init__(self, data):
        self.data = data
        self.link = None

class LinkedList:
    def __init__(self):
        self.head = None

    def printList(self):
        temp = self.head

        while(temp):
            print(temp.data)
            temp = temp.link

    # using to pointers curr and prev
    def reverse_list(self,head):
        # initalize pointers
        prev, curr = None, head
        # keep going until end of linked list
        while curr:
            # temp varaible
            nxt = curr.link
            curr.link = prev
            prev = curr
            curr = nxt
        return prev

if __name__ == "__main__":

    llist = LinkedList()

    llist.head = Node("first node")
    second = Node("second node")
    third = Node("third node")

    llist.head.link = second
    second.link = third

llist.printList()


# Author: Allen Anker
# Created by Allen Anker on 24/09/2018
"""
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
"""

class Solution:
    def missing_number(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums = sorted(nums)
        i = 0
        while i < len(nums):
            if nums[i] != i:
                return i
            i += 1
        return len(nums)

solution = Solution()
nums = [0, 3, 1]
print(solution.missing_number(nums))


#!/usr/bin/env python3

from is_prime import is_prime

def goldbach(n):
    numbers = [(x, y) for x in range(1, n)
               for y in range(1, n)
               if is_prime(x)  # True
               if is_prime(y)  # True
               if x <= y
               if (x + y) == n]
    return numbers

def main():
    print(goldbach(52))

if __name__ == '__main__':
    main()


import datetime
import time
import winsound

class Lembrete:
    def __init__(self, horario, data, dosagem, medicamento):
        self.horario = horario
        self.data = data
        self.dosagem = dosagem
        self.medicamento = medicamento
        self.notificacao_ativa = False

    def criar_alarme(medicamento, dosagem, data, horario):
        while True:
            agora = datetime.datetime.now()
            alarme = datetime.datetime.strptime(data + ' ' + horario, '%d/%m/%Y %H:%M')

            if agora >= alarme:
                print(f"Alarme para {medicamento}! Hora de tomar {dosagem}.")
                winsound.Beep(1000, 1000)  # Emite um som de alarme (Windows)
                break

            time.sleep(60)

    def ativar_notificacao(self):
        self.notificacao_ativa = True
        print("Notificação ativada")

    def desativar_notificacao(self):
        self.notificacao_ativa = False
        print("Notificação desativada")

    def enviar_notificacao(self):
        if self.notificacao_ativa:
            mensagem = f"Lembrete: É hora de tomar {self.dosagem} de {self.medicamento.nome}"
            print(mensagem)
        else:
            print("Notificação desativada")


import utils
import matplotlib.pyplot as plt

# Anzahl aller Knoten im Netzwerk
nodes_number = 256
# Anzahl der korrumpierten Knoten
corrupted_number = 112
# Anzahl der Cluster im Netzwerk
cluster_number = 32
# Anzahl der ausgewählten Nodes pro Cluster
picked_nodes_number = 0
# Anzahl der Iterationen für die Simulation
iteration_number = 10000
# Anzahl der gleichen Ergebnisse im gesamten Quorum
threshold = 0.5
# Anzahl der gleichen Ergebnisse im Nested Quorum
nested_threshold = 0.5

nodes_per_cluster = int(nodes_number / cluster_number)

debug = False

x = []
y = []

selection = list(range(nodes_per_cluster+1))
for count in selection:

    picked_nodes_number = count
    if nodes_per_cluster < picked_nodes_number:
        break

    x.append(count)
    successful_corrupted_number = 0

    for _ in range(iteration_number):
        # Create clusters
        clusters = utils.create_clusters(nodes_number, cluster_number)
        if debug:
            print('clusters:' + str(clusters))

        # Create corrupted nodes
        corrupted_clusters = utils.create_equaly_corrupted_clusters(clusters, corrupted_number)
        if debug:
            print('corrupted clusters:' + str(corrupted_clusters))

        corrupted_clusters_after_selection = utils.select_nodes_in_clusters(corrupted_clusters, picked_nodes_number, debug)
        if debug:
            print('corrupted clusters after selection:' + str(corrupted_clusters_after_selection))

        successful_corrupted_cluster_number = 0
        for cluster in corrupted_clusters_after_selection:
            if sum(cluster) > (nested_threshold * picked_nodes_number):
                successful_corrupted_cluster_number += 1

        successful_corrupted_ratio = successful_corrupted_cluster_number / cluster_number
        if successful_corrupted_ratio > threshold:
            successful_corrupted_number += 1

    success_rate = successful_corrupted_number / iteration_number
    y.append(success_rate)

    print('Picked nodes in cluster: ' + str(picked_nodes_number))
    print('Successful corrupted: ' + str(successful_corrupted_number))
    print('Successful corrupted ratio: ' + str(success_rate))
    print('-'*100)

fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot(x, y)
plt.show()