from __future__ import print_function, division  # requires Python >= 2.6

# numpy and scipy imports
import numpy as np
import math
from scipy.sparse import kron, identity
from scipy.sparse.linalg import eigsh  # Lanczos routine from ARPACK

from collections import namedtuple

####Initial parameter
#physical parameter
J = 1
Jz = 1

#number of states kept
Nstate = 10
#number of iterations
Nlength = 100

#exact solution
ExactEnergy = -math.log(2) + 0.25

Block = namedtuple("Block", ["length", "basis_size", "operator_dict"])
EnlargedBlock = namedtuple("EnlargedBlock", ["length", "basis_size", "operator_dict"])

def is_valid_block(block):
    for op in block.operator_dict.values():
        if op.shape[0] != block.basis_size or op.shape[1] != block.basis_size:
            return False
    return True

is_valid_enlarged_block = is_valid_block

# Model-specific code for the Heisenberg XXZ chain
model_d = 2  # single-site basis size

Sz1 = np.array([[0.5, 0], [0, -0.5]], dtype='d')  # single-site S^z
Sp1 = np.array([[0, 1], [0, 0]], dtype='d')  # single-site S^+

H1 = np.array([[0, 0], [0, 0]], dtype='d')  # single-site portion of H is zero

def H2(Sz1, Sp1, Sz2, Sp2):  # two-site part of H
    return (
        (J / 2) * (kron(Sp1, Sp2.conjugate().transpose()) + kron(Sp1.conjugate().transpose(), Sp2)) +
        Jz * kron(Sz1, Sz2)
    )

initial_block = Block(length=1, basis_size=model_d, operator_dict={
    "H": H1,
    "conn_Sz": Sz1,
    "conn_Sp": Sp1,
})

def enlarge_block(block):
    mblock = block.basis_size
    o = block.operator_dict

    enlarged_operator_dict = {
        "H": kron(o["H"], identity(model_d)) + kron(identity(mblock), H1) + H2(o["conn_Sz"], o["conn_Sp"], Sz1, Sp1),
        "conn_Sz": kron(identity(mblock), Sz1),
        "conn_Sp": kron(identity(mblock), Sp1),
    }

    return EnlargedBlock(length=(block.length + 1),
                         basis_size=(block.basis_size * model_d),
                         operator_dict=enlarged_operator_dict)

def rotate_and_truncate(operator, transformation_matrix):
    return transformation_matrix.conjugate().transpose().dot(operator.dot(transformation_matrix))

def single_dmrg_step(sys, env, m):
    assert is_valid_block(sys)
    assert is_valid_block(env)

    # Enlarge each block by a single site.
    sys_enl = enlarge_block(sys)

    if sys is env:  # no need to recalculate a second time
        env_enl = sys_enl
    else:
        env_enl = enlarge_block(env)

    assert is_valid_enlarged_block(sys_enl)
    assert is_valid_enlarged_block(env_enl)

    # Construct the full superblock Hamiltonian.
    m_sys_enl = sys_enl.basis_size
    m_env_enl = env_enl.basis_size
    sys_enl_op = sys_enl.operator_dict
    env_enl_op = env_enl.operator_dict
    superblock_hamiltonian = kron(sys_enl_op["H"], identity(m_env_enl)) + kron(identity(m_sys_enl), env_enl_op["H"]) + \
                             H2(sys_enl_op["conn_Sz"], sys_enl_op["conn_Sp"], env_enl_op["conn_Sz"], env_enl_op["conn_Sp"])

    energy, psi0 = eigsh(superblock_hamiltonian, k=1, which="SA")

    psi0 = psi0.reshape([sys_enl.basis_size, -1], order="C")
    rho = np.dot(psi0, psi0.conjugate().transpose())

    evals, evecs = np.linalg.eigh(rho)
    possible_eigenstates = []
    for eval, evec in zip(evals, evecs.transpose()):
        possible_eigenstates.append((eval, evec))
    possible_eigenstates.sort(reverse=True, key=lambda x: x[0])  # largest eigenvalue first

    my_m = min(len(possible_eigenstates), m)
    transformation_matrix = np.zeros((sys_enl.basis_size, my_m), dtype='d', order='F')
    for i, (eval, evec) in enumerate(possible_eigenstates[:my_m]):
        transformation_matrix[:, i] = evec

    truncation_error = 1 - sum([x[0] for x in possible_eigenstates[:my_m]])
    print("truncation error:", truncation_error)

    new_operator_dict = {}
    for name, op in sys_enl.operator_dict.items():
        new_operator_dict[name] = rotate_and_truncate(op, transformation_matrix)

    newblock = Block(length=sys_enl.length,
                     basis_size=my_m,
                     operator_dict=new_operator_dict)

    return newblock, energy

def graphic(sys, env):
    graphic = ("=" * sys.length) + "**" + ("-" * env.length)
    return graphic

def infinite_system_algorithm(L, m):
    # initial
    block = initial_block
    # Repeatedly enlarge the system by performing a single DMRG step, using a
    # reflection of the current block as the environment.
    while 2 * block.length < L:
        print("L =", block.length * 2 + 2)
        print(graphic(block, block))
        block, energy = single_dmrg_step(block, block, m=m)
        print("E/L =", energy / (block.length * 2))
        print("error=", ExactEnergy - energy / (block.length * 2))

if __name__ == "__main__":
    np.set_printoptions(precision=10, suppress=True, threshold=10000, linewidth=300)

    infinite_system_algorithm(L=Nlength, m=Nstate)


import math
from enum import Enum
from numbers import Number
from typing import Tuple

import torch
import torch.nn.functional as F
import torch.distributed as dist
from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR
from accelerate import init_empty_weights

from transformers import (
    AutoModelForCausalLM,
    AutoConfig,
    mpu,
    ParallelOPTForCausalLM,
    ParallelGPTJForCausalLM,
    ParallelGPT2LMHeadModel,
    ParallelLlamaForCausalLM)

parallel_model_map = {
    "opt": ParallelOPTForCausalLM,
    "gpt2": ParallelGPT2LMHeadModel,
    "gptj": ParallelGPTJForCausalLM,
    "llama": ParallelLlamaForCausalLM
}

def get_entropy(gen_logits, inf_mask, mask, model_parallel=False):
    inf_mask = torch.isinf(gen_logits) | inf_mask
    if model_parallel:
        full_probs = mpu.parallel_softmax(gen_logits.float(), dim=-1)
        full_logprobs = mpu.parallel_log_softmax(gen_logits.float(), dim=-1)
        full_logprobs = full_logprobs.masked_fill(inf_mask, 0)
        ent = -mpu.parallel_sum(full_probs * full_logprobs, dim=-1)
    else:
        full_probs = F.softmax(gen_logits, dim=-1, dtype=torch.float32)
        full_logprobs = F.log_softmax(gen_logits, dim=-1, dtype=torch.float32)
        full_logprobs = full_logprobs.masked_fill(inf_mask, 0)
        ent = -torch.sum(full_probs * full_logprobs, dim=-1)
    ent = ent * mask
    return ent

def get_log_probs(logits, ids, mask, inf_mask=None, model_parallel=False):
    if model_parallel:
        logprobs = -mpu.parallel_logprobs(logits, ids)
        if inf_mask is not None:
            gathered_inf_mask = mpu.parallel_gather(inf_mask, -1, ids.unsqueeze(-1)).squeeze(-1)
            logprobs = logprobs.masked_fill(gathered_inf_mask, -float("inf"))
        # logprobs = mpu.parallel_log_softmax(logits.float(), dim=-1)
        # if inf_mask is not None:
        #     logprobs = logprobs.masked_fill(inf_mask, -float("inf"))
        # logprobs = mpu.parallel_gather(logprobs, -1, ids.unsqueeze(-1)).squeeze(-1)
    else:
        logprobs = F.log_softmax(logits, dim=-1)
        if inf_mask is not None:
            logprobs = logprobs.masked_fill(inf_mask, -float("inf"))
        logprobs = torch.gather(logprobs, dim=-1, index=ids.unsqueeze(-1)).squeeze(-1)
    logprobs = logprobs.masked_fill(~(mask.bool()), 0)

    # we ensure that the selected logprobs are not inf or nan
    assert all((~torch.isinf(logprobs.view(-1))) & (~torch.isnan(logprobs.view(-1))))

    return logprobs

def get_x_entropy(logits_1, logits_2, inf_mask, mask, model_parallel=False):
    inf_mask = torch.isinf(logits_1) | torch.isinf(logits_2) | inf_mask
    if model_parallel:
        full_probs = mpu.parallel_softmax(logits_1.float(), dim=-1)
        full_logprobs = mpu.parallel_log_softmax(logits_2.float(), dim=-1)
        full_logprobs = full_logprobs.masked_fill(inf_mask, 0)
        xent = -mpu.parallel_sum(full_probs * full_logprobs, dim=-1)
    else:
        full_probs = F.softmax(logits_1, dim=-1, dtype=torch.float32)
        full_logprobs = F.log_softmax(logits_2, dim=-1, dtype=torch.float32)
        full_logprobs = full_logprobs.masked_fill(inf_mask, 0)
        xent = -torch.sum(full_probs * full_logprobs, dim=-1)
    xent = xent * mask
    return xent

def get_rev_kl(log_p, log_q, mask):
    log_ratio = (log_p - log_q) * mask
    kl = log_ratio.float().exp() - 1 - log_ratio
    return kl

def get_global_statistics(xs: torch.Tensor) -> Tuple[float, float, int]:
    """
    Computes element-wise mean and variance of the tensor across processes
    """
    sum_and_count = torch.tensor([xs.sum(), xs.numel()], device=xs.device)
    dist.all_reduce(sum_and_count, dist.ReduceOp.SUM)
    global_sum, count = sum_and_count
    global_mean = global_sum / count

    sum_var = torch.sum((xs - global_mean) ** 2)
    dist.all_reduce(sum_var, dist.ReduceOp.SUM)
    global_var = sum_var / count
    return global_mean, global_var, count

def whiten(xs: torch.Tensor, shift_mean=True, distributed=True) -> torch.Tensor:
    """Whitens values"""
    if distributed and dist.is_initialized():
        mean, var, _ = get_global_statistics(xs)
    else:
        var, mean = torch.var_mean(xs)

    whitened = (xs - mean) * torch.rsqrt(var + 1e-8)
    if not shift_mean:
        whitened += mean
    return whitened

def significant(x: Number, ndigits=2) -> Number:
    """
    Cut the number up to its `ndigits` after the most significant
    """
    if isinstance(x, torch.Tensor):
        x = x.item()

    if not isinstance(x, Number) or x == 0:
        return x

    return round(x, ndigits - int(math.floor(math.log10(abs(x)))))

class OptimizerName(str, Enum):
    """Supported optimizer names"""

    ADAM: str = "adam"
    ADAMW: str = "adamw"
    ADAM_8BIT_BNB: str = "adam_8bit_bnb"
    ADAMW_8BIT_BNB: str = "adamw_8bit_bnb"
    SGD: str = "sgd"

def get_optimizer_class(name: OptimizerName):
    """
    Returns the optimizer class with the given name

    Args:
        name (str): Name of the optimizer as found in `OptimizerNames`
    """
    if name == OptimizerName.ADAM:
        return torch.optim.Adam
    if name == OptimizerName.ADAMW:
        return torch.optim.AdamW
    if name == OptimizerName.SGD.value:
        return torch.optim.SGD
    supported_optimizers = [o.value for o in OptimizerName]
    raise ValueError(
        f"`{name}` is not a supported optimizer. "
        f"Supported optimizers are: {supported_optimizers}"
    )

class SchedulerName(str, Enum):
    """Supported scheduler names"""

    COSINE_ANNEALING = "cosine_annealing"
    LINEAR = "linear"

def get_scheduler_class(name: SchedulerName):
    """
    Returns the scheduler class with the given name
    """
    if name == SchedulerName.COSINE_ANNEALING:
        return CosineAnnealingLR
    if name == SchedulerName.LINEAR:
        return LinearLR
    supported_schedulers = [s.value for s in SchedulerName]
    raise ValueError(
        f"`{name}` is not a supported scheduler. "
        f"Supported schedulers are: {supported_schedulers}"
    )


print('Calculadora Iniciada!!!\n')
info = 1; soma = 0; sub = 0; mult = 0; div = 0; poten = 1; num1 = 0; num2 = 0

def calcular_soma(num1: float, num2: float, soma: float):
    num1 = float(input('\n\nDigite um Número: '))
    num2 = float(input('Digite outro Número: '))
    soma = num1 + num2
    print('A soma do número',num1,'com o número',num2,'resulta em',soma,'\n')

def calcular_subtracao(num1: float, num2: float, sub: float):
    num1 = float(input('\n\nDigite um Número: '))
    num2 = float(input('Digite outro Número: '))
    sub = num1 - num2
    print('A subtração do número',num1,'pelo o número',num2,'resulta em',sub,'\n')

def calcular_multiplicacao(num1: float, num2: float, mult: float):
    num1 = float(input('\n\nDigite um Número: '))
    num2 = float(input('Digite outro Número: '))
    mult = num1 * num2
    print('A multiplicação do número',num1,'pelo o número',num2,'resulta em',mult,'\n')

def calcular_divisao(num1: float, num2: float, div: float):
    num1 = float(input('\n\nDigite um Número: '))
    num2 = float(input('Digite outro Número: '))
    div = num1 / num2
    print('A divisão do número',num1,'pelo o número',num2,'resulta em',div,'\n')

def calcular_potencia(num1: float, num2: int, poten: float):
    num1 = float(input('\n\nDigite o Número da base que deseja elevar a uma potência: '))
    num2 = int(input('Digite o valor do expoente: '))
    for _ in range(0, num2):
        poten = poten * num1
    print('A potencia da base número ',num1,'elevada pelo o número',num2,'resulta em',poten,'\n')

while info == 1:
    op = int(input('Digite um número sendo\n1- para soma\n2- para subtração\n3- para multiplicação\n4- para divisão\n5- Para potenciação\n'))

    if op == 1:
        calcular_soma(num1, num2, soma)

    if op == 2:
        calcular_subtracao(num1, num2, sub)

    if op == 3:
        calcular_multiplicacao(num1, num2, mult)

    if op == 4:
        calcular_divisao(num1, num2, div)

    if op == 5:
        calcular_potencia(num1, num2, poten)

    info = int(input('Deseja fazer outra operação ?\nDigite o número 1 para fazer outra operação ou qualquer outro número para encerrar.\n'))
print('\nCalculadora Encerrada!!!!')


from django.test import TestCase, Client
from shortener_url.models import Url
from rest_framework import status
import json

class TestShortenerUrl(TestCase):

    def setUp(self):
        Url.objects.create(original_url="https://web.whatsapp.com/", custom_alias="whatsapp", shortened_url="http://shortener/u/whatsapp")

    def test_shortener_alias(self):
        data = {
            'url': 'http://www.google.com.br',
            'CUSTOM_ALIAS': 'google'
        }
        response = self.client.post('/create', json.dumps(data), content_type="application/json")
        self.assertEqual(status.HTTP_201_CREATED, response.status_code)

    def test_shortener_without_url(self):
        data = {
            'url': '',
            'CUSTOM_ALIAS': ''
        }
        response = self.client.post('/create', json.dumps(data), content_type="application/json")
        self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)

    def test_shortener(self):
        data = {
            'url': 'https://www.youtube.com/',
            'CUSTOM_ALIAS': ''
        }
        response = self.client.post('/create', json.dumps(data), content_type="application/json")
        self.assertEqual(status.HTTP_201_CREATED, response.status_code)

    def test_shortener_existing_alias(self):
        data = {
            'url': 'https://web.whatsapp.com/',
            'CUSTOM_ALIAS': 'whatsapp'
        }
        response = self.client.post('/create', json.dumps(data), content_type="application/json").json()
        self.assertEqual('001', response['err_code'])

class TestRetrieveUrl(TestCase):

    def setUp(self):
        Url.objects.create(original_url="https://web.whatsapp.com/", custom_alias="whatsapp", shortened_url="http://shortener/u/whatsapp")

    def test_retrieve_alias(self):
        response = self.client.get('/retrieve/whatsapp')
        self.assertEqual(status.HTTP_302_FOUND, response.status_code)

    def test_retrieve_url_not_found(self):
        response = self.client.get('/retrieve/gmail').json()
        self.assertEqual('002', response['err_code'])

    def test_retrieve_without_alias(self):
        response = self.client.get('/retrieve/')
        self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)

class TestTopVisitedUrl(TestCase):

    def test_top_visited_url(self):
        response = self.client.get('/top_visited')
        self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)


import tkinter as tk
from PIL import ImageTk, Image

class Caption:
    """ """
    text = ''

    lastx = None
    lasty = None
    speech_bubble = 'imgs/spb-300x165.png'
    thought_bubble = 'imgs/thought.png'

    long_sample = ("I am the hope of the universe. I am the answer to all living things "
                   "that cry out for peace. I am protector of the innocent. I am the "
                   "light in the darkness. I am truth. Ally to good! Nightmare to you!")

    def __init__(self, canvas, caption_text=None, bubble_type='speech', position={'x': 0, 'y': 0}):
        self.canvas = canvas
        if not caption_text:
            self.text = caption_text
        self.type = bubble_type  # 'speech' or 'thought'
        self.speech_img = ImageTk.PhotoImage(Image.open(self.speech_bubble))
        self.thought_img = ImageTk.PhotoImage(Image.open(self.thought_bubble))
        self.lastx, self.lasty = position

        if bubble_type == 'thought':
            bg_image = self.thought_img
            text_posx = position['x'] + 50
            text_posy = position['y'] + 50
        else:
            bg_image = self.speech_img
            text_posx = position['x'] + 75
            text_posy = position['y'] + 25

        self.cid = self.canvas.create_image(position['x'], position['y'], anchor=tk.NW, image=bg_image)
        caption_tag = 'caption-{}'.format(int(self.cid / 2))  # local caption id
        layer_tag = 'layer-{}'.format(1)
        self.canvas.itemconfig(self.cid, tag=(caption_tag, layer_tag))

        # caption text
        self.tid = self.canvas.create_text(text_posx, text_posy,
                                           anchor=tk.NW,
                                           width=200,
                                           text=caption_text,
                                           tags='caption-text')
        # caption_text_tag = 'caption-{}-text'.format(self.cid)
        # canvas.addtag_withtag(caption_text_tag, tid)
        self.canvas.itemconfig(self.tid, tag=(caption_tag, layer_tag))

        print(caption_tag)


from typing import List, Dict

from fastapi import WebSocket
from fastapi import HTTPException, status

from sqlalchemy import exc
from sqlalchemy.ext.asyncio import AsyncSession

from database.models.chat_models.chat_model import Chat
from database.models.chat_models.members_model import ChatMember
from database.models.chat_models.messages_model import Message
from src.schemas.chat_schema import CreateUserRoom, SaveMessage, MessageOut, ChatMemberOut

class ChatCrud:
    def __init__(self, db_session: AsyncSession) -> None:
        self._session: AsyncSession = db_session

    async def _close_session(self):
        if self._session.is_active:
            await self._session.close()

    async def _get_chat_by_id(self, chat_id) -> Chat | None:
        return await self._session.get(Chat, chat_id)

    async def get_chat_history(self, chat_id: int) -> List[MessageOut]:
        chat: Chat = await self._session.get(Chat, chat_id)
        if chat is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Chat not found")
        messages = list()
        for message in chat.messages:
            messages.append(MessageOut(**message.__dict__))

        await self._close_session()
        return messages

    async def create_chat(self):
        chat = Chat()
        self._session.add(chat)
        try:
            await self._session.commit()
        except exc.IntegrityError:
            await self._session.rollback()

        return chat.id

    async def create_user_room(self, create_data: CreateUserRoom):
        chat_id = await self.create_chat()
        added_userd = await self.add_user_to_chat([create_data.owner_id], chat_id)

        await self._close_session()
        return added_userd

    async def add_user_to_chat(self, user_id_list: List[str], chat_id: int) -> List[ChatMemberOut]:
        added_users: List[ChatMemberOut] = list()

        if await self._get_chat_by_id(chat_id) is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Chat not found")

        for user_id in user_id_list:
            member = ChatMember(chat_id=chat_id, user_id=user_id)
            self._session.add(member)
            added_users.append(ChatMemberOut(chat_id=chat_id, user_id=user_id))

        try:
            await self._session.commit()
        except exc.IntegrityError:
            await self._session.rollback()
        return added_users

    async def user_in_chat(self, chat_id, user_id):
        chat: Chat = await self._session.get(Chat, chat_id)
        if chat is None:
            return False

        members = [user_id for members in chat.members if user_id == members.user_id]
        if user_id in members:
            return True

    async def save_message(self, message_data: SaveMessage):
        if not await self.user_in_chat(message_data.chat_id, message_data.user_id):
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)

        chat: Chat = await self._session.get(Chat, message_data.chat_id)
        if chat is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)

        message = Message(**message_data.dict())
        chat.messages.append(message)

        try:
            self._session.add(chat)
            await self._session.commit()
        except exc.IntegrityError:
            await self._session.rollback()

        await self._close_session()

class Notifier:
    def __init__(self):
        self.connections: Dict[int, Dict] = dict()

    async def send_in_group(self, chat_id, user_id, message):
        chat_users = self.connections[chat_id]
        for user in chat_users:
            if user != user_id:
                await chat_users[user].send_text(message)

    async def connect(self, chat_id: int, user_id: str, websocket: WebSocket):
        await websocket.accept()

        if self.connections == {} or len(self.connections) == 0:
            self.connections[chat_id] = {}

        if self.connections.get(chat_id, None) is None:
            self.connections[chat_id] = {}

        self.connections[chat_id].update({user_id: websocket})

    def remove(self, chat_id: int, user_id: str):
        try:
            self.connections[chat_id].pop(user_id)

            # delete chat_room
            if len(self.connections[chat_id]) == 0:
                self.connections.pop(chat_id)
        except KeyError:
            pass


from config import TG_KEY, GPT_KEY
from keybrds import kb
from redis_client import redis_client

import openai
from aiogram import Bot, Dispatcher, executor, types

openai.api_key = GPT_KEY

bot = Bot(token=TG_KEY)
dispatcher = Dispatcher(bot)

@dispatcher.message_handler(commands=["start"])
async def start_func(message: types.Message):
    print("Bot has started!")
    await message.reply(
        "Welcome to Chat_bot. This bot uses ChatGPT3!\n\nTo clear cache use command /del.",
        reply_markup=kb,
    )

@dispatcher.message_handler(commands=["del"])
async def clear_cache(message: types.Message):
    user_id = types.User.get_current().id
    redis_client.delete(user_id)
    redis_client.close()
    await message.reply("Cache was cleared!", reply_markup=kb)

@dispatcher.message_handler()
async def get_message(message: types.Message) -> None:
    user_id = types.User.get_current().id
    user_name = types.User.get_current().username

    print(user_id, "==", user_name)

    if redis_client.get(user_id):
        db_message = redis_client.get(user_id).decode()
    else:
        db_message = str(redis_client.set(user_id, ""))
    redis_client.close()

    chat_history = db_message + "\n\nHuman: " + message.text + "\n\nAI:"

    if len(chat_history) > 2000:
        chat_history = chat_history[-2000:]
    print("CHAT LENGTH: ", len(chat_history))

    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": chat_history}],
            temperature=1.5,
        )
        answer = response["choices"][0]["message"]["content"]
        await message.reply(f"{answer}", parse_mode="html")
    except:
        await message.reply(
            "An error occured!\nTry again!\n\nПроизошла ошибка!\nПопробуйте еще раз!",
            parse_mode="html",
        )
        print("\n\n\n======EXCEPTION HANDELED!=======\n\n\n")
        answer = ""

    chat_history = chat_history + answer
    # print('CHAT_HISTORY: ',  chat_history)
    redis_client.set(user_id, chat_history.encode(), ex=1800)
    # print('RDB: ', redis_client.get(user_id).decode())

    redis_client.close()

if __name__ == "__main__":
    executor.start_polling(dispatcher, skip_updates=True)


import matplotlib.pyplot as plt
import seaborn as sns; sns.set()  # for plot styling
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from numpy import genfromtxt

#humm, encontre este codigo en un servidor remoto
#estaba junto con el "traffic.pcap"
# que podria ser?, like some sample code

my_data2 = np.genfromtxt('test_2.txt', delimiter=',')
db = DBSCAN(eps=10000, min_samples=100000).fit(my_data2)
labels = db.labels_
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
unique_labels = set(labels)
colors = [plt.cm.Spectral(each)
          for each in np.linsspace(0, 1, len(unique_labels))]
for k, col in zip(unique_labels, colors):
    class_member_mask = (labels == k)
    xy = X[class_member_mask & core_samples_mask]
    plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
             markeredgecolor='k', markersize=14)

#NOTE: what you see in the sky put it format TMCTF{replace_here}
#where "replace_here" is what you see
plt.title('aaaaaaaa: %d' % n_clusters_)
plt.show()


import random
from Coverage import Coverage

def fuzzer(max_length=100, char_start=32, char_range=32):

    length = random.randint(0, max_length + 1)
    out = ""
    for i in range(length):
        out += chr(random.randint(char_start, char_start+char_range))
    return out

def cgi_decode(s):
    """Decode the CGI-encoded string `s`:
       * replace "+" by " "
       * replace "%xx" by the character with hex number xx.
       Return the decoded string.  Raise `ValueError` for invalid inputs."""

    # Mapping of hex digits to their integer values
    hex_values = {
        '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
        '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
        'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15,
        'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15,
    }

    t = ""
    i = 0
    while i < len(s):
        c = s[i]
        if c == '+':
            t += ' '
        elif c == '%':
            digit_high, digit_low = s[i + 1], s[i + 2]
            i += 2
            if digit_high in hex_values and digit_low in hex_values:
                v = hex_values[digit_high] * 16 + hex_values[digit_low]
                t += chr(v)
            else:
                raise ValueError("Invalid encoding")
        else:
            t += c
        i += 1
    return t

coverage = set()
for i in range(1000):
    candidate = fuzzer(max_length=10)
    with Coverage() as cov:
        try:
            result = cgi_decode(candidate)
        except Exception as exc:
            pass

    new_coverage = frozenset(cov.coverage())
    if new_coverage.difference(coverage):
        print(candidate)

    coverage.update(new_coverage)

print(sorted([line for (method, line) in coverage if method == "cgi_decode"]))

def insert_character(str):
    pos = random.randint(0, len(str))
    return str[:pos] + chr(random.randrange(32, 127)) + str[pos:]

def delete_character(str):
    if str == "":
        return str
    pos = random.randint(0, len(str) - 1)
    return str[:pos] + str[pos + 1:]

def replace_character(str):
    pos = random.randint(0, len(str) - 1)
    return str[:pos] + chr(random.randrange(32, 127)) + str[pos+1:]

def mutate(str):
    ops = [ insert_character, delete_character, replace_character ]
    op = random.choice(ops)
    return op(str)

valid_string = "foo=bar"

def coverage_fuzzer(seed, iterations, min_mutations=1, max_mutations=5):
    coverages_seen = set()
    population = seed
    valid = 0
    assert len(population) > 0

    for iteration in range(iterations):
        candidate = random.choice(population)
        trials = random.randint(min_mutations, max_mutations)
        for i in range(trials):
            candidate = mutate(candidate)

        with Coverage() as cov:
            try:
                result = cgi_decode(candidate)
            except Exception as exc:
                pass

        new_coverage = frozenset(cov.coverage())

        if new_coverage.difference(coverages_seen):
            # We have new coverage
            #print(new_coverage)
            population.append(candidate)
            coverages_seen.update(new_coverage)
            print(iteration, len(population))

    print(population)
    print(sorted([line for (method, line) in coverages_seen if method == "cgi_decode"]))

coverage_fuzzer([valid_string], 1000)


"""
热力图
"""

from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.globals import GeoType, ThemeType
from pyecharts.faker import Faker
import random, os

map = (
    Geo(init_opts=opts.InitOpts(width="1000px", height="800px", renderer="canvas",
                                theme=ThemeType.LIGHT, animation_opts=opts.AnimationOpts(animation=True)))
        .add_schema(maptype="china")
        .add(series_name="中国热力图",
             data_pair=[list(z) for z in
                        zip(Faker.provinces,
                            [random.randint(0, (i + 1) * 200 + 100) for i in range(len(Faker.provinces))])],
             type_=GeoType.EFFECT_SCATTER, symbol_size=20,
             color=Faker.visual_color[random.randint(0, len(Faker.visual_color)-1)])
        .add(series_name="广东热力图",
             data_pair=[list(z) for z in
                        zip(Faker.guangdong_city,
                            [random.randint(0, (i + 1) * 100) for i in range(len(Faker.provinces))])],
             type_=GeoType.EFFECT_SCATTER, symbol_size=10,
             color=Faker.visual_color[1])
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(visualmap_opts=opts.VisualMapOpts(max_=400, pos_top=20),
                         title_opts=opts.TitleOpts(title=""),
                         )
)
map.render(path="E:/tmp/geo_heatmap.html")

os.system('E:/tmp/geo_heatmap.html')


#!/usr/bin/env python3

# Laboratorio 12 - Tetris
# Nome: Marcos Diaz
# RA: 221525

ALTURA_TABULEIRO = 10
LARGURA_TABULEIRO = 10

# Funcao: atualiza_posicao
#
# Parametros:
#      l: largura do bloco que ira cair
#      a: altura do bloco que ira cair
#      x: posicao horizontal inicial do bloco que ira cair
#   desl: deslocamento horizontal a ser aplicado ao bloco (positivo para direita, negativo para a esquerda)
#    rot: 1 se deve rotacionar o bloco, 0 caso contrario
#
# Retorno:
#   Nova largura, altura e posicao horizontal.
#
def atualiza_posicao(l, a, x, desl, rot):
    # Implementar a funcao e trocar o valor de retorno
    #rotacionar
    pos=0
    if rot == 1:
        largura=a
        altura=l
    else:
        largura=l
        altura=a
    #computar x
    if desl>=0:
        if x+largura+desl <=10:
            pos=x+desl
        else:
            pos=10-largura
    elif desl<0:
        if x+desl>=0:
            pos=x+desl
        else:
            pos=0
    #retornar
    return largura, altura, pos

# Funcao: encontra_y
#
# Parametros:
#    mat: matriz representando o tabuleiro
#      l: largura do bloco que ira cair
#      x: posicao horizontal do bloco que ira cair
#
# Retorno:
#   altura final y do canto inferior esquerdo do bloco apos
#   este descer o maximo possivel
#
def encontra_y(mat, l, x):
    # Implementar a funcao e trocar o valor de retorno
    yf=0
    for i in range(10):
        if 1 in mat[i][x:x+l]:
            yf= i+1
    return yf

# Funcoes: posicao_final_valida
#
# Parametros:
#      a: altura do bloco que caiu
#      y: altura final do bloco que caiu
#
# Retorno:
#   1 se o bloco naquela posicao estiver contido dentro do tabuleiro, ou 0 caso contrario.
#
def posicao_final_valida(a, y):
    # Implementar a funcao e trocar o valor de retorno
    if y+a<=10:
        return 1
    else:
        return 0

# Funcoes: posiciona_bloco
#
# Parametros:
#    mat: matriz do tabuleiro
#      l: largura do novo bloco
#      a: altura do novo bloco
#      x: posicao horizontal do novo bloco
#      y: altura final do novo bloco
#
#      Deve preencher com 1s as novas posicoes ocupadas pelo bloco que caiu
# Retorno:
#   NULL
#
def posiciona_bloco(mat, l, a, x, y):
    # Implementar a funcao
    for i in range(y, y+a):
        for j in range(x, x+l):
             mat[i][j]=1

# Funcoes: atualiza_matriz
#
#    mat: matriz do tabuleiro
#
#         Deve remover as linhas totalmente preenchidas do tabuleiro copiando
#         linhas posicionadas acima.
# Retorno:
#   retorna o numero de linhas totalmente preenchidas que foram removidas apos
#   a atualizacao do tabuleiro.
#
def atualiza_matriz(mat):
    # Implementar a funcao e trocar o valor de retorno
    p=0
    preenchida=[1 for i in range(10)]
    ref=[i[:] for i in mat]
    """
    if preenchida in ref:
        print("rodou if!")
        print(mat[0] is preenchida)
        while preenchida in ref:
            mat.remove(preenchida)
            mat.append([0 for z in range(10)])
            p=p+1
    """
    for i in range(10):
        if ref[9-i]==preenchida:
            #o indexerror esta aqui!
            newlast=[0 for z in range(10)]
            mat.pop(9-i)
            mat.append(newlast)
            p=p+1
    return p


"""
Store things and forget them.
"""

import time

class Session:
    """
    Session acts a dict, with a max size, and it forgets old items.

    Eviction is lazy, or explicit, with garbage collection.

    The code is compatible with asyncio.
    """

    def __init__(self, max_size: int = 0, max_age: int = 0) -> None:
        assert max_size >= 0, "Positive max_size, please"
        assert max_age >= 0, "Positive max_age, please"
        self.max_size = max_size
        self.max_age = max_age
        self.data = dict()

    def __contains__(self, key):
        return key in self.data

    def __getitem__(self, key):
        if key not in self.data:
            raise IndexError()
        ts = time.monotonic()
        last, value = self.data[key]
        if self.max_age > 0 and (ts - last) > self.max_age:
            "too old"
            del self.data[key]
            raise IndexError()
        self.data[key] = (ts, value)  # let refresh the timer
        return value

    def __delitem__(self, key):
        del self.data[key]

    def __setitem__(self, key, value):
        if (
            self.max_size > 0
            and key not in self.data
            and len(self.data) > self.max_size
        ):
            raise Exception("Your session is full")
        self.data[key] = (time.monotonic(), value)

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

    def garbage_collector(self) -> int:
        "Looking for rotten items and removing them. Returns number of evictions"
        assert self.max_age != 0, "Garbage collection with max_age=0 is a strange idea"
        ts = time.monotonic()
        garbage = list()
        for k, v in self.data.items():
            if (ts - v[0]) > self.max_age:
                garbage.append(k)
        for k in garbage:
            del self.data[k]
        return len(garbage)

    def keys(self):
        if self.max_age == 0:
            return self.data.keys()
        keys = list()
        old = list()
        ts = time.monotonic()
        for k in self.data.keys():
            if (ts - self.data[k][0]) > self.max_age:
                old.append(k)
            else:
                keys.append(k)
        for k in old:
            del self.data[k]
        return keys


import requests
from bs4 import BeautifulSoup
def strip_string(string1):
    for i in string1:
        if i=='<':
            var1 = string1[string1.index(i):string1.index(">")+1]
            string1 = string1.replace(var1, "")
    return string1
def scrape_meaning(a):
    URL = f"https://www.dictionary.com/browse/{a}"
    r = requests.get(URL)
    soup = BeautifulSoup(r.content, 'html5lib')
    meaning = str(soup.find('span', attrs={'class': 'one-click-content css-nnyc96 e1q3nk1v1'}))
    if meaning.endswith(" ") or meaning.endswith(""):
        meaning = meaning[:-7]
    meaning1 = str(strip_string(meaning))
    if ":" in meaning1:
        meaning1 = meaning1[:meaning1.index(":")]

    if len(meaning1) > 90:
        meaning1 = meaning1[:90] + "\n" + "-" + meaning1[90:]

    return meaning1
def scrape_usage(a):
    URL = f"https://www.dictionary.com/browse/{a}"
    r = requests.get(URL)

    soup = BeautifulSoup(r.content, 'html5lib')
    usage = str(soup.find('span', attrs={'class': 'luna-example italic'}))
    usage1 = str(strip_string(usage))
    if len(usage1) > 90:
        usage1 = usage1[:90] + "\n" + "-" + usage1[90:]
    return usage1


from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import LoginView
from django.shortcuts import get_object_or_404
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.views import View
from .models import *
from django.contrib.auth.models import User
from .serializers import *
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend

@api_view(['GET', 'POST'])
def genre_list(request):
    if request.method == 'GET':
        genres = Genre.objects.all()
        serializer = GenreSerializer(genres, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = GenreSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def genre_detail(request, pk):
    try:
        genre = Genre.objects.get(pk=pk)
    except Genre.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = GenreSerializer(genre)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = GenreSerializer(genre, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        genre.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET', 'POST'])
def movie_list(request):
    if request.method == 'GET':

        movie = Movie.objects.all()
        serializer = MovieSerializer(movie, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = MovieSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def movie_detail(request, pk):
    try:
        movie = Movie.objects.get(pk=pk)
    except Movie.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = MovieSerializer(movie)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = MovieSerializer(movie, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        movie.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET', 'POST'])
def raitingStar_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        star = RaitingStar.objects.all()
        serializer = RaitingStarSerializer(star, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = RaitingStarSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def raitingStar_detail(request, pk):
    try:
        star = RaitingStar.objects.get(pk=pk)
    except RaitingStar.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = RaitingStarSerializer(star)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = RaitingStarSerializer(star, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        star.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET', 'POST'])
def reviews_list(request):
    if request.method == 'GET':
        reviews = Reviews.objects.all()
        serializer = ReviewsSerializer(reviews, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ReviewsSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
def aut(request):
    try:
        user = User.objects.get(username=request.data['username'])
        if (user.password == request.data['password']):
            return Response(status=status.HTTP_200_OK)
        else:
            return Response(request.data['password'], status=status.HTTP_404_NOT_FOUND)
    except User.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

@api_view(['GET', 'PUT', 'DELETE'])
def reviews_detail(request, pk):
    try:
        reviews = Reviews.objects.get(pk=pk)
    except Reviews.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ReviewsSerializer(reviews)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ReviewsSerializer(reviews, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        reviews.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET', 'POST'])
def raiting_list(request):
    if request.method == 'GET':
        raiting = Raiting.objects.all()
        serializer = RaitingSerializer(raiting, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = RaitingSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def raiting_detail(request, pk):
    try:
        raiting = Raiting.objects.get(pk=pk)
    except Raiting.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = RaitingSerializer(raiting)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = RaitingSerializer(raiting, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        raiting.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


from math import gcd
n1=int(input('\n\t Enter first number = '))
n2=int(input('\n\t Enter second number = '))
print('\n\t Primitive Pythagorean Triples between ',n1,'and ',n2,'are as below :-')
if n1>n2:
    n1,n2=n2,n1
if n1<3:
    n1=3
if n1==n2 or n2<5:
    print('\n\tWrong Input')
else:
    b,i=1,0
    a=b-1
    f=True
    while 1:
        a+=2
        if gcd(a,b)!=1:
            continue
        p,q=2*a*b,a**2-b**2
        if p>q:
            p,q=q,p
        if p<n1:
            f=True
            continue
        r=a**2+b**2
        if r<=n2 and p>=n1:
            i+=1
            f=True
            print('\n\t Triplet No ',i,'\t Pair of Pythagorean Triples - ',(p,q,r))
        elif f:
            b+=1
            a=b-1
            f=False
        else:
            break


# Let's learn about list comprehensions! You are given three integers x,y  and z representing the dimensions of a cuboid along' \
#    ' with an integer n. Print a list of all possible coordinates given by [i,j,k]  on a 3D grid where the sum of it  is not equal to n.' \
#    ' Here, . Please use list comprehensions rather than multiple loops, as a learning exercise.
if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())

cuboid = [[x_, y_, z_] for x_ in range(x+1) for y_ in range(y+1) for z_ in range(z+1) if(x_+y_+z_ != n)]
print(cuboid)


import pandas as pd
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
from numpy.random import rand
from random import sample, shuffle
plt.close()
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from itertools import permutations
import matplotlib.pyplot as plt

# The training data is two points x^{n-1}, x^n, separated by dt.
# We will integrate the equations with dt, and choose Nt random points
# per solution, and choose three points (the third point is the label for
# the Euler algorithm.

# solution to the differential equation
t1 = 0.
t2 = 2.*np.arccos(-1)

# Equivalent to
def circle (t, s):
    x = -s[1]
    y =  s[0]
    return x, y

# Equivalent to def circle above
#circle = lambda t, s: np.array([-s[1], s[0]])

F = circle

# Time interval
t0, tmax = 0, 6.28

# Generate 20 initial condition curves: x0, y0 where x0 \in [0, 5], y0 \in [0, 5]
# This will generate 20 circles with different radii
# Also generate 20 array t_eval, with sorted random numbers between t0 and tmax.
# Each list will contain Nt values.

Nruns = 150   # number of runs
x0max = 1
y0max = 1
dt = .02

# Alternative approach:
# Generate a collection of points (x[n-1], x[n], x[n+1] (for initial conditions)
x0 = x0max * rand(Nruns)
y0 = y0max * rand(Nruns)

# Only work with a single run and validate on the same run (easier problem)
#x0 = x0max * np.ones([Nruns])
#y0 = y0max * np.ones([Nruns])
t0 = t1 + (t2-t1) * rand(Nruns)  # starting times, random between [0, 6.28]
#x0 = np.asarray([x0max])

sols = {}
y_list = []
for i in range(Nruns):
    # solution always evaluated at the same points
    t_eval = np.linspace(t0[i], t0[i]+2*dt, 3)
    # x[0][i] and y0[i] are always 1
    # What is the second argument of solve_ivp?  Min/max t for simulation
    # t_eval are three time points: t0[i], t0[i]+dt, t0[i]+2*dt
    # Initial Conditions (I.C.): x0[i], y[0][i] for run i
    sol = sols[i] = solve_ivp(F, [t0[i], t0[i]+2*dt], [x0[i], y0[i]], t_eval=t_eval)
    print(f"({i}) t_eval: ", t_eval)
    print(f"({i}) t[i]: ", t0[i])
    print(f"({i}) x0[i]: ", x0[i])
    print(f"({i}) y0[i]: ", y0[i])
    print()
    #print(sol.t)
    plt.plot(sol.t, sol.y[0], color='r', lw=1)
    plt.plot(sol.t, sol.y[1], color='b', lw=1)
    #plt.scatter(sol.t, sol.y[0], color='r')
    #plt.scatter(sol.t, sol.y[1], color='b')
    plt.xlabel('t')
    #plt.ylabel('sample points')
plt.show()
plt.close()
#quit()

# select 100 triplets (t[2*i], x[2*i], x[2*i+1]) where x[2i] is the solution at t^n
# and x[2i+1] is the solution at t^{n+1}

# Even numbers (the odd numbers are 'dt' away )
even = list(range(0, len(t_eval), 2))
Nsamples_per_run = 10
x0_seq3 = []
x1_seq3 = []
t_seq3 = []
for i in range(Nruns):
    sol = sols[i]
    t_seq3.append( list(sol.t) )
    x0_seq3.append( list(sol.y[0]) )
    x1_seq3.append( list(sol.y[1]) )

#-----------------------------------------------------------------------------------
# I now have the training data on which to base the neural network:
#   times:  (t_i^n, t_i^{n+1}), i=0, 1, Nruns*Nsamples_per_run
#   x0_pairs: (x[0]_i^n, x[0]_i^{n+1}), i=0, 1, Nruns*Nsamples_per_run
#   x1_pairs: (x[1]_i^n, x[1]_i^{n+1}), i=0, 1, Nruns*Nsamples_per_run

class NN(nn.Module):
    """Simple neural network accepting two features as input and returning a single output

    In the context of PINNs, the neural network is used as universal function approximator
    to approximate the solution of the differential equation
    """
    def __init__(self, num_hidden: int, dim_hidden: int, act=nn.Tanh()):
        super(NN, self).__init__()

        # input t into the network
        # There are two inputs and two outputs
        # The inputs are x^{n-1}, x^{n} where x \in R^2
        self.layer_in = nn.Linear(4, dim_hidden)
        self.layer_out = nn.Linear(dim_hidden, 2)

        num_middle = num_hidden
        self.middle_layers = nn.ModuleList(
            [nn.Linear(dim_hidden, dim_hidden) for _ in range(num_middle)]
        )
        self.act = act

    def forward(self, t):
        out = self.act(self.layer_in(t))
        for layer in self.middle_layers:
            out = self.act(layer(out))
        out = self.layer_out(out)
        return out

# Create DataSet and DataLoader
# https://pytorch.org/tutorials/beginner/data_loading_tutorial.html

class myDataset(Dataset):
    def __init__(self, t_seq, x0_seq, x1_seq):
        super(myDataset, self).__init__()
        self.t_seq = torch.tensor(t_seq, dtype=torch.float32)
        self.x0_seq = torch.tensor(x0_seq, dtype=torch.float32)
        self.x1_seq = torch.tensor(x1_seq, dtype=torch.float32)

    def __len__(self):
        return len(self.t_seq // 3)

    def __getitem__(self, i):
        # return 3 sequences of size 3
        return torch.tensor([*self.t_seq[i], *self.x0_seq[i], *self.x1_seq[i]])

dataset = myDataset(t_seq3, x0_seq3, x1_seq3)
dataloader = DataLoader(dataset, batch_size=4, shuffle=True, drop_last=True)

# Armed with the dataset and dataloader, I can implement the neural network
# For each batch, pass it through the NN, and output an approximation of d((x,y))/dt
# Apply Euler to obtain the solution at the next time step. Define MSE loss, and do back propagation
# The samples need not be in temporal order

learning_rate = 1.e-2
loss_fn = torch.nn.MSELoss(reduction='mean')
model = NN(num_hidden=2, dim_hidden=30, act=nn.ReLU())
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)

# Loss function is hardly decreasing. WHY?
nb_epochs = 400
losses = []
epoch_losses = []
for epoch in range(nb_epochs):
    # shuffle each epoch?
    epoch_loss = 0
    count = 0
    for sample in dataloader:
        optimizer.zero_grad()  # correct place?
        # Will the order be important? No if fully connected network
        s = sample[:, [3,4,6,7]]  # x[0]^n, x[1]^n
        dsdt_approx = model(s)
        try:
            snew = s[:,[1,3]] + dt * dsdt_approx  # One step Euler
        except:
            #print("break: size s: ", s.shape)
            # incorrect batch size (not sure actually)
            quit()
            break
        s_exact = sample[:, [5,8]]
        s_approx = snew
        loss = loss_fn(snew, s_exact)
        epoch_loss += loss.item()
        loss.backward()
        losses.append(loss)
        optimizer.step()
        count += 1
    epoch_losses.append(epoch_loss / count)
print("epoch_losses: ", len(epoch_losses), epoch_losses)

# With a trained NN, choose some initial condition and draw a trajectory (x, y)

# The network is not training when I input sequences into the NN!

dt1 = dt #* 0.5

sv0 = torch.tensor([1., 0.])  # at t = 0
# The exact solution is x = cos(t), y = sin(t)
sv1 = torch.tensor([np.cos(dt), np.sin(dt1)])
# sol.y[0] is y[0], sol.y[1] is y[1]
# sv: first the point at t^n, followed by the point at t^{n+1}
sv = torch.tensor([*sv0, *sv1], dtype=torch.float32)   # y[0] and y[1] are interleaved (y[0][0], y[1][0], y[0][1], y[1][1])
x_lst = []
y_lst = []
t_lst = []

print("sv: ", sv)
# The model requires three points. This means I must find a way to compute the first two points. I will consider the exact solution.
# In reality, I could apply two steps of a Runga-Kutta algorithms, or several steps of Euler with smaller time step.

# Save initial condition (x,y,t) (same as y[0], y[1], t)
x_lst.append(sv0[0].item())
y_lst.append(sv0[1].item())
t_lst.append(0)
print("x_lst= ", x_lst)

sv_nm1 = sv0.clone()
sv_n   = sv1.clone()
sv = torch.tensor([*sv_nm1, *sv_n], dtype=torch.float32)   # y[0] and y[1] are interleaved (y[0][0], y[1][0], y[0][1], y[1][1])

# The method is unstable
for i in range(600):
    # My sv update is incorrect
    dydt = model(sv)  # model takes in first two points. How is that done?
    #sv_new = sv[2:] + dt1 * dydt
    sv_np1 = sv_n + dt1 * dydt
    sv_nm1 = sv_n.clone()  # Inefficient, but clear, implementation
    sv_n   = sv_np1.clone()
    sv = torch.tensor([*sv_nm1, *sv_n], dtype=torch.float32)
    x_lst.append(sv_np1[0].item())
    y_lst.append(sv_np1[1].item())
    t_lst.append((i+1)*dt1)

x_lst = np.asarray(x_lst)
y_lst = np.asarray(y_lst)
t_lst = np.asarray(t_lst)

plt.figure(figsize=(10, 6))
plt.plot(t_lst, x_lst, label='$x_0$')
plt.plot(t_lst, y_lst, label='$x_1$')
plt.xlabel('t')
plt.ylabel('$x_0$, $x_1$')
radius = np.sqrt(x_lst**2 + y_lst**2)
plt.plot(t_lst, radius, label='radius')
plt.legend()
plt.grid()
plt.show()
plt.close()


import jc
from connectors.core.connector import get_logger, ConnectorError
from .constants import LOGGER_NAME

logger = get_logger(LOGGER_NAME)

def convert(config, params):
    parser = params.get('parser')
    cmd_output = params.get('command_output')
    raw = params.get('raw', False)

    if not parser or not cmd_output:
        logger.exception('Missing required input')
        raise ConnectorError('Missing required input')

    parser = parser.replace('-', '_')

    if parser in jc.streaming_parser_mod_list():
        logger.exception(f"'{parser}' parser not valid. Streaming parsers are not supported.")
        raise ConnectorError(f"'{parser}' parser not valid. Streaming parsers are not supported.")

    if parser not in jc.standard_parser_mod_list():
        logger.exception(f"'{parser}' parser not valid.")
        raise ConnectorError(f"'{parser}' parser not valid.")

    parser_info = jc.parser_info(parser)
    logger.info(f"Selected parser: {parser_info}")

    return jc.parse(parser, cmd_output, raw=raw, quiet=True)


from __future__ import annotations

from typing import Literal, Optional

from cognite.client import data_modeling as dm
from pydantic import Field

from ._core import DomainModel, DomainModelApply, TypeList, TypeApplyList

__all__ = ["CogPool", "CogPoolApply", "CogPoolList", "CogPoolApplyList", "CogPoolFields", "CogPoolTextFields"]

CogPoolTextFields = Literal["name", "time_unit", "timezone"]
CogPoolFields = Literal["max_price", "min_price", "name", "time_unit", "timezone"]

_COGPOOL_PROPERTIES_BY_FIELD = {
    "max_price": "maxPrice",
    "min_price": "minPrice",
    "name": "name",
    "time_unit": "timeUnit",
    "timezone": "timezone",
}

class CogPool(DomainModel):
    space: str = "market"
    max_price: Optional[float] = Field(None, alias="maxPrice")
    min_price: Optional[float] = Field(None, alias="minPrice")
    name: Optional[str] = None
    time_unit: Optional[str] = Field(None, alias="timeUnit")
    timezone: Optional[str] = None

    def as_apply(self) -> CogPoolApply:
        return CogPoolApply(
            external_id=self.external_id,
            max_price=self.max_price,
            min_price=self.min_price,
            name=self.name,
            time_unit=self.time_unit,
            timezone=self.timezone,
        )

class CogPoolApply(DomainModelApply):
    space: str = "market"
    max_price: Optional[float] = None
    min_price: Optional[float] = None
    name: Optional[str] = None
    time_unit: Optional[str] = None
    timezone: Optional[str] = None

    def _to_instances_apply(self, cache: set[str]) -> dm.InstancesApply:
        if self.external_id in cache:
            return dm.InstancesApply(dm.NodeApplyList([]), dm.EdgeApplyList([]))

        sources = []
        properties = {}
        if self.max_price is not None:
            properties["maxPrice"] = self.max_price
        if self.min_price is not None:
            properties["minPrice"] = self.min_price
        if self.time_unit is not None:
            properties["timeUnit"] = self.time_unit
        if properties:
            source = dm.NodeOrEdgeData(
                source=dm.ContainerId("market", "CogPool"),
                properties=properties,
            )
            sources.append(source)
        properties = {}
        if self.name is not None:
            properties["name"] = self.name
        if self.timezone is not None:
            properties["timezone"] = self.timezone
        if properties:
            source = dm.NodeOrEdgeData(
                source=dm.ContainerId("market", "Market"),
                properties=properties,
            )
            sources.append(source)
        if sources:
            this_node = dm.NodeApply(
                space=self.space,
                external_id=self.external_id,
                existing_version=self.existing_version,
                sources=sources,
            )
            nodes = [this_node]
        else:
            nodes = []

        edges = []
        cache.add(self.external_id)

        return dm.InstancesApply(dm.NodeApplyList(nodes), dm.EdgeApplyList(edges))

class CogPoolList(TypeList[CogPool]):
    _NODE = CogPool

    def as_apply(self) -> CogPoolApplyList:
        return CogPoolApplyList([node.as_apply() for node in self.data])

class CogPoolApplyList(TypeApplyList[CogPoolApply]):
    _NODE = CogPoolApply


import time
from datetime import datetime
from models.cancel_queue import CancelQueue
from models.last_updated_tracker import LastUpdatedTracker
from sqlalchemy import insert, update, select
from .get_orders import get_orders
from .get_orders_items import get_orders_items
from ... import my_logger, SP_EXCEPTIONS, pacific_zone
from ...helpers.db_config import db_conn

conn = db_conn()

"""
Hitting Sp Api Orders & Orders Item Api to fetch user's orders information
And Updating the Amazon Orders Cancel Queue Based on order's is_buyer_requested_cancellation status
"""

def process_cancel_orders(posted_after, posted_before):
    try:
        my_logger.info(
            f"posted_after {posted_after} | posted_before {posted_before} | Datetime Now in PacificTime {(datetime.now(pacific_zone)).isoformat()}"
        )
        time.sleep(3)
        orders = get_orders(
            posted_after,
            posted_before,
            marketplace_ids=["ATVPDKIKX0DER"],
            order_statuses=["PartiallyShipped", "Unshipped"],
            fulfillment_channels=["MFN"]
        )
        if len(orders) > 0:
            my_logger.info(f"orders length {len(orders)}")
            last_purchase_date = posted_before
            for order in orders:
                time.sleep(3)
                order_items = get_orders_items(
                    order_id=order.get("AmazonOrderId"))
                if order_items:
                    my_logger.info(f"order_id {order.get('AmazonOrderId')} \n order_items {len(order_items)}")
                    for order_item in order_items:
                        is_buyer_requested_cancellation = order_item.get("BuyerRequestedCancel").get(
                            "IsBuyerRequestedCancel"
                        ) if order_item.get("BuyerRequestedCancel") else "false"
                        buyer_cancellation_reason = order_item.get("BuyerRequestedCancel").get(
                            "BuyerCancelReason"
                        ) if order_item.get("BuyerRequestedCancel") else None
                        # Updating the Cancel Queue
                        if is_buyer_requested_cancellation != "false":
                            cqs = conn.query(CancelQueue).where(
                                CancelQueue.order_number == order.get('AmazonOrderId'),
                                CancelQueue.order_item_id == order_item.get('OrderItemId'),
                                CancelQueue.sku == order_item.get('SellerSKU')
                            ).first()
                            if not cqs:
                                my_logger.info(f"Sku {order_item.get('SellerSKU','')} is cancelled and saving in db.")
                                cq = CancelQueue(order.get('AmazonOrderId',''))
                                cq.order_item_id = order_item.get('OrderItemId','')
                                cq.sku = order_item.get('SellerSKU','')
                                cq.buyer_cancel_date = datetime.now(pacific_zone)
                                cq.purchase_date = datetime.strptime(order.get('PurchaseDate'), "%Y-%m-%dT%H:%M:%SZ")
                                cq.last_processed_at = datetime.now(pacific_zone)
                                cq.desktopshipper_cancel = 0
                                cq.skubana_cancel = 0
                                cq.amazon_cancel = 0
                                cq.buyer_cancellation_reason = buyer_cancellation_reason
                                cq.processing_status = 'PENDING'
                                cq.created_at = datetime.now(pacific_zone)
                                cq.updated_at = datetime.now(pacific_zone)
                                conn.merge(cq)
                                conn.commit()
                            else:
                                my_logger.debug(
                                    f"Sku {order_item.get('SellerSKU','')} is already in the queue, skipping."
                                )
                last_purchase_date = order.get('PurchaseDate')

            # Updating Order Tracker
            stmt = (
                select(LastUpdatedTracker)
                .where(LastUpdatedTracker.tracker_type == 'orders')
            )
            last_tracker = conn.execute(stmt).first()
            if not last_tracker:
                stmt = (
                    insert(LastUpdatedTracker)
                    .values(
                        tracker_type="orders",
                        last_updated_at=datetime.strptime(last_purchase_date, "%Y-%m-%dT%H:%M:%SZ"),
                        created_at=datetime.now(pacific_zone),
                        updated_at=datetime.now(pacific_zone)
                    )
                )
                conn.execute(stmt)
                conn.commit()
            else:
                stmt = (
                    update(LastUpdatedTracker)
                    .where(LastUpdatedTracker.tracker_type == "orders")
                    .values(
                        last_updated_at=datetime.strptime(last_purchase_date, "%Y-%m-%dT%H:%M:%SZ"),
                        updated_at=datetime.now(pacific_zone)
                    )
                )
                conn.execute(stmt)
                conn.commit()
            return True
        else:
            my_logger.error(f"No Orders")
            return False
    except SP_EXCEPTIONS as e:
        my_logger.error(str(e))
        orders = None
        raise e


import art
import subprocess
clear = lambda: subprocess.call('cls||clear', shell=True)

print(art.logo)
list = []
def add_list(name,bid):

  new_dic = {
    "name": name,
    "bid": bid
  }
  list.append(new_dic)

def declare_winner(list):
  max_bid = 0
  for dic in list:
    if max_bid < int(dic["bid"]):
      max_bid = int(dic["bid"])
      winner = dic["name"]
  print(f"Winner of the auction is (The one who pays the most:D) {winner} with the price ${max_bid}")

while True:
  name = input("What is your name?: ")
  bid = input("What is your bid?: $")
  add_list(name, bid)
  while True:
    flag = input("Is there any one who want to bid too?(yes or no)").lower()
    if flag != "yes" and flag != "no":
      print("Invalid input! Let's try again")
      continue
    else:
      break
  if flag == "yes":
    clear()
    continue
  else:
    clear()
    break

declare_winner(list)


#!/usr/bin/python3
from brownie import web3, Attack
from scripts.deploy import deploy
from scripts.helpful_scripts import get_account
from colorama import Fore
from time import time

# * colours
green = Fore.GREEN
red = Fore.RED
blue = Fore.BLUE
magenta = Fore.MAGENTA
reset = Fore.RESET

def print_colour(solved):
    if solved:
        print(f"{blue}Is complete: {green}{True}{reset}")
    else:
        print(f"{blue}Is complete: {red}{solved}{reset}")

def hack(contract_address=None, attacker=None):
    if not contract_address:
        target, _ = deploy()
        _, attacker = get_account()
    else:
        print(f"{red}Something is wrong{reset}")
        exit(-1)

    print_colour(target.isComplete())

    # # Get the value of ans
    # block_number = web3.eth.blockNumber
    # block_hash = web3.eth.getBlock(block_number - 1)["hash"].hex()
    # timestamp = web3.eth.getBlock("latest")["timestamp"]

    # # print(block_hash + timestamp)

    # # Compute the answer using the same algorithm as the contract
    # ans_hash = web3.solidityKeccak(["bytes32", "uint32"], [block_hash, timestamp]).hex()
    # print(ans_hash)

    # answer = int("0x" + ans_hash[-2:], 0)
    # print(answer)
    # print(target.answer())

    attcking_contract = Attack.deploy(target.address, {"from": attacker})

    attcking_contract.hack({"from": attacker, "value": "1 ether"})

    # target.guess(answer, {"from": attacker, "value": "1 ether"}).wait(1)

    print_colour(target.isComplete())

    assert target.isComplete() == True

def main(contract_address=None):
    if contract_address:
        hack(contract_address, get_account())
    else:
        hack()

if __name__ == "__main__":
    main()


import streamlit as st
import altair as alt
import inspect
from vega_datasets import data

@st.experimental_memo
def get_chart_99637(use_container_width: bool):
    import altair as alt
    from vega_datasets import data

    airports = data.airports()
    states = alt.topo_feature(data.us_10m.url, feature='states')

    # US states background
    background = alt.Chart(states).mark_geoshape(
        fill='lightgray',
        stroke='white'
    ).properties(
        width=500,
        height=300
    ).project('albersUsa')

    # airport positions on background
    points = alt.Chart(airports).mark_circle(
        size=10,
        color='steelblue'
    ).encode(
        longitude='longitude:Q',
        latitude='latitude:Q',
        tooltip=['name', 'city', 'state']
    )

    chart = background + points

    tab1, tab2 = st.tabs(["Streamlit theme (default)", "Altair native theme"])

    with tab1:
        st.altair_chart(chart, theme="streamlit", use_container_width=True)
    with tab2:
        st.altair_chart(chart, theme=None, use_container_width=True)

try:
    st.expander("See code").code(inspect.getsource(get_chart_99637))
    get_chart_99637(use_container_width=True)
except Exception as e:
    st.exception(e)


Students = {}

with open("input.txt") as file:
    for line in file:
        info = line.strip().split(";")
        Students[info[0]] = info[1:]

inputNumber = None
print("To exit input 0")
while inputNumber != "0":
    inputNumber = input("Student Number to Search:")
    if inputNumber != "0":
        if inputNumber in Students.keys():
            print(Students[inputNumber])
        else:
            print("Student not found!")


from typing import Optional
from decimal import Decimal

from validator_collection import validators

from highcharts_core import errors
from highcharts_core.metaclasses import HighchartsMeta
from highcharts_core.decorators import class_sensitive
from highcharts_core.options.sonification.track_configurations import (InstrumentTrackConfiguration,
                                                                       SpeechTrackConfiguration,
                                                                       ContextTrackConfiguration)
from highcharts_core.options.sonification.grouping import SonificationGrouping
from highcharts_core.utility_classes.events import SonificationEvents

class SonificationOptions(HighchartsMeta):
    """Options for configuring sonification and audio charts."""

    def __init__(self, **kwargs):
        self._after_series_wait = None
        self._default_instrument_options = None
        self._default_speech_options = None
        self._duration = None
        self._enabled = None
        self._events = None
        self._global_context_tracks = None
        self._global_tracks = None
        self._master_volume = None
        self._order = None
        self._point_grouping = None
        self._show_crosshair = None
        self._show_tooltip = None
        self._update_interval = None

        self.after_series_wait = kwargs.get('after_series_wait', None)
        self.default_instrument_options = kwargs.get('default_instrument_options', None)
        self.default_speech_options = kwargs.get('default_speech_options', None)
        self.duration = kwargs.get('duration', None)
        self.enabled = kwargs.get('enabled', None)
        self.events = kwargs.get('events', None)
        self.global_context_tracks = kwargs.get('global_context_tracks', None)
        self.global_tracks = kwargs.get('global_tracks', None)
        self.master_volume = kwargs.get('master_volume', None)
        self.order = kwargs.get('order', None)
        self.point_grouping = kwargs.get('point_grouping', None)
        self.show_crosshair = kwargs.get('show_crosshair', None)
        self.show_tooltip = kwargs.get('show_tooltip', None)
        self.update_interval = kwargs.get('update_interval', None)

    @property
    def after_series_wait(self) -> Optional[int | float | Decimal]:
        """The time to wait in milliseconds after each data series when playing the visualization's data series
        in sequence. Defaults to ``700``.

        :rtype: numeric or :obj:`None <python:None>`
        """
        return self._after_series_wait

    @after_series_wait.setter
    def after_series_wait(self, value):
        self._after_series_wait = validators.numeric(value,
                                                     allow_empty = True,
                                                     minimum = 0)

    @property
    def default_instrument_options(self) -> Optional[InstrumentTrackConfiguration]:
        """Default sonification options for all instrument tracks.

        .. warning::

          If specific options are also set on individual tracks or per-series, this configuration will be *overridden*.

        :rtype: :class:`InstrumentTrackConfiguration <highcharts_core.options.sonification.track_configurations.InstrumentTrackConfiguration>`
          or :obj:`None <python:None>`
        """
        return self._default_instrument_options

    @default_instrument_options.setter
    @class_sensitive(InstrumentTrackConfiguration)
    def default_instrument_options(self, value):
        self._default_instrument_options = value

    @property
    def default_speech_options(self) -> Optional[SpeechTrackConfiguration]:
        """Default sonification options for all speech tracks.
        .. warning::

          If specific options are also set on individual tracks or per-series, this configuration will be *overridden*.

        :rtype: :class:`SpeechTrackConfiguration <highcharts_core.options.sonification.track_configurations.SpeechTrackConfiguration>`
          or :obj:`None <python:None>`
        """
        return self._default_speech_options

    @default_speech_options.setter
    @class_sensitive(SpeechTrackConfiguration)
    def default_speech_options(self, value):
        self._default_speech_options = value

    @property
    def duration(self) -> Optional[int | float | Decimal]:
        """The total duration of the sonification, expressed in milliseconds. Defaults to ``6000``.

        :rtype: numeric or :obj:`None <python:None>`
        """
        return self._duration

    @duration.setter
    def duration(self, value):
        self._duration = validators.numeric(value, allow_empty = True, minimum = 0)

    @property
    def enabled(self) -> Optional[bool]:
        """If ``True``, enables sonification functionality on the chart. Defaults to ``True``.

        :rtype: :class:`bool <python:bool>` or :obj:`None <python:None>`
        """
        return self._enabled

    @enabled.setter
    def enabled(self, value):
        if value is None:
            self._enabled = None
        else:
            self._enabled = bool(value)

    @property
    def events(self) -> Optional[SonificationEvents]:
        """Event handlers for sonification.

        :rtype: :class:`SonificationEvents <highcharts_core.utility_classes.events.SonificationEvents>` or
          :obj:`None <python:None>`
        """
        return self._events

    @events.setter
    @class_sensitive(SonificationEvents)
    def events(self, value):
        self._events = value

    @property
    def global_context_tracks(self) -> Optional[ContextTrackConfiguration]:
        """Context tracks to add globally, an array of either instrument tracks, speech tracks, or a mix.

        .. note::

          Context tracks are not tied to data points, but play at a set interval - either based on ``time`` or on
          ``prop`` values.

        :rtype: :class:`ContextTrackConfiguration <highcharts_core.options.sonification.track_configurations.ContextTrackConfiguration>`
          or :obj:`None <python:None>`
        """
        return self._global_context_tracks

    @global_context_tracks.setter
    @class_sensitive(ContextTrackConfiguration)
    def global_context_tracks(self, value):
        self._global_context_tracks = value

    @property
    def global_tracks(self) -> Optional[InstrumentTrackConfiguration]:
        """Global tracks to add to every series.

        :rtype: :class:`InstrumentTrackConfiguration <highcharts_core.options.sonification.track_configurations.InstrumentTrackConfiguration>`
          or :obj:`None <python:None>`
        """
        return self._global_tracks

    @global_tracks.setter
    @class_sensitive(InstrumentTrackConfiguration)
    def global_tracks(self, value):
        self._global_tracks = value

    @property
    def master_volume(self) -> Optional[int | float | Decimal]:
        """The overall/master volume for the sonification, from ``0`` to ``1``. Defaults to ``0.7``.

        :rtype: numeric or :obj:`None <python:None>`
        """
        return self._master_volume

    @master_volume.setter
    def master_volume(self, value):
        self._master_volume = validators.numeric(value,
                                                 allow_empty = True,
                                                 minimum = 0,
                                                 maximum = 1)

    @property
    def order(self) -> Optional[str]:
        """The order in which to play the sonification for data series. Accepts either:

          * ``'sequential'`` where the series play individually one after the other or
          * ``'simultaneous'`` where the series play at the same time

        Defaults to ``'sequential'``.

        :rtype: :class:`str <python:str>` or :obj:`None <python:None>`
        """
        return self._order

    @order.setter
    def order(self, value):
        if not value:
            self._order = None
        else:
            value = validators.string(value)
            value = value.lower()
            if value not in ['sequential', 'simultaneous']:
                raise errors.HighchartsValueError(f'.order expects either "sequential" or "simultaenous". '
                                                  f'Received: "{value}"')

            self._order = value

    @property
    def point_grouping(self) -> Optional[SonificationGrouping]:
        """Options for grouping data points together when sonifying.

        This allows for the visual presentation to contain more points than what is being played.

        If not enabled, all visible / uncropped points are played.

        :rtype: :class:`SonificationGrouping <highcharts_core.options.sonification.grouping.SonificationGrouping>` or
          :obj:`None <python:None>`
        """
        return self._point_grouping

    @point_grouping.setter
    @class_sensitive(SonificationGrouping)
    def point_grouping(self, value):
        self._point_grouping = value

    @property
    def show_crosshair(self) -> Optional[bool]:
        """If ``True``, show X and Y crosshairs (if defined on the chart) as the sonification plays. Defaults to
        ``True``.

        .. warning::

           If multiple tracks that play at different times try to show crosshairs, it can be glitchy. Therefore,
           it is recommended in those cases to turn this on/off for individual tracks using the ``.show_play_marker``
           property.

        :rtype: :class:`bool <python:bool>` or :obj:`None <python:None>`
        """
        return self._show_crosshair

    @show_crosshair.setter
    def show_crosshair(self, value):
        if value is None:
            self._show_crosshair = None
        else:
            self._show_crosshair = bool(value)

    @property
    def show_tooltip(self) -> Optional[bool]:
        """If ``True``, show tooltips as the sonification plays. Defaults to ``True``.

        .. warning::

           If multiple tracks that play at different times try to show tooltips, it can be glitchy. Therefore,
           it is recommended in those cases to turn this on/off for individual tracks using the ``.show_play_marker``
           property.

        :rtype: :class:`bool <python:bool>` or :obj:`None <python:None>`
        """
        return self._show_tooltip

    @show_tooltip.setter
    def show_tooltip(self, value):
        if value is None:
            self._show_tooltip = None
        else:
            self._show_tooltip = bool(value)

    @property
    def update_interval(self) -> Optional[int | float | Decimal]:
        """The number of milliseconds to wait between each recomputation of the sonification, if the chart updates
        rapidly.

        .. tip::

          This avoids slowing down processes like panning.

        :rtype: numeric or :obj:`None <python:None>`
        """
        return self._update_interval

    @update_interval.setter
    def update_interval(self, value):
        self._update_interval = validators.numeric(value, allow_empty = True, minimum = 0)

    @classmethod
    def _get_kwargs_from_dict(cls, as_dict):
        kwargs = {
            'after_series_wait': as_dict.get('afterSeriesWait', None),
            'default_instrument_options': as_dict.get('defaultInstrumentOptions', None),
            'default_speech_options': as_dict.get('defaultSpeechOptions', None),
            'duration': as_dict.get('duration', None),
            'enabled': as_dict.get('enabled', None),
            'events': as_dict.get('events', None),
            'global_context_tracks': as_dict.get('globalContextTracks', None),
            'global_tracks': as_dict.get('globalTracks', None),
            'master_volume': as_dict.get('masterVolume', None),
            'order': as_dict.get('order', None),
            'point_grouping': as_dict.get('pointGrouping', None),
            'show_crosshair': as_dict.get('showCrosshair', None),
            'show_tooltip': as_dict.get('showTooltip', None),
            'update_interval': as_dict.get('updateInterval', None),
        }

        return kwargs

    def _to_untrimmed_dict(self, in_cls = None) -> dict:
        untrimmed = {
            'afterSeriesWait': self.after_series_wait,
            'defaultInstrumentOptions': self.default_instrument_options,
            'defaultSpeechOptions': self.default_speech_options,
            'duration': self.duration,
            'enabled': self.enabled,
            'events': self.events,
            'globalContextTracks': self.global_context_tracks,
            'globalTracks': self.global_tracks,
            'masterVolume': self.master_volume,
            'order': self.order,
            'pointGrouping': self.point_grouping,
            'showCrosshair': self.show_crosshair,
            'showTooltip': self.show_tooltip,
            'updateInterval': self.update_interval,
        }

        return untrimmed


'''
Array where each index contains the number of 1s in it's binary form.

Brute Force: Is to obviouly convert each number to binary representation and count number of 1s. This has Time complexity O(n * len(binstring))

However, we can use these rules of binary numbers:
    - Count(n) = Count(n // 2) for even numbers, since doubling an even number just adds a 0 to the right
    - Count(n) = Count(n // 2) + 1 for odd numbers

So, we can combine into one statement by adding (i % 2), which is 1 when odd and 0 when even
'''

class Solution:
    def countBits(self, n: int) -> List[int]:
        counts = [0]

        for i in range(1, n + 1):
            cnt = counts[i // 2] + (i % 2)
            counts.append(cnt)

        return counts


class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        The code is to find the area of the rectangle thats it!
        The code works perfectly for any input
        But time limit is exceeded all the time
        complexityy is 0(n^2)
        """
        h_len = len(height)
        #table = [[None for idx in range(h_len)] for idy in range(h_len)]
        max_area = float('-inf')
        # For 2 points
        for idx in range(h_len-1):
            # find area between these two points
            area = min(height[idx], heigeht[idx+1])
            if max_area < area:
                max_area = area
        # For more than 2 points
        for lent in range(3, h_len+1):
            for idx in range(h_len-lent+1):
                idy = idx+lent-1
                area = min(height[idx],height[idy]) * (idy-idx)
                # print height[idx:idy+1], area, idy, idx
                if area > max_area:
                    max_area = area
        return max_area


import json
import boto3
from datetime import datetime

# get ec2 metrics
def get_metric_ec2(namespace, metricname, client):
    response = client.get_metric_statistics(
            Namespace=namespace,
            MetricName=metricname,
            Dimensions=[
                {
                    'Name': 'InstanceId',
                    'Value': 'i-092988b42c6dea77e'
                }
            ],
            StartTime=datetime(2022, 5, 21),
            EndTime=datetime.now(),
            Period=3600,
            Statistics=[
                'SampleCount', 'Average', 'Sum', 'Minimum', 'Maximum'
            ]
        )
    return response

# get s3  metrics
def get_metric_s3(namespace, metricname, storageType, client):
    response = client.get_metric_statistics(
            Namespace=namespace,
            MetricName=metricname,
            Dimensions=[
                {
                    'Name': 'StorageType',
                    'Value': storageType
                },
                {
                    'Name': 'BucketName',
                    'Value': 'tdg-s3-bucket'
                }
            ],
            StartTime=datetime(2022, 5, 21),
            EndTime=datetime.now(),
            Period=3600,
            Statistics=[
                'SampleCount', 'Average', 'Sum', 'Minimum', 'Maximum'
            ]
        )
    return response

def lambda_handler(event, context):

    headers = {
        'Access-Control-Allow-Origin': '*'
    }

    if "headers" in event and "referer" in event["headers"] and "18.215.185.124" in event["headers"]["referer"]:

        path = event["rawPath"].split("/")
        namespace = "AWS/" + path[1]
        metricname = path[2]

        if namespace == "AWS/EC2":
            client = boto3.client('cloudwatch', region_name='us-east-1')
            return {
                'statusCode': 200,
                'headers': headers,
                'body': json.dumps(get_metric_ec2(namespace, metricname, client), default=str)
            }
        else:
            client = boto3.client('cloudwatch', region_name='eu-west-3')
            storageType = path[3]
            return {
                'statusCode': 200,
                'headers': headers,
                'body': json.dumps(get_metric_s3(namespace, metricname, storageType, client), default=str)
            }

    else:
        return {
            'statusCode': 403,
            'headers': headers,
            'body': json.dumps("Access denied")
        }


import cv2

filepath = "vtest.avi"
# cap = cv2.VideoCapture(filepath)
# Webカメラを使うときはこちら

class Capture:
    """
    Captureクラスは動画の動体検出をサポートするメソッドを提供します。
    """
    def __init__(self,movie_path:str|None=None,device:int=0) -> None:
        """initialize capture mode. and configs."""

        if not movie_path:
            self.cap = cv2.VideoCapture(device)
        else:
            try:
                if movie_path[-3:] != 'mp4':
                    raise "Non-mp4 files are not supported."
                self.cap = cv2.VideoCapture(movie_path)
            except:
                raise """cannot capture video. not found video.
                        arrow to capture 'mp4'.
                        """

        self.avg = None

    def motion_detection(self,reseption:float=0.8):
        while True:
            # 1フレームずつ取得する。
            ret, frame = self.cap.read()
            if not ret:
                break

            # グレースケールに変換
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            # 比較用のフレームを取得する
            if self.avg is None:
                self.avg = gray.copy().astype("float")
                continue

            # 現在のフレームと移動平均との差を計算
            cv2.accumulateWeighted(gray, self.avg, reseption)
            frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(self.avg))

            # デルタ画像を閾値処理を行う
            thresh = cv2.threshold(frameDelta, 3, 255, cv2.THRESH_BINARY)[1]
            # 画像の閾値に輪郭線を入れる
            contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            frame = cv2.drawContours(frame, contours, -1, (0, 255, 0), 3)

            # 結果を出力
            cv2.imshow("Frame", frame)
            key = cv2.waitKey(30)
            if key == 27:
                break

        self.cap.release()
        cv2.destroyAllWindows()

if __name__ == "__main__":
    cc = Capture().motion_detection(reseption=0.5)


def not_empty(s):
    return s and s.strip()

list(filter(not_empty, ['A', '地方', ' B阿斯顿发 ', None, 'C', '  ']))

str = 'sakdj '
str.strip( )
str

sorted([28,2345,723467,12541023,23,-1878,89*52],key=abs)

list(map(lambda x:x*x,[1,2,4,5,6,10]))

50**3
7//2.1

thisset = set(("Google", "Runoob", "Taobao"))
thisset.update({"123"})
thisset

my_set = set({'apple'})
my_set


from flask import Flask, request
import json
from datetime import datetime
import requests
from lights import light

from constants import Tables, Params, PHUE
from sqlite import sqlite

app = Flask(__name__)

Light1 = light.Light(1)
Light2 = light.Light(3)

@app.route("/listener")
def generate_refresh_token():
    code = request.args.get(Params.CODE.value)
    url = f"https://api.meethue.com/oauth2/token?code={code}&grant_type=authorization_code"
    generated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    response = json.loads(requests.post(url, auth=PHUE.AUTH.value).text)
    access_token = response[Params.ACCESS_TOKEN.value]
    refresh_token = response[Params.REFRESH_TOKEN.value]
    c = sqlite.SQLite()
    response, code = c.delete_all(Tables.TOKENS.value)
    if code == 409:
        c.close_conn()
        return response
    response, code = c.insert(
        Tables.TOKENS.value, (generated_at, access_token, refresh_token))
    if code == 409:
        c.close_conn()
        return response
    Light1.tokens.pull_tokens()
    Light2.tokens.pull_tokens()
    Light1.pull_light_data()
    Light2.pull_light_data()
    return "Success! Tokens have been generated!", 201

@app.route("/create-table", methods=['POST'])
def create_table():
    body = request.json
    columns = body[Params.COLUMNS.value]
    table_columns = ""
    for key in columns:
        try:
            assert (columns[key] in Tables.COLUMN_TYPES.value)
        except:
            message = f"Table column '{key}' can only be of type 'text', 'real' or 'integer'. '{columns[key]}' is not allowed."
            return message, 409
        else:
            table_columns += f"{key} {columns[key]},\n"
    table_columns = table_columns[:-2]
    c = sqlite.SQLite()
    response = c.create_table(body['table_name'], table_columns)
    c.close_conn()
    return response

@app.route("/lights/<id>/power-on", methods=['POST'])
def power_on(id):
    light = Light1 if int(id) == 1 else Light2
    return light.set_light("on")

@app.route("/lights/<id>/power-off", methods=['POST'])
def power_off(id):
    assert id == request.view_args[Params.ID.value]
    light = Light1 if int(id) == 1 else Light2
    return light.set_light("off")

@app.route("/db/<table>", methods=['GET'])
def get_dblight_data(table):
    assert table == request.view_args['table']
    c = sqlite.SQLite()
    response, code = c.get_all(table)
    c.close_conn()
    return response, code

@app.route("/lights/state", methods=["GET"])
def curr_light_state():
    state = []
    state.append(Light1.get_light_data())
    state.append(Light2.get_light_data())
    return state


#program to print stars(*) in nxn matrix form
'''eg:
5
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
	'''

class Solution:

    def printSquare(self, N):

        for i in range (N):
            for j in range(N):
                print("*",end=" ")
            print( )
if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        N = int(input())
        if(N>=1 and N<=20):
        	ob = Solution()
        	ob.printSquare(N)


from django.shortcuts import render
from django.http import HttpResponse
from django.template import Template,Context
# Create your views here.

def suma(request,num1,num2):
	res = num1+num2
	contenido = """

El resultado es: %s

	 """ %res
	return HttpResponse(contenido)

def prueba1(request):
	externo = open("C:/Users/erick/OneDrive/Escritorio/Trabajos Django/ESYG/templates/prueba.html")
	plantilla = Template(externo.read())
	externo.close()
	ctx = Context()
	contenido = plantilla.render(ctx)
	return HttpResponse(contenido)

def prueba2(request):
	return render(request,"prueba.html")


from mrjob.job import MRJob
from mrjob.protocol import JSONProtocol, RawValueProtocol, JSONValueProtocol
from mrjob.step import MRStep
import json
import numpy as np

def multivar_gauss_pdf(x, mu, cov):
    '''
    Caculates the multivariate normal density (pdf)

    Parameters:
    -----------

    x    - numpy array of a "d x 1" sample vector
    mu   - numpy array of a "d x 1" mean vector
    cov  - numpy array of a d x d" covariance matrix

    (where d - dimensionality of data)

    Output:
    -------
            - (float) probability of x given parameters of
                     Gaussian Distribution
    '''
    part1 = 1 / ( ((2* np.pi)**(len(mu)/2)) * (np.linalg.det(cov)**(1/2)) )
    part2 = (-1/2) * np.dot(np.dot((x-mu).T,(np.linalg.inv(cov))),(x-mu))
    return float(part1 * np.exp(part2))

def responsibility(x,mu,cov,p,K):
    '''
    Calculates conditional probability of latent variable given
    observed data and parameters

    Parameters:
    -----------

    x     - numpy array of a "d x 1" sample vector
    mu    - list of length "K" of lists "d x 1" mean vector
    cov   - list of length "K" numpy arrays each "d x d" covariance matrix
    p     - list of floats, each float prior probability of cluster
    K     - number of clusters (values of latent variables)

    (where d - dimensionality of data)

    Output:
          - list of floats, each element of list is responsibility corresponding
            to x and relevant latent variable valiue
    '''
    resps = [p[k]*multivar_gauss_pdf(x,np.array(mu[k]),np.array(cov[k])) for k in range(K)]
    p_x = sum(resps)
    return [float(r_k)/p_x for r_k in resps]

def extract_features(line):
    ''' extracts features from line of input'''
    data = line.strip().split(",")
    return [ float(e) for e in data[1:] ]

def make_json_encodable(mixing, means, covar):
    '''
    Transforms

    Parameters:
    -----------

    mixing   - list of size k
    means    - list of size k of numpy arrays (each numpy array has size d)
    covar    - list of size k of two dimensional numpy array (matrix of size dxd)

    (where d is dimensionality and k is number of clusters)

    Output:
    --------
             - dictionary with parameter names as keys
             {"mu": list of mean vectors, "mixing": list of mixing coefficients,
              "covariance": list of covariance matrices}

    '''
    matrix_to_list = lambda x: [list(e) for e in x]
    mixing = mixing
    means = matrix_to_list(means)
    covariance = [matrix_to_list(e) for e in covar]
    return {"mixing":mixing,"mu":means,"covariance":covariance}

class IterationGaussianMixtureMR(MRJob):
    '''
    Runs single iteration of Expectation Maximization Algorithm for Gaussian
    Mixture Model.

    Mappers use parameters from previous iteration to calculate responsibilities
    and intermediate values that are then used by single reducer to calculate
    new parameters.

    Command Line Options:
    ---------------------

    --clusters             - number of clusters
    --dimensions           - dimensionality of data
    --parameters           - (str)json encoded dictionary of parameters

    '''
    INPUT_PROTOCOL = RawValueProtocol

    INTERNAL_PROTOCOL = JSONProtocol

    OUTPUT_PROTOCOL = JSONValueProtocol

    def __init__(self,*args,**kwargs):
        super(IterationGaussianMixtureMR,self).__init__(*args,**kwargs)
        # sum of responsibilities for each cluster & number of observations
        self.resp_sum = [0]*self.clusters
        self.N = 0
        # sum of observations weighted by reponsibility
        self.resp_w_sum = [np.zeros(self.dim, dtype = np.float64) for i in range(self.clusters)]
        # sum of x_n*x_n_t (outer products) weighted by reponsibility
        self.resp_w_cov = [np.zeros([self.dim,self.dim], dtype = np.float64) for i in range(self.clusters)]

    def configure_options(self):
        super(IterationGaussianMixtureMR,self).configure_options()
        self.add_passthrough_option("--dimensions",
                                    type = int,
                                    help = "dimensionality of input data")
        self.add_passthrough_option("--clusters",
                                    type = int,
                                    help = "number of clusters")
        self.add_passthrough_option("--parameters",
                             type = str,
                             help = "file with parameters from previous iteration")

    def load_options(self,args):
        super(IterationGaussianMixtureMR,self).load_options(args)
        # number of clusters
        if self.options.clusters is None:
            self.option_parser.error("You need to specify number of clusters")
        else:
            self.clusters = self.options.clusters
        # data dimensionality
        if self.options.dimensions is None:
            self.option_parser.error("You need to specify dimensionality of data")
        else:
            self.dim = self.options.dimensions
        # filename where parameters from previous iteration are saved
        if self.options.parameters is None:
            self.option_parser.error("You need to load file with distribution parameters")

    def mapper_gmm_init(self):
        params = json.loads(self.options.parameters)
        self.mu = params["mu"]
        self.covar = params["covariance"]
        self.mixing = params["mixing"]

    def mapper_gmm(self,_,line):
        features = extract_features(line)
        assert(len(features)==self.dim), "dimension mismatch"
        x = np.array(features)
        r_n = responsibility(x,self.mu,self.covar,self.mixing,self.clusters) # responsibilities
        self.resp_sum = [self.resp_sum[i]+r_n_k for i,r_n_k in enumerate(r_n)]
        self.resp_w_sum = [w_sum + r_n[i]*x for i,w_sum in enumerate(self.resp_w_sum)]
        self.resp_w_cov = [w_covar+r_n[i]*np.outer(x,x) for i,w_covar in enumerate(self.resp_w_cov)]
        self.N+=1

    def mapper_final_gmm(self):
        matrix_to_list = lambda x: [list(e) for e in x]
        # sum of responsibilities
        yield 1,("r_sum", self.resp_sum)
        # sum of observations weighted by responsibility
        yield 1,("r_w_sum", [list(e) for e in self.resp_w_sum])
        # covariates weighted by responsibility
        yield 1,("r_w_cov", [ matrix_to_list(cov) for cov in self.resp_w_cov])
        # number of observations
        yield 1,("total", self.N)

    def reducer_gmm(self,key, values):
        N = 0;
        r_sum = [0]*self.clusters
        r_w_sum = [np.zeros(self.dim, dtype = np.float64) for i in range(self.clusters)]
        r_w_cov = [np.zeros([self.dim,self.dim], dtype = np.float64) for i in range(self.clusters)]
        for value in values:
            if value[0]=="r_sum":
                r_sum = [r_sum[i]+gamma for i,gamma in enumerate(value[1])]
            elif value[0]=="r_w_sum":
                r_w_sum = [r_w_sum[i]+np.array(r_w_new, dtype = np.float64) for i,r_w_new in enumerate(value[1])]
            elif value[0]=="r_w_cov":
                r_w_cov = [ r_w_cov[i] + np.array(cov) for i,cov in enumerate(value[1])]
            elif value[0]=="total":
                N+=value[1]
        mixing = [float(gamma)/N for gamma in r_sum]
        means =  [1.0/r_sum[i]*r_w_sum[i] for i, gamma in enumerate(mixing)]
        covar =  [ 1.0/r_sum[k]*r_w_cov_k - np.outer(means[k],means[k]) for k,r_w_cov_k in enumerate(r_w_cov)]
        yield None, make_json_encodable(mixing,means,covar)

    def steps(self):
        return [MRStep(mapper_init = self.mapper_gmm_init,
                       mapper = self.mapper_gmm,
                       mapper_final = self.mapper_final_gmm,
                       reducer = self.reducer_gmm)]

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

Gaussian Mixture Model MapReduce/IterationGaussianMixtureMR.py