from bs4 import BeautifulSoup
import requests
import db

RAIFEISSEN_URL = "https://www.raiffeisen.ru/currency_rates/"
RAIFESSEN_CURRENCIES_ROW_ALLOCATOR = "b-table__row"
RAIFESSEN_CURRENCIES_TABLE_ALLOCATOR = "b-table-currency"

BANKI_URL = "https://www.banki.ru/products/currency/cash/kazan~/"
BANKI_CURRENCIES_TABLE_ALLOCATOR = "currency-table__table"
BANKI_CURRENCIES_ROW_ALLOCATOR = "currency-table__bordered-row"

def parse_raifessen_page() -> list:
    rsp = requests.get(RAIFEISSEN_URL)
    soup = BeautifulSoup(rsp.text)

    currencies_table = soup.find("div", {"class": RAIFESSEN_CURRENCIES_TABLE_ALLOCATOR})
    currencies_rows = currencies_table.findAll("div", {"class": RAIFESSEN_CURRENCIES_ROW_ALLOCATOR})

    currencies_exchanges = []
    for row in currencies_rows:
        children = row.findChildren("div", recursive=False)
        child_num = 0
        currencies_exchange = {}
        for child in children:
            if child_num == 0:
                currencies_exchange['code'] = child.text.strip()
            if child_num == 2:
                currencies_exchange['name'] = child.text.strip()
            if child_num == 3:
                currencies_exchange['buy'] = child.text.strip().replace(',', '.')
            if child_num == 4:
                currencies_exchange['sale'] = child.text.strip().replace(',', '.')
            child_num += 1
        currencies_exchanges.append(currencies_exchange)
    return currencies_exchanges

def parse_banki_page() -> list:
    rsp = requests.get(BANKI_URL)
    soup = BeautifulSoup(rsp.text)

    currencies_table = soup.find("table", {"class": BANKI_CURRENCIES_TABLE_ALLOCATOR})
    currencies_rows = currencies_table.findAll("tr", {"class": BANKI_CURRENCIES_ROW_ALLOCATOR})

    currencies_exchanges = []
    for row in currencies_rows:
        children = row.findChildren("td", recursive=False)
        child_num = 0
        currencies_exchange = {}
        for child in children:
            if child_num == 0:
                currencies_exchange['code'] = child.text.strip()
            if child_num == 1:
                currencies_exchange['cb'] = child.findChild().text.strip().replace(',', '.')
            if child_num == 2:
                currencies_exchange['buy'] = child.findChildren()[1].text.strip().replace(',', '.')
                currencies_exchange['best_buy'] = child.findChildren()[2].text.strip().replace('\n', '').replace('\t',
                                                                                '')
            if child_num == 3:
                currencies_exchange['sale'] = child.findChildren()[1].text.strip().replace(',', '.')
                currencies_exchange['best_sale'] = child.findChildren()[2].text.strip().replace('\n', '').replace('\t',
                                                                                '')
            child_num += 1
        currencies_exchanges.append(currencies_exchange)
    return currencies_exchanges

def save_data_to_db(raifessen_currency_exchanges, banki_currency_exchanges):
    for banki_item in banki_currency_exchanges:
        for raifessen_item in raifessen_currency_exchanges:
            if banki_item['code'] == raifessen_item['code']:
                obj = db.CurrenciesRecord(
                    code=banki_item['code'], name=raifessen_item['name'], cb_currency=float(banki_item['cb']),
                    raif_buy=float(raifessen_item['buy']), raif_sale=float(raifessen_item['sale']),
                    best_buy=float(banki_item['buy']), best_sale=float(banki_item['sale']),
                    best_buyer=banki_item['best_buy'], best_sailer=banki_item['best_sale'])
                db.session.add(obj)
                db.session.commit()

def get_currencies():
    raifessen_currency_exchanges = parse_raifessen_page()
    banki_currency_exchanges = parse_banki_page()

    save_data_to_db(raifessen_currency_exchanges, banki_currency_exchanges)


import sys
import math
from copy import deepcopy
from collections import defaultdict

allData = sys.stdin.read().split('\n')

inspects = [0] * 8
items = []
ops = ["*13", "+3", "+6", "+2", "**2", "+4", "*7", "+7"]
#ops = ["*19", "+6", "**2", "+3"]
tests = []
trues = []
falses = []

for i in range(0, len(allData), 7):
    id = allData[i]
    held = allData[i + 1]
    held = [int(x) for x in held[18:].split(",")]
    items.append(held)
    op = allData[i + 2]
    test = allData[i + 3]
    test = int(test[21:])
    tests.append(test)
    true = allData[i + 4]
    true = int(true[-1])
    trues.append(true)
    false = allData[i + 5]
    false = int(false[-1])
    falses.append(false)

run = 1
for t in tests:
    print(t)
    run *= t
print(run)

for x in range(10000):
    #print(x)
    for i, monkey in enumerate(items):
        for ele in monkey:
            inspects[i] += 1
            newlvl = eval(str(ele) + ops[i])
            #newlvl = newlvl // 3
            newlvl = newlvl % run
            if (newlvl % tests[i] == 0):
                items[trues[i]].append(newlvl)
            else:
                items[falses[i]].append(newlvl)
        items[i] = []

print(items)
print(inspects)
print(sorted(inspects)[-2:])


import re

from helpers import only_digits

class SoupWgets:
    @staticmethod
    def andorra(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'div' and \
                'col-2' in tag.get('class', []) and \
                'Confirmats totals' in tag.contents[0]
        tags = soup.find_all(condition)
        assert len(tags) == 1
        return tags[0].parent, int(tags[0].contents[2])

    @staticmethod
    def armenia(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'script' and \
                len(tag.contents) == 1 and \
                'window.infographicData' in tag.contents[0]
        tag = soup.find(condition)
        cases = re.search(
            '"text":"Հաստատված դեպքերի ընդհանուր քանակը-([0-9]+)"',
            tag.contents[0]
        ).group(1)
        return tag, int(cases)

    @staticmethod
    def azerbaijan(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'span' and \
                'Virusa yoluxan' in tag.contents[0]
        tags = soup.find_all(condition)
        # assert len(tags) == 2
        return tags[0].parent.parent, \
            int(tags[0].find_previous_sibling('strong').contents[0])

    @staticmethod
    def belarus(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'div' and \
                'ЗАРЕГИСТРИРОВАНЫ' in tag.contents
        tags = soup.find_all(condition)
        assert len(tags) == 2
        return tags[0].parent.parent, \
            int(tags[0].find_previous_sibling(
                'div').contents[0].contents[0].replace(' ', ''))

    @staticmethod
    def bulgaria(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'p' and \
                'statistics-value' in tag.get('class', []) and \
                'confirmed' in tag.get('class', []) and \
                len(tag.contents) == 1
        tag = soup.find(condition)
        return tag, int(tag.contents[0])

    @staticmethod
    def czechia(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'p' and \
                'mb-0 text--center' == ' '.join(tag.get('class', [''])) and \
                len(tag.contents) == 1 and \
                tag.contents[0] == 'Potvrzené případy'
        tag = soup.find(condition)
        return tag.parent, \
            int(tag.find_next_sibling(
            ).find(
                'span', attrs={'id': 'count-sick'}
            ).contents[0].replace(u'\xa0', ''))

    @staticmethod
    def france(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'h4' and \
                'table-indicateurs-open-data-france' in tag.text
        tags = soup.find_all(condition)
        assert len(tags) == 1
        return tags[0].text.replace(' ', '').replace('\n', ''), None

    @staticmethod
    def germany(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'strong' and \
                'Gesamt' == tag.text
        tag = soup.find(condition)
        tag = tag.parent.find_next_sibling()
        # Before 2022-01-26
        # return tag, int(tag.strong.text.replace('.', ''))
        return tag, int(only_digits(tag.text))

    @staticmethod
    def gibraltar_before_2021_11_20_17_24_02(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'li' and \
                'Confirmed cases:' in tag.contents[0]
        tags = soup.find_all(condition)
        assert len(tags) == 1
        return tags[0].parent, int(tags[0].contents[0][17:])

    @staticmethod
    def gibraltar_before_2021_12_12_14_41_04(soup):
        def condition_recovered(tag):
            if tag is None:
                return False
            return tag.name == 'li' and \
                'Recovered cases:' in tag.contents[0]

        def condition_active(tag):
            if tag is None:
                return False
            return tag.name == 'li' and \
                'Active cases in Gibraltar' in tag.contents[0]

        def condition_deaths(tag):
            if tag is None:
                return False
            return tag.name == 'li' and \
                'Deaths' in tag.contents[0]
        tags_recovered = soup.find_all(condition_recovered)
        tags_active = soup.find_all(condition_active)
        tags_deaths = soup.find_all(condition_deaths)
        assert len(tags_recovered) == 1
        assert len(tags_active) == 1
        assert len(tags_deaths) == 1
        total_cases = int(tags_recovered[0].contents[0][17:]) + \
            int(tags_active[0].contents[2].split('(')[0][2:]) + \
            int(tags_deaths[0].contents[0][8:])
        return tags_recovered[0].parent, total_cases

    @staticmethod
    def gibraltar(soup):
        def condition_recovered(tag):
            if tag is None:
                return False
            return tag.name == 'li' and \
                'Recovered cases:' in tag.contents[0]

        def condition_active(tag):
            if tag is None:
                return False
            return tag.name == 'li' and \
                'Active cases in Gibraltar' in tag.contents[0]

        def condition_deaths(tag):
            if tag is None:
                return False
            return tag.name == 'li' and \
                'Deaths' in tag.contents[0]
        tags_recovered = soup.find_all(condition_recovered)
        tags_active = soup.find_all(condition_active)
        tags_deaths = soup.find_all(condition_deaths)
        assert len(tags_recovered) == 1
        assert len(tags_active) == 1
        assert len(tags_deaths) == 1
        total_cases = int(only_digits(tags_recovered[0].contents[0][17:])) + \
            int(only_digits(tags_active[0].contents[2].split('(')[0][2:])) + \
            int(only_digits(tags_deaths[0].contents[0][8:].split(' ')[0]))
        return tags_recovered[0].parent, total_cases

    @staticmethod
    def greece(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'a' and \
                'Ημερήσια έκθεση επιτήρησης COVID-19' in tag.get('aria-label', '')
        tag = soup.find(condition)
        return tag['aria-label'], None

    @staticmethod
    def kyrgyzstan_before_2021_01_12_9_15_00(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'section' and \
                'sp-section-3' in tag.get('id', '')
        tag = soup.find(condition)
        covid_1 = tag.tbody.tr.find_next_sibling().find_next_sibling(
            ).td.find_next_sibling().find_next_sibling()
        covid_2 = covid_1.find_next_sibling()
        cases = (
            int(covid_1.p.span.span.b.contents[0]),
            int(covid_2.p.span.strong.span.contents[0])
        )
        return tag.tbody, cases[0]

    @staticmethod
    def kyrgyzstan(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'h4' and \
                'Всего' in tag.text
        tag = soup.find(condition)
        covid_1 = tag.parent.parent.find_next_sibling().find_next_sibling().div
        covid_2 = covid_1.find_next_sibling()
        cases = int(covid_1.h4.text) + int(covid_2.h4.text)
        return tag.parent.parent, cases

    @staticmethod
    def luxembourg(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'article' and \
                'card' in tag.get('class', []) and \
                'resource-card' in tag.get('class', [])
        tag = soup.find(condition)
        return tag.div.h4.contents[0], None

    @staticmethod
    def north_macedonia(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'a' and \
                'податоци за covid-19' in tag.get('title', '').lower()
        tag = soup.find(condition)
        return tag, None

    @staticmethod
    def portugal(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'a' and \
                len(tag.contents) == 1 and \
                'Relatório de Situação nº' in tag.text
        tag = soup.find(condition)
        return tag.text, None

    @staticmethod
    def spain(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'div' and \
                'banner-coronavirus banner-verde' == ' '.join(tag.get('class', ['']))
        tag = soup.find(condition)
        return tag, int(tag.find('p', {'class': 'cifra'}).text.replace('.', ''))

    @staticmethod
    def romania(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'h3' and \
                tag.get('id', '') == 'chart-label-confirmed_cases'
        tag = soup.find(condition)
        return tag, int(only_digits(tag.text))

    @staticmethod
    def russia(soup):
        def condition(tag):
            if tag is None:
                return False
            # Change since 2022-01-20 11:24:23
            # 'Выявлено случаев' = total cases -> 'Выявлено' = daily cases
            return tag.name == 'div' and \
                'cv-countdown__item-label' in tag.get('class', []) and \
                len(tag.contents) == 1 and \
                (
                    'Выявлено' in tag.contents or
                    'Выявлено случаев' in tag.contents
                )
        tags = soup.find_all(condition)
        # assert len(tags) == 1
        return tags[0].parent.parent, \
            int(tags[0].find_previous_sibling(
            ).contents[0].contents[0].replace(' ', ''))

    @staticmethod
    def switzerland(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'th' and \
                tag.get('class', [''])[0] == 'detail-card-geography-table__title-cell' and \
                len(tag.contents) == 1 and \
                tag.contents[0] == 'Switzerland'
        tag = soup.find(condition)
        number_tag = tag.find_next_sibling().find_next_sibling()
        number = number_tag.contents[0].replace(' ', '')
        return tag.parent, int(number)

    @staticmethod
    def ukraine(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'span' and \
                'хворих на Covid-19' in tag.contents
        tags = soup.find_all(condition)
        assert len(tags) == 1
        return tags[0].parent.parent, \
            int(tags[0].find_next_sibling(
                ).contents[0].strip().replace(' ', ''))

    @staticmethod
    def uzbekistan(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'p' and \
                'Всего подтверждено' in tag.contents[0]
        tags = soup.find_all(condition)
        assert len(tags) == 1
        return tags[0].parent.parent.parent, \
            int(tags[0].find_next_sibling()['data-count'])

    # AFRO
    @staticmethod
    def cote_divoire_one(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'div' and \
                'alert alert-danger alert-dismissible fade show cas' in ' '.join(tag.get('class', [])) and \
                'Cas Confirmés' in tag.text
        tag = soup.find(condition)
        total = tag.strong.text
        return tag, int(only_digits(total))

    @staticmethod
    def equatorial_guinea(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'b' and \
                'Casos confirmados' == tag.text
        tag = soup.find(condition).parent.parent
        total = tag.find_next_sibling().find_next_sibling().find_next_sibling().text
        return tag, int(only_digits(total))

    @staticmethod
    def ethiopia(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'div' and \
                'highlight-body' in tag.get('class', []) and \
                'Total Cases' == tag.text
        tag = soup.find(condition).parent
        return tag, int(only_digits(tag.div.text))

    @staticmethod
    def nigeria(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'h6' and \
                'text-white' in tag.get('class', []) and \
                'Confirmed Cases' in tag.text
        tag = soup.find(condition).parent
        total = tag.h2.text
        return tag, int(only_digits(total))

    @staticmethod
    def sierra_leone(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'span' and \
                'exad-corona-label' in tag.get('class', []) and \
                'Cases:' in tag.text
        tag = soup.find(condition)
        total = tag.find_next_sibling().text
        return tag.parent, int(only_digits(total))

    @staticmethod
    def uganda(soup):
        def condition(tag):
            if tag is None:
                return False
            return tag.name == 'h5' and \
                'mb-0 f18 txt-color' in ' '.join(tag.get('class', [])) and \
                'CUMULATIVE CASES' in tag.text
        tag = soup.find(condition).parent
        total = tag.h2.text
        return tag.parent, int(only_digits(total))


import databases
import sqlalchemy

from fastapi import FastAPI, Request

from pydantic import BaseModel, ValidationError

from decouple import config

DATABASE_URL = f"postgresql://{config('DB_USER')}:{config('DB_PASSWORD')}@{config('DB_HOST')}:{config('DB_PORT')}/{config('DB_DATABASE')}"

database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()

# on each change of tables, run the following commands:
# alembic revision --autogenerate -m "Many to many relationship"
# alembic upgrade head

books = sqlalchemy.Table(
    'books',
    metadata,
    sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column('title', sqlalchemy.String),
    sqlalchemy.Column('author', sqlalchemy.String),
)

readers = sqlalchemy.Table(
    'readers',
    metadata,
    sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column('first_name', sqlalchemy.String),
    sqlalchemy.Column('last_name', sqlalchemy.String),
)

readers_books = sqlalchemy.Table(
    'readers_books',
    metadata,
    sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column('book_id', sqlalchemy.Integer, sqlalchemy.ForeignKey('books.id'), nullable=False),
    sqlalchemy.Column('reader_id', sqlalchemy.Integer, sqlalchemy.ForeignKey('readers.id'), nullable=False),
)

# Not needed if using alembic
# engine = sqlalchemy.create_engine(DATABASE_URL)
# metadata.create_all(engine)

class BookCreate(BaseModel):
    title: str
    author: str

class ReaderCreate(BaseModel):
    first_name: str
    last_name: str

class ReadBookCreate(BaseModel):
    book_id: int
    reader_id: int

app = FastAPI()

@app.on_event('startup')
async def startup():
    await database.connect()

@app.on_event('shutdown')
async def shutdown():
    await database.disconnect()

@app.get('/books/')
async def get_all_books():
    query = books.select()
    return await database.fetch_all(query)

# @app.post('/books/')
# async def create_book(request: Request):
#     data = await request.json()
#     query = books.insert().values(**data)
#     last_record_id = await database.execute(query)
#     return {'id': last_record_id}

@app.post('/books/')
async def create_book(data: BookCreate):
    try:
        book_data = BookCreate(**data.dict())
    except ValidationError as e:
        return {'error': str(e)}

    query = books.insert().values(**book_data.dict())
    last_record_id = await database.execute(query)

    return {'id': last_record_id}

@app.get('/readers/')
async def get_all_readers():
    query = readers.select()
    return await database.fetch_all(query)

# @app.post('/readers/')
# async def create_reader(request: Request):
#     data = await request.json()
#     query = readers.insert().values(**data)
#     last_record_id = await database.execute(query)
#     return {'id': last_record_id}

@app.post('/readers/')
async def create_reader(request: ReaderCreate):
    try:
        reader_data = ReaderCreate(**request.dict())
    except ValidationError as e:
        return {'error': str(e)}

    query = readers.insert().values(**reader_data.dict())
    last_record_id = await database.execute(query)

    return {'id': last_record_id}

@app.post('/read/')
async def create_read_book(request: ReadBookCreate):
    try:
        readbook_data = ReadBookCreate(**request.dict())
    except ValidationError as e:
        return {'error': str(e)}

    query = readers_books.insert().values(**readbook_data.dict())
    last_record_id = await database.execute(query)

    return {'id': last_record_id}


import torch
import torch.nn as nn
import numpy as np
import read_bvh
from ForwardKinematics import FK
import tools

#Joints_num =  57
#In_frame_size = Joints_num*3= 171
class Model(nn.Module):
    def __init__(self, joint_num=57,out_rotation_mode="Quaternion"):
        super(Model, self).__init__()

        self.joint_num=joint_num

        self.out_rotation_mode = out_rotation_mode

        self.joint_parent_matrix=torch.autograd.Variable(torch.Tensor(read_bvh.parenting_matrix).cuda())

        if(self.out_rotation_mode=="ortho6d"):
            self.out_channel = 6
        if(self.out_rotation_mode=="ortho5d"):
            self.out_channel = 5
        elif (self.out_rotation_mode=="Quaternion"):
            self.out_channel = 4
        elif (self.out_rotation_mode=="AxisAngle"):
            self.out_channel = 4
        elif (self.out_rotation_mode=="euler"):
            self.out_channel = 3
        elif (self.out_rotation_mode=="hopf"):
            self.out_channel = 3
        elif (out_rotation_mode  == "rmat"):
            self.out_channel = 9

        #if(self.hip_5d_rotation==True):
        #    self.out_channel = 5+(joint_num-1)*3
        self.mlp = nn.Sequential(
                nn.Linear(self.joint_num*3, 1024),
                nn.LeakyReLU(),
                nn.Linear(1024, 1024),
                nn.LeakyReLU(),
                nn.Linear(1024, 1024),
                nn.LeakyReLU(),
                nn.Linear(1024, self.out_channel*joint_num)
                )

    #lst joint_num
    def set_parent_index_lst(self,parent_index_lst):
        self.parent_index_lst = parent_index_lst

    #numpy joint_num*3
    def set_joint_offsets(self, joint_offsets):
        self.joint_offsets = joint_offsets

    def initialize_skeleton_features(self, standard_bvh_fn):
        fk=FK()
        joint_offsets, parent_index_lst, joint_index_lst = fk.get_offsets_and_parent_index_lst(standard_bvh_fn)
        joint_offsets=joint_offsets*0.01
        self.set_parent_index_lst(parent_index_lst)
        self.set_joint_offsets(joint_offsets)

        #self.joint_rotation_matrix_limitation_mask = torch.autograd.Variable(torch.FloatTensor(fk.get_joint_rotation_matrix_limitaion_mask_np(joint_index_lst)).cuda()) #joint_num*4*4
        #self.joint_rotation_matrix_limitation_mask = self.joint_rotation_matrix_limitation_mask.view(1,self.joint_num, 4,4)

    #joint_rotation_matrices batch*joint_num*4*4
    #the output pose will be fixed at the hip position
    #pose_batch batch*joint_num*3
    def rotation_seq2_pose_seq(self, joint_rotation_matrices):
        joint_num=self.joint_num
        batch=joint_rotation_matrices.shape[0]

        ##get the offsets batch
        offsets_batch = torch.autograd.Variable(torch.FloatTensor(self.joint_offsets).cuda())
        offsets_batch = offsets_batch.view(1, joint_num,3).repeat(batch, 1,1) #batch*joint_num*3

        fk=FK()

        pose_batch=fk.compute_global_positions(self.parent_index_lst, offsets_batch, joint_rotation_matrices)#batch*joint_num*3
        return pose_batch.contiguous()

    #in_seq  b*joint_num*3
    #out_poses b*joint_num*3
    #out_rotation_matrix b*joint_num*4*4
    def forward(self, in_seq):
        batch=in_seq.shape[0]

        if(self.out_rotation_mode == "Quaternion"):
            out_r = self.mlp(in_seq.view(batch,-1)) #batch*(joint_num*4)
            out_rotation_matrices = tools.compute_rotation_matrix_from_quaternion(out_r.view(-1, self.out_channel))#(batch*joint_num)*3*3
        elif (self.out_rotation_mode == "ortho6d"):
            out_r = self.mlp(in_seq.view(batch,-1)) #batch*(joint_num*6)
            out_rotation_matrices = tools.compute_rotation_matrix_from_ortho6d(out_r.view(-1, self.out_channel))
        elif (self.out_rotation_mode == "ortho5d"):
            out_r = self.mlp(in_seq.view(batch,-1)) #batch*(joint_num*5)
            out_rotation_matrices = tools.compute_rotation_matrix_from_ortho5d(out_r.view(-1, self.out_channel))
        elif (self.out_rotation_mode == "AxisAngle"):
            out_r = self.mlp(in_seq.view(batch,-1)) #batch*(joint_num*4)
            out_rotation_matrices = tools.compute_rotation_matrix_from_axisAngle(out_r.view(-1, self.out_channel))
        elif (self.out_rotation_mode == "euler"):
            out_r = self.mlp(in_seq.view(batch,-1)) #batch*(joint_num*3)
            out_rotation_matrices = tools.compute_rotation_matrix_from_euler(out_r.view(-1, self.out_channel))
        elif ((self.out_rotation_mode=="rmat") and (self.training==True)):
            out_r = self.mlp(in_seq.view(batch,-1)) #batch*(joint_num*9)
            out_rotation_matrices = out_r.view(-1,3,3)#(b*joint_num)*3*3
        elif ((self.out_rotation_mode=="rmat") and (self.training==False)):
            out_r = self.mlp(in_seq.view(batch,-1)) #batch*(joint_num*9)
            out_rotation_matrices = out_r.view(-1,3,3)#(b*joint_num)*3*3
            out_rotation_matrices = tools.compute_rotation_matrix_from_matrix(out_rotation_matrices)

        out_rotation_matrices = tools.get_44_rotation_matrix_from_33_rotation_matrix(out_rotation_matrices).view(batch,self.joint_num,4,4)#(batch*joint_num)*4*4
        #out_rotation_matrices = out_rotation_matrices * self.joint_rotation_matrix_limitation_mask.expand(batch, self.joint_num,4,4)
        out_poses = self.rotation_seq2_pose_seq(out_rotation_matrices) #b*joint_num*3

        #out_rotation_matrices_fix_hip =torch.cat( (torch.autograd.Variable(torch.eye(4,4).cuda()).view(1,1,4,4).expand(batch, 1, 4,4), out_rotation_matrices[:,1:self.joint_num]), 1)
        #out_poses_fix_hip = self.rotation_seq2_pose_seq(out_rotation_matrices_fix_hip)

        #out_rotation_matrices_with_hip = torch.cat((out_rotation_matrices[:,0:1], out_rotation_matrices[:,1:self.joint_num].detach()), 1)
        #out_poses_with_hip = self.rotation_seq2_pose_seq(out_rotation_matrices_with_hip)

        return out_poses, out_rotation_matrices#out_poses_with_hip, out_rotation_matrices_with_hip , out_poses_fix_hip, out_rotation_matrices_fix_hip

    #in cuda tensor  b*joint_num*3 b*joint_num*3
    def compute_pose_loss(self, gt_pose_seq, predict_pose_seq):
        loss_function= torch.nn.MSELoss()#torch.nn.MSELoss()
        loss = loss_function(predict_pose_seq, gt_pose_seq)
        return loss

    #in cuda b*joint_num*4*4
    def compute_rotation_matrix_loss(self, gt_rotation_matrix, predict_rotation_matrix):
        loss_function = torch.nn.MSELoss()
        loss = loss_function(predict_rotation_matrix, gt_rotation_matrix)
        return loss

    #predict_rotation_matrices batch*joint_num*4*4 these are local euler rotation defined on the coordinate on joints.
    def compute_joint_twist_loss(self, predict_rotation_matrices):
        batch=predict_rotation_matrices.shape[0]
        joint_num=predict_rotation_matrices.shape[1]

        #eliminate the hip's rotation
        r_matrices = predict_rotation_matrices[:,1:joint_num].contiguous().view(-1,4,4) #(batch*(joint_num-1))*4*4
        eulers =tools.compute_euler_angles_from_rotation_matrices(r_matrices) #(batch*(joint_num-1))*3

        zeros =torch.autograd.Variable(torch.zeros(batch*(joint_num-1)).cuda())
        threshold = zeros + 100/180*np.pi

        loss_twist = torch.pow(torch.max(zeros, torch.abs(eulers[:,1])-threshold),2).mean()

        return loss_twist


from rtpmidi import RtpMidi
from pymidi import server
import os
import sys
import time
from queue import Queue
from threading import Thread
import time
import numpy as np
from numpy import interp
import socket

# DEFINE Socket
SOCKET_HOST = '192.168.2.2'  # Standard loopback interface address (localhost)
SOCKET_PORT = 58315  # Port to listen on (non-privileged ports are > 1023)

def setup():
    for a in arms:
        a.set_simulation_robot(on_off=False)
        # a.motion_enable(enable=True)
        a.clean_warn()
        a.clean_error()
        a.set_mode(0)
        a.set_state(0)
        a.set_servo_angle(angle=[0.0, 0.0, 0.0, 90, 0.0, 0.0, 0.0], wait=False, speed=20, acceleration=5,
                          is_radian=False)

class MyHandler(server.Handler):
    def on_peer_connected(self, peer):
        # Handler for peer connected
        print('Peer connected: {}'.format(peer))

    def on_peer_disconnected(self, peer):
        # Handler for peer disconnected
        print('Peer disconnected: {}'.format(peer))

    def on_midi_commands(self, peer, command_list):
        # Handler for midi msgs
        for command in command_list:
            chn = command.channel
            if chn == 0:  # Channel 1
                if command.command == 'note_on':
                    key = command.params.key.__int__()
                    q_pitch.put(key)
                    # print("singsingsing FROM THE TABLETOP")
            if chn == 1:  # Channel 2
                if command.command == 'note_on':
                    tempo = command.params.key.__int__()
                    energy = command.params.velocity
                    q_tempo.put(np.array([tempo, energy]))
                    print("grooooovy")
            # if chn == 2:  # Channel 3!!!!!
            #     if command.command == 'note_on':
            #         if command.params.key.__int__() == 60:
            #             q2.put(0)
            #             # print("onset baby!")
            #         else:
            #             print("F in chat")
            #             # print(chn)
            #             key = command.params.key
            #             velocity = command.params.velocity
            #             # print('key {} with velocity {}'.format(key, velocity))
            #             q.put(velocity)

            # playDance(dances[velocity])

def onset(in_q2):  # third q system
    armsused = [arm5, arm8, arm9, arm10, arm7]
    targets = [0, 0, 0, 0, 0]
    numbot = len(targets)
    positions = [60, 80]
    robotcounter = 0
    positioncounter = 0
    for b in range(numbot):
        armsused[b].set_mode(0)
        armsused[b].set_state(0)
        armsused[b].set_servo_angle(angle=[0.0, -4.0, 0.0, 165, 0.0, 80, 0.0], wait=False, speed=20, acceleration=5,
                                    is_radian=False)
    while True:
        in_q2.get()
        currentbot = robotcounter % numbot
        currentpos = positions[positioncounter % 2]
        targets[currentbot] = currentpos

        if robotcounter % numbot == (numbot - 1):
            positioncounter += 1
        # print("current bot is:", currentbot, "current pose is:", currentpos)
        armsused[currentbot].set_servo_angle(angle=[0.0, -4.0, 0.0, 165, 0.0, currentpos, 0.0], wait=False,
                                             speed=130, acceleration=80, is_radian=False)
        robotcounter += 1

def tempo(in_q3):
    tempoArms = [arm1, arm4, arm5, arm6, arm7]
    ups = [arm1, arm4, arm6]
    downs = [arm5, arm7]
    for a in tempoArms:
        a.set_mode(0)
        a.set_state(0)
        # print("moving")
        a.set_servo_angle(angle=[0.0, -60.0, 0.0, 60, 0.0, 30, 0.0], wait=False, speed=40, acceleration=50,
                          is_radian=False)
        a.set_position(*[121, -1, 505, -2, -86, -170], wait=True)

    counter = 0
    while True:
        goal = in_q3.get()
        height = goal[1]
        min_h = 10
        max_h = 40
        # height = ((height - 60) * (max_h - min_h) / 10) + min_h
        if height > max_h:
            height = max_h
        elif height < min_h:
            height = min_h
        direction = (-1) ** counter
        j2 = -75 + height
        j6 = 90 - abs(j2)
        j4 = 90 + j2 + j6
        speed = j4 / 0.6
        if direction > 0:
            for a in ups:
                a.set_servo_angle(angle=[0.0, j2, 0.0, j4, 0.0, j6, 0.0], wait=False, speed=speed,
                                  acceleration=50, is_radian=False)
            for a in downs:
                a.set_servo_angle(angle=[0.0, -60, 0.0, 60, 0.0, 30, 0.0], wait=False, speed=speed,
                                  acceleration=50, is_radian=False)
        else:
            for a in ups:
                a.set_servo_angle(angle=[0.0, -60, 0.0, 60, 0.0, 30, 0.0], wait=False, speed=speed,
                                  acceleration=50, is_radian=False)
            for a in downs:
                a.set_servo_angle(angle=[0.0, j2, 0.0, j4, 0.0, j6, 0.0], wait=False, speed=speed,
                                  acceleration=50, is_radian=False)
        counter += 1

def pitchContour(in_q4):
    pitcharm = [arm6]
    for a in pitcharm:
        a.set_servo_angle(angle=[0.0, -50, 0.0, 40, 0.0, 30, 0.0], wait=True, speed=20,
                          acceleration=10, is_radian=False)
        a.set_position(*[200, 0, 620, 180, -89, 0], wait=False)
    # 55 - 80 range
    # 550-900
    max_h = 900
    min_h = 500
    # print("Start the loop")
    while True:
        pitch = in_q4.get()
        height = interp(pitch, [59, 83], [500, 900])
        # height = ((pitch - 48) * (max_h - min_h) / 12) + min_h
        if height > 900:
            height = 900
        if height < 500:
            height = 500

        for a in pitcharm:
            print(pitch)
            a.set_position(*[200, 0, height, 180, -89, 0], speed=8400, wait=False)

def playRobot(que, arm):
    IP = [0, 0, 0, 90, 0, 0, 0]
    tf = 50

    # t0 = 0
    t = [0 for i in range(0, 7)]
    q_i = [0 for i in range(0, 7)]
    q_dot_i = [0 for i in range(0, 7)]
    q_dot_f = [0 for i in range(0, 7)]
    q_dotdot_i = [0 for i in range(0, 7)]
    q_dotdot_f = [0 for i in range(0, 7)]
    t_array = np.arange(0, tf, 0.006)
    p = [0, 0, 0, 90, 0, 0, 0]
    v = [0 for i in range(0, 7)]
    a = [0 for i in range(0, 7)]

    # j_angles = [0, 0, 0, 90, 0, 0, 0]

    while True:
        q = que.get()
        # print(q)
        # print("\nDequeued")

        goal = q
        q_i = p
        # q_i = j_angles
        q_dot_i = [0, 0, 0, 0, 0, 0, 0]
        q_dotdot_i = [0, 0, 0, 0, 0, 0, 0]
        q_f = goal
        j = 0

        while j < len(t_array):
            start_time = time.time()

            if abs(p[0] - q_f[0]) < 1.0 and abs(p[1] - q_f[1]) < 1.0 and abs(p[2] - q_f[2]) < 1.0 and abs(
                    p[3] - q_f[3]) < 1.0 and abs(p[4] - q_f[4]) < 1.0 and abs(p[5] - q_f[5]) < 1.0 and abs(
                p[6] - q_f[6]) < 1.0:
                break

            # if que.empty() == False:
            #     q = que.get
            #     goal = q
            #     q_i = p
            #     q_dot_i = v
            #     q_dotdot_i = [0 for i in range(0, 7)]
            #     q_f = goal
            #     j = 0
            #     # IF YOU WANT TO ADD SPEED CHANGES THEN SWAP THE ABOVE LINES WITH THE BELOW LINES
            #     # # q should input an array of [*absolute* position of joint, time(in seconds) to reach there]
            #     # q_f = goal[0]
            #     # tf = goal[1]
            #     # t_array = np.arange(0, tf, 0.006)
            #     print("switch")
            if j == len(t_array):
                t = tf
            else:
                t = t_array[j]

            a0 = q_i
            a1 = q_dot_i
            a2 = []
            a3 = []
            a4 = []
            a5 = []

            for i in range(0, 7):
                a2.append(0.5 * q_dotdot_i[i])
                a3.append(1.0 / (2.0 * tf ** 3.0) * (
                        20.0 * (q_f[i] - q_i[i]) - (8.0 * q_dot_f[i] + 12.0 * q_dot_i[i]) * tf - (
                        3.0 * q_dotdot_f[i] - q_dotdot_i[i]) * tf ** 2.0))
                a4.append(1.0 / (2.0 * tf ** 4.0) * (
                        30.0 * (q_i[i] - q_f[i]) + (14.0 * q_dot_f[i] + 16.0 * q_dot_i[i]) * tf + (
                        3.0 * q_dotdot_f[i] - 2.0 * q_dotdot_i[i]) * tf ** 2.0))
                a5.append(1.0 / (2.0 * tf ** 5.0) * (
                        12.0 * (q_f[i] - q_i[i]) - (6.0 * q_dot_f[i] + 6.0 * q_dot_i[i]) * tf - (
                        q_dotdot_f[i] - q_dotdot_i[i]) * tf ** 2.0))

                p[i] = (a0[i] + a1[i] * t + a2[i] * t ** 2 + a3[i] * t ** 3 + a4[i] * t ** 4 + a5[i] * t ** 5)
                v[i] = (a1[i] + 2 * a2[i] * t + 3 * a3[i] * t ** 2 + 4 * a4[i] * t ** 3 + 5 * a5[i] * t ** 4)
                a[i] = (2 * a2[i] + 6 * a3[i] * t + 12 * a4[i] * t ** 2 + 20 * a5[i] * t ** 3)

            # j_angles = p
            arm.set_servo_angle_j(angles=p, is_radian=False)
            # print(f"{p} {arm}")

            tts = time.time() - start_time
            sleep = 0.006 - tts

            if tts > 0.006:
                sleep = 0

            time.sleep(sleep)
            j += 1
            # if t == 1:
            # print(t, p, v, a)

        # print(f"\nFinished {arm}")

def changeDir(q, pos):
    # while True:
    # pos = list(map(int, input("\nEnter the positions for joints 1-7 : ").strip().split()))[:7]
    # time.sleep(5)
    # pos = [0, 0, 0, 90, 0, 90, 0]
    q.put(pos)

if __name__ == "__main__":
    # INITIALIZE Socket
    print("Sockets Init\n")
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((SOCKET_HOST, SOCKET_PORT))
    s.listen()
    s.settimeout(None)
    conn, addr = s.accept()
    print("Socket done\n")
    s.settimeout(None)

    # INITIALIZE Arms
    ROBOT = "xArms"
    PORT = 5004

    sys.path.append(os.path.join(os.path.dirname(__file__), '../../..'))
    from xarm.wrapper import XArmAPI

    arm1 = XArmAPI('192.168.1.208')
    arm2 = XArmAPI('192.168.1.244')
    arm3 = XArmAPI('192.168.1.203')
    arm4 = XArmAPI('192.168.1.236')
    arm5 = XArmAPI('192.168.1.226')
    arm6 = XArmAPI('192.168.1.242')
    arm7 = XArmAPI('192.168.1.215')
    arm8 = XArmAPI('192.168.1.234')
    # arm9 = XArmAPI('192.168.1.237')
    arm10 = XArmAPI('192.168.1.204')

    arms = [arm1, arm2, arm3, arm4, arm5, arm6, arm7, arm8, arm10]

    totalArms = len(arms)

    setup()
    repeat = input("do we need to repeat? [y/n]")
    if repeat == 'y':
        setup()

    set_arms = [arm2, arm3, arm8, arm10]

    for a in set_arms:
        a.set_mode(1)
        a.set_state(0)

    ############################################# MIDI Keyboard #############################################

    # Direction queues
    arm2_q = Queue()
    arm3_q = Queue()
    arm8_q = Queue()
    arm10_q = Queue()
    que_pos = [arm2_q, arm3_q, arm8_q, arm10_q]

    # Live Traj Threads for Arms
    t_midi_a1 = Thread(target=playRobot, args=(arm2_q, arm2))
    t_midi_a2 = Thread(target=playRobot, args=(arm3_q, arm3))
    t_midi_a3 = Thread(target=playRobot, args=(arm8_q, arm8))
    t_midi_a4 = Thread(target=playRobot, args=(arm10_q, arm10))

    # Live Traj Thread
    # t_liveTraj = Thread(target=changeDir, args=(que_pos,))

    # Start Threads
    # t_liveTraj.start()
    t_midi_a1.start()
    t_midi_a2.start()
    t_midi_a3.start()
    t_midi_a4.start()

    ############################################# MIR Band ###################################################
    # Create the shared queue
    # q_onset = Queue()
    q_tempo = Queue()
    q_pitch = Queue()

    # Create Threads
    rtp_midi = RtpMidi(ROBOT, MyHandler(), PORT)
    rt = Thread(target=rtp_midi.run, args=())

    # t_onset = Thread(target=onset, args=(q_onset,))
    t_tempo = Thread(target=tempo, args=(q_tempo,))
    t_pitch = Thread(target=pitchContour, args=(q_pitch,))

    # Start Threads
    # t_onset.start()
    t_tempo.start()
    t_pitch.start()
    rt.start()

    ############################################# Start MIDI Performance ########################################

    chord_pos = {
        "E-M": {
            "arm2": [0, 0, 135, 130, 0, 50, 0],
            "arm3": [0, 0, -103, 130, 0, 50, 0],
            "arm8": [0, 0, 60, 130, 0, 50, 0],
            "arm10": [0, 0, -8.5, 130, 0, 50, 0]
        },
        "C#-m": {
            "arm2": [-36, -40, 180, 150, 0, 20, 0],
            "arm3": [42, -40, 180, 150, 0, 20, 0],
            "arm8": [-110, -40, 180, 150, 0, 20, 0],
            "arm10": [158, -40, 180, 150, 0, 20, 0]
        },
        "A-M": {
            "arm2": [-36, 40, 180, 110, 0, 80, 0],
            "arm3": [42, 40, 180, 110, 0, 80, 0],
            "arm8": [-110, 40, 180, 110, 0, 80, 0],
            "arm10": [158, 40, 180, 110, 0, 80, 0]
        },
        "B-M": {
            "arm2": [-180, 60, 180, 50, 0, 28, 0],
            "arm3": [-180, 60, 180, 50, 0, 28, 0],
            "arm8": [-8, 60, 180, 50, 0, 28, 0],
            "arm10": [-8, 60, 180, 50, 0, 28, 0]
        }
    }

    try:
        with conn:
            s.settimeout(None)
            print('Connected by', addr)
            while True:
                chord = conn.recv(1024).decode()
                print(chord)
                if chord in chord_pos.keys():
                    changeDir(arm2_q, chord_pos.get(chord).get("arm2"))
                    changeDir(arm3_q, chord_pos.get(chord).get("arm3"))
                    changeDir(arm8_q, chord_pos.get(chord).get("arm8"))
                    changeDir(arm10_q, chord_pos.get(chord).get("arm10"))

                # if chord == "E-M":
                #     print("E-M\n")
                #     changeDir(arm2_q, [0, 0, 135, 130, 0, 50, 0])
                # if chord == "C#-m":
                #     print("C#-m\n")
                #     # changeDir(que_pos, [105, 43, -61, 125, -76, 70, 25])
                #     changeDir(arm2_q,[-36, -40, 180, 150, 0, 20, 0])
                # if chord == "A-M":
                #     print("A-M\n")
                #     # changeDir(que_pos, [-35, -115, -175, 190, -7.5, -12, 25])
                #     changeDir(arm2_q, [-36, 40, 180, 110, 0, 80, 0])
                # if chord == "B-M":
                #     print("B-M\n")
                #     # changeDir(que_pos, [-60, 75, 255, 151, -17, 30, 25])
                #     changeDir(arm2_q, [-180, 60, 180, 50, 0, 20, 0])

    except socket.error as socketerror:
        s.close()  # Remember to close sockets after use!
        print("Error: ", socketerror)

    except KeyboardInterrupt:
        s.close()  # Remember to close sockets after use!
        print('Keyboard interrupt...')

    finally:
        s.close()  # Remember to close sockets after use!
        print("Exiting...")


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

# IF // SI
# El código se ejecuta en caso de que
# la condición se culpa de manera adecuada.

# ELSE // DE LO CONTRARIO
# Se ejecuta otro código en caso que no se repita.

edad = int(input("Ingrese su edad: "))
edad_ecu = int(18 - edad)

if edad >= 18:
    print("Eres mayor de edad")

elif edad >= 16:
    print("Tienes", edad, "años, ya casi alcanza la edad necesaria, le faltan", edad_ecu, " años para la mayoría de edad")

else:
    print("Tienes", edad, "años, eres un bebé, aún te faltan", edad_ecu ,"años para la mayoría de edad")


import math
import numpy as np
import xyz_py as xyzp
from numpy import sqrt
from numpy import around
from algorithm.nelder_mead import minimize
from util.water_info import calculate_molecule_properties
import random as rand
import vg
import os
# from nelder_mead import minimize

np.set_printoptions(formatter={'float': lambda x: "{0:0.5f}".format(x)})

'''
Summary: This script performs a geometry optimization for water dimers using the
Ferguson Flexible Water Model. It uses the Nelder-Mead optimization algorithm
to find the lowest energy geometry based on the potential energy function
implemented in the Ferguson() function. The input is an XYZ file with the
initial geometry of the water dimer, and the user can also choose to add
perturbation to the initial coordinates for each iteration. The output is
the optimized geometry in an XYZ file and the lowest energy found in a text file.
'''

'''
The parameters are acquired from the following paper:
Parameterization and evaluation of a flexible water model
https://doi.org/10.1002/jcc.540160413
'''

# Global variables (Ferguson Flexible Water Model)
K_L = 547.5 # kcal/(mol Å^-2) - spring constant for bond lengths
L = 1.0 # Å / equlibrium bond length between O and H
K_CUB = -1.65 # Å^-1 - cubic force constant for bond lengths
K_THETA = 49.9 # kcal/(mol rad^-1) - force constant for bond angles
THETA = 109.5 # deg /equlibrium angle between O and H
A = 650000 # kcal mol^-1 Å^12 - Lennard-Jones potential constant
B = 625.47 # kcal mol^-1 Å^6 - Lennard-Jones potential constant
Q_H = 0.413 # kcal^0.5 Å^0.5 mol^-0.5 - partial charge on hydrogen atoms
Q_O = -0.826 # kcal^0.5 Å^0.5 mol^-0.5 - partial charge on oxygen atoms
K_VALUE = 332.0637133 # Coulomb's constant in kcal/mol-Å-e^2 units

# Neader Mead Parameters
ITERATION = 10
STEP_SIZE = 0.01
MAX_ITERATION = 10000

# USER INPUT (1/2):  Get file name from user input
while True:
    filename = input("Q1/2. Enter the file name Ex) ./xyz/water/tip4p_wales_n_2.xyz: ").strip()
    if not os.path.exists(filename):
        print(f"Error: File {filename} does not exist.")
    elif not filename.endswith('.xyz'):
        print(f"Error: File {filename} is not a valid xyz file.")
    else:
        break

# USER INPUT (2/2): Determine whether to add randomness to the initial posiiton of the molecules
isPerturbated = ""
while isPerturbated not in ["y", "n"]:
    isPerturbated = input("Q2/2. Would you like to add perturbation to the initial coordinates for every iteration? (y/n) ").strip().lower()

# Ferguson potential function
def Ferguson(params):

    coordinates = params.reshape(-1,3)
    O1 = coordinates[0]
    H11 = coordinates[1]
    H21 = coordinates[2]
    O2 = coordinates[3]
    H12 = coordinates[4]
    H22 = coordinates[5]

    # Hij where
    # i refers to the ith number of hydrogens
    # j refers to the jth number of oxygen

    # Calculate bond lengths
    r11 = np.sqrt(np.sum((O1-H11)**2, axis=0))
    r21 = np.sqrt(np.sum((O1-H21)**2, axis=0))
    r12 = np.sqrt(np.sum((O2-H12)**2, axis=0))
    r22 = np.sqrt(np.sum((O2-H22)**2, axis=0))

    # Calculate angles
    OH11 = O1 - H11
    OH21 = O1 - H21
    OH12 = O2 - H12
    OH22 = O2 - H22
    angle1 = vg.angle(OH11, OH21)
    angle2 = vg.angle(OH12, OH22)

    angle_rad1 = angle1 * (math.pi/180)
    angle_rad2 = angle2 * (math.pi/180)

    # Calculate bonds term
    first_term = (r11-L)**2 + K_CUB*(r11-L)**3
    second_term = (r21-L)**2 + K_CUB*(r21-L)**3
    third_term = (r12-L)**2 + K_CUB*(r12-L)**3
    fourth_term = (r22-L)**2 + K_CUB*(r22-L)**3
    bonds_term = K_L*(first_term + second_term + third_term + fourth_term)

    # Calculate angles term
    angles_term = K_THETA * ((angle_rad1 - THETA * math.pi/180)**2 + (angle_rad2 - THETA * math.pi/180)**2)

    # Calculate oxygen repulsion term
    rO = np.sqrt(np.sum((O1-O2)**2, axis=0))
    LJ_term = A/(rO**12) - B/(rO**6)

    # Calculate Coulombic term - OH interactions
    rO1H12 = np.sqrt(np.sum((O1-H12)**2, axis=0))
    rO1H22 = np.sqrt(np.sum((O1-H22)**2, axis=0))
    rO2H11 = np.sqrt(np.sum((O2-H11)**2, axis=0))
    rO2H21 = np.sqrt(np.sum((O2-H21)**2, axis=0))

    OH_interations = (Q_H*Q_O) * (1/rO1H12 + 1/rO1H22 + 1/rO2H11 + 1/rO2H21)

    # Calculate Coulombic term - HH interactionsb
    rH11H12 = np.sqrt(np.sum((H11-H12)**2, axis=0))
    rH21H12 = np.sqrt(np.sum((H21-H12)**2, axis=0))
    rH11H22 = np.sqrt(np.sum((H11-H22)**2, axis=0))
    rH21H22 = np.sqrt(np.sum((H21-H22)**2, axis=0))

    HH_interations = (Q_H*Q_H) * (1/rH11H12 + 1/rH21H12 + 1/rH11H22 + 1/rH21H22)
    OO_interaction = (Q_O*Q_O) * (1/rO)

    U = bonds_term + angles_term + LJ_term + K_VALUE * (OH_interations + HH_interations + OO_interaction)

    return U

# Import coordinates from XYZ file
atom_labels, cooridnates = xyzp.load_xyz(filename)
initial_coordinates = np.array(cooridnates).flatten()
min_energy = 0
min_coordinate = []

# Perform Nelder-Mead optimization
for i in range(ITERATION):
    if isPerturbated == "y":
        random_initial_points = np.random.random_sample(size = 18) * 0.1 - 0.05
        result = minimize(Ferguson, initial_coordinates + random_initial_points, STEP_SIZE, MAX_ITERATION)
    else:
        result = minimize(Ferguson, initial_coordinates, STEP_SIZE, MAX_ITERATION)
    current_coordinates = result[0].reshape(-1, 3)
    current_energy = result[1]

    print(f"\nIteration {i+1}: energy converged: {current_energy} kcal/mol")
    calculate_molecule_properties(current_coordinates)

    if current_energy < min_energy:
        min_energy = current_energy
        min_coordinates = current_coordinates

print("\nThe lowest energy found was", min_energy, "kcal/mol")
print(min_coordinates, "\n")

# Save optimized coordinates and energy
xyzp.save_xyz(os.path.splitext(filename)[0]+'_opt.xyz', atom_labels, min_coordinates)

with open(os.path.splitext(filename)[0]+'_opt.txt', "w") as f:
    f.write(str(min_energy))

f.close()


from flask import jsonify, request
from models.user_model import User
from Schemas.user_schema import UserSchema
from models.user_model import db

def create_user():
    user_schema = UserSchema()
    user_data = user_schema.load(request.json)
    user = User(**user_data)
    db.session.add(user)  # agrega el nuevo usuario a la sesión
    db.session.commit()  # guarda los cambios en la base de datos
    return user_schema.dump(user), 201

def get_users():
    users = User.query.all()
    user_schema = UserSchema(many=True)
    return user_schema.dump(users), 200

def get_user(user_id):
    user = User.query.get_or_404(user_id)
    user_schema = UserSchema()
    return user_schema.dump(user), 200

def update_user(user_id):
    user = User.query.get_or_404(user_id)
    user_schema = UserSchema()
    user_data = user_schema.load(request.json, partial=True) # Carga los datos del request
    for key, value in user_data.items():
        setattr(user, key, value) # Actualiza el valor del atributo correspondiente en la instancia de User
    db.session.commit() # Guarda los cambios en la base de datos
    return user_schema.dump(user), 200

def delete_user(user_id):
    user = User.query.get_or_404(user_id)
    db.session.delete(user) # Elimina la instancia de User de la sesión de base de datos
    db.session.commit() # Guarda los cambios en la base de datos
    return '', 204


with open('dataset.txt', 'r') as f:
    Text = f.readline()
    vals = f.readline().split()

Text = Text[:-1]

k = int(vals[0])
d = int(vals[1])

depth = k
FrequencyArray = []

kmers = ['' for i in range(4**k)]

def getLetter(num):
    return {
        0: 'A',
        1: 'C',
        2: 'G',
        3: 'T'
        }.get(num)

def getKmers(k, depth):
    if depth == 0:
        return
    iters = 4**(k-depth)
    count = 0
    for j in range(0, iters):
        for i in range(0, (4**depth)/4):
            kmers[count] += 'A'
            count += 1
        for i in range((4**depth)/4, 2*(4**depth)/4):
            kmers[count] += 'C'
            count += 1
        for i in range(2*(4**depth)/4, 3*(4**depth)/4):
            kmers[count] += 'G'
            count += 1
        for i in range(3*(4**depth)/4, 4**depth):
            kmers[count] += 'T'
            count += 1
    getKmers(k, depth-1)

def SymbolToNumber(symbol):
    if symbol == 'A':
        return 0
    if symbol == 'C':
        return 1
    if symbol == 'G':
        return 2
    if symbol == 'T':
        return 3

def PatternToNumber(pattern):
    if pattern == '':
        return 0
    symbol = pattern[-1]
    pattern = pattern[:-1]

    return 4*PatternToNumber(pattern) + SymbolToNumber(symbol)

def NumberToPattern(index):
    return kmers[index]

def HammingDistance(string1, string2):
    count = 0
    for i in range(0, len(string1)):
        if string1[i] != string2[i]:
            count += 1
    return count

def Suffix(Pattern):
    return Pattern[1:]

def Neighbors(Pattern, d):
    results = []
    if d == 0:
        return Pattern
    elif len(Pattern) == 1:
        results.append('A')
        results.append('C')
        results.append('G')
        results.append('T')
        return results
    Neighborhood = []
    SuffixNeighbors = Neighbors(Suffix(Pattern), d)
    for Text in SuffixNeighbors:
        if HammingDistance(Suffix(Pattern), Text) < d:
            Neighborhood.append('A' + Text)
            Neighborhood.append('C' + Text)
            Neighborhood.append('G' + Text)
            Neighborhood.append('T' + Text)
        else:
            Neighborhood.append(Pattern[0] + Text)
    return Neighborhood

def ComputeFrequencies(Text, k):
    for i in range(0, 4**k):
        FrequencyArray.append(0)

    for i in range(0, len(Text) - k):
        pattern = Text[i: i+k]
        nearbies = Neighbors(pattern, d)
        for kmer in nearbies:
            if HammingDistance(kmer, pattern) <= d:
                FrequencyArray[PatternToNumber(kmer)] += 1
        nearbies = Neighbors(ReverseComplement(pattern), d)
        for kmer in nearbies:
            if HammingDistance(kmer, ReverseComplement(pattern)) <= d:
                FrequencyArray[PatternToNumber(kmer)] += 1

    count = 0
    for item in FrequencyArray:
        if NumberToPattern(count) == ReverseComplement(NumberToPattern(count)):
            item = item/2
        count += 1

def MostFrequent():
    most = max(FrequencyArray)
    count = 0
    indeces = []
    for item in FrequencyArray:
        if item == most:
            indeces.append(count)
        count += 1
    return indeces

def ReverseComplement(String):
    Complement = ""
    for x in String:
        if x == 'A':
            Complement += 'T'
        elif x == 'C':
            Complement += 'G'
        elif x == 'G':
            Complement += 'C'
        elif x == 'T':
            Complement += 'A'

    return Complement[::-1]

if k <= 12:
    filename = str(k) + '.txt'
    with open(filename, 'r') as f:
        kmers = f.read().splitlines()
else:
    getKmers(k, k)

ComputeFrequencies(Text, k)
indeces = MostFrequent()
results = ""

for index in indeces:
    results += NumberToPattern(index) + " "

print(results)


import Producto

class DetallePedido():

    def __init__(self,cantidadProducto:int,valorUnitario:float,producto:Producto):
        self.CantidadProducto = cantidadProducto
        self.ValorUnitario = valorUnitario
        self.Producto=producto

    def CalcularPrecio(self):
        print("Precio")
        return

list = []

list.append(DetallePedido('nombreProducto', str.Hamburguesa))
list.append(DetallePedido('precio', 8000))

for obj in list:
    print( obj.DetallePedido, sep = ' ')

if __name__=='__main__':
    DetallePedido1 = DetallePedido(3,15000,'Hamburguesa')
    print(DetallePedido1)


from scipy.stats import norm

Pair = list[float]
Point = list[list[float]]

def f(y: float, p: list[float], point: Point) -> float:
    f = 0
    for i in range(len(p)):
        f += p[i] * norm.pdf(y, point[i][0], point[i][1])
    return f

def w(y: float, f: float, p: float, pair: Pair) -> float:
    return p * norm.pdf(y, pair[0], pair[1]) / f

def gaussian_mixture_em_iter(p: list[float], point: Point, Y: list[float]) -> tuple[list[float], Point]:
    n = len(Y)
    m = len(p)
    new_p = [0] * m
    new_point = [[0, 0]] * m
    for i in range(len(p)):
        new_p[i], new_point[i][0], new_point[i][1], W = 0, 0, 0, 0
        for y in Y:
            fy = f(y, p, point)
            wy = w(y, fy, p[i], point[i])
            new_p[i] += p[i] * norm.pdf(y, point[i][0], point[i][1]) / fy
            new_point[i][0] += y * wy
            new_point[i][1] += ((y - point[i][0]) ** 2) * wy
            W += wy
        new_p[i] = new_p[i] / n
        new_point[i] = [new_point[i][0] / W, (new_point[i][1] / W) ** 0.5]
    return new_p, new_point

def gaussian_mixture_em(p: list[float], point: Point, Y: list[float], iters: int) -> tuple[list[float], Point]:
    for i in range(iters):
        p, point = gaussian_mixture_em_iter(p, point, Y)
        if i in [3, 15, 63]:
            print("iter {}:".format(i), p, point)

    return p, point


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

# In[80]:

import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')

# In[81]:

full_data = pd.read_csv(r'\Users\Pedro\Documents\high_diamond_ranked_10min.csv')

# In[82]:

# full_data.columns

# In[83]:

X = np.array(full_data.drop(['gameId', 'blueWins'],1).astype(float))
Y = np.array(full_data['blueWins'])

# In[84]:

kmeans = KMeans(n_clusters=2) # 2 clusters: blueWins = 1 v blueWins = 0
kmeans.fit(X)

# In[85]:

# model quality
correct = 0
for i in range(len(X)):
    predict = np.array(X[i].astype(float))
    predict = predict.reshape(-1, len(predict))
    prediction = kmeans.predict(predict)
    if prediction[0] == Y[i]:
        correct += 1

print(correct/len(X))

# In[86]:

# only 0.27 correct predictions
# it's only natural because we used the data as it is
# We have to two options

# In[87]:

# 1 - play around with the parameters, in our kmeans method, such as max_iter and n_jobs

# In[88]:

# we will try one kmeans with max_iter = 600
kmeans600 = KMeans(n_clusters=2, max_iter=600)
kmeans600.fit(X)

# In[89]:

# model quality
correct_600 = 0
for i in range(len(X)):
    predict_600 = np.array(X[i].astype(float))
    predict_600 = predict_600.reshape(-1, len(predict_600))
    prediction_600 = kmeans600.predict(predict_600)
    if prediction_600[0] == Y[i]:
        correct_600 += 1

print(correct_600/len(X))

# In[90]:

# we can see that for 600 iterations of Kmeans, we have a massive improvement from 0.27 up to 0.72
# but there will be occasions where even with parameter tweaking, the quality of model won't improve at least significantly
# in such case we need
# 2 -  rescale our data

# In[91]:

scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)

# In[92]:

kmeans.fit(X_scaled)

# In[93]:

correct_scaled = 0
for i in range(len(X)):
    predict_scaled = np.array(X[i].astype(float))
    predict_scaled = predict_scaled.reshape(-1, len(predict_scaled))
    prediction_scaled = kmeans.predict(predict_scaled)
    if prediction_scaled[0] == Y[i]:
        correct_scaled += 1

print(correct_scaled/len(X))

# In[ ]:

# same a similar result was obtained as in the first try with this method
# we can use the 600 interations model and check it improves

# In[94]:

kmeans600.fit(X_scaled)

# In[96]:

correct_scaled600 = 0
for i in range(len(X)):
    predict_scaled600 = np.array(X[i].astype(float))
    predict_scaled600 = predict_scaled600.reshape(-1, len(predict_scaled600))
    prediction_scaled600 = kmeans600.predict(predict_scaled600)
    if prediction_scaled600[0] == Y[i]:
        correct_scaled600 += 1

print(correct_scaled600/len(X))

# In[64]:

# again similar result as before
# in order to try and make the model betterwe rescaled the date, but it seems that for this dataset rescaling doesnt make
# that much of a difference and tweaking max iteraction provides a better result in term of the quality of the clusters

# In[ ]:


# https://www.codewars.com/kata/51b62bf6a9c58071c600001b/train/python

# Create a function taking a positive integer as its parameter and
#  returning a string containing the Roman Numeral representation of
#   that integer.

# Modern Roman numerals are written by expressing each digit separately
#  starting with the left most digit and skipping any digit with a
#   value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM,
#    90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII;
#     or MMVIII. 1666 uses each Roman symbol in descending order:
#      MDCLXVI.

# Example:

# solution(1000) # should return 'M'
# Help:

# Symbol    Value
# I          1
# V          5
# X          10
# L          50
# C          100
# D          500
# M          1,000
# Remember that there can't be more than 3 identical symbols in a row.

# More about roman numerals - http://en.wikipedia.org/wiki/Roman_numerals

import math

def roman_encoder(n):
    romanArabicDict = {
        "M": 1000,
        "CM": 900,
        "D": 500,
        "CD": 400,
        "C": 100,
        "XC": 90,
        "L": 50,
        "XL": 40,
        "X": 10,
        "IX": 9,
        "V": 5,
        "IV": 4,
        "I": 1,
    }
    result = ""
    for roman in romanArabicDict:
        arabic = romanArabicDict[roman]
        # Divide n by the arabic number, is this > 1? multiply this with roman number
        result += roman * math.floor(n / arabic)
        # Calculate the leftover of division and assign to n
        n = n % arabic
    return result


"""
Serializers for bootcamps
"""
from rest_framework import serializers

from cms.serializers import BootcampRunPageSerializer
from klasses.models import Bootcamp, BootcampRun, Installment, BootcampRunEnrollment

class InstallmentSerializer(serializers.ModelSerializer):
    """Serializer for Installment model"""

    amount = serializers.DecimalField(decimal_places=2, max_digits=20)

    class Meta:
        model = Installment
        fields = ("amount", "deadline")

class BootcampSerializer(serializers.ModelSerializer):
    """Serializer for Bootcamp model"""

    class Meta:
        model = Bootcamp
        fields = ["id", "title"]

class BootcampRunSerializer(serializers.ModelSerializer):
    """Serializer for BootcampRun model"""

    bootcamp = BootcampSerializer()
    installments = InstallmentSerializer(many=True, source="installment_set")

    def to_representation(self, instance):
        page_fields = {}
        if self.context.get("include_page") is True:
            page_fields = {
                "page": (
                    BootcampRunPageSerializer(instance=instance.bootcamprunpage).data
                    if hasattr(instance, "bootcamprunpage")
                    else {}
                )
            }
        return {**super().to_representation(instance), **page_fields}

    class Meta:
        model = BootcampRun
        fields = [
            "id",
            "display_title",
            "bootcamp",
            "title",
            "run_key",
            "novoed_course_stub",
            "start_date",
            "end_date",
            "early_bird_deadline",
            "is_payable",
            "installments",
            "bootcamp_run_id",
            "allows_skipped_steps",
        ]

class BootcampRunEnrollmentSerializer(serializers.ModelSerializer):
    """Serializer for BootcampRunEnrollment model"""

    class Meta:
        model = BootcampRunEnrollment
        fields = ["id", "user_id", "bootcamp_run_id", "novoed_sync_date"]


# Problem Description: https://practice.geeksforgeeks.org/problems/relative-sorting/0

t = int(input())

for _ in range(t):
    n, m = [int(x) for x in input().split()]
    a = [int(x) for x in input().split()]
    b = [int(x) for x in input().split()]
    d = {}
    output = []

    for i in range(n):
        if(a[i] in d):
            d[a[i]] += 1
        else:
            d[a[i]] = 1

    for i in range(m):
        if(b[i] in d):
            for j in range(d[b[i]]):
                output.append(b[i])
            del d[b[i]]

    temp = []
    for k, v in d.items():
        for i in range(v):
            temp.append(k)
    temp.sort()
    output += temp

    print(' '.join([str(x) for x in output]))


import gymnasium as gym
import numpy as np
from Data import Data
from Memory import ReplayBuffer
from gymnasium import spaces

class TradeEnv(gym.Env):
    def __init__(self, trading_cost, timeframe="1M", ticker="Oil", train=True):
        self.data_source = Data(timeframe=timeframe, ticker=ticker, train=train)
        self.trading_cost = trading_cost
        self.action_space = spaces.Discrete(2)

    def seed(self, seed=42):
        self.np_random, seed = seeding.np_random(seed)
        return [seed]

    def step(self, action, observation, lookback):
        assert self.action_space.contains(
            action
        ), f"{action} {type(action)} is an invalid action"

        if action == 0:
            action = -1

        pos = observation.Close

        observation_, done = self.data_source.take_step(lookback)

        reward = action * (observation_.Close - pos)

        return observation_, reward, done, None

    def reset(self, lookback):
        self.data_source.reset()

        return self.data_source.take_step(lookback)[0]


from math import *
from typing import Tuple, List
import numpy as np

def numpy_map(f, v) -> np.array:
    return np.array(list(map(f, v)))

def rotation_matrix(rotation: np.array) -> np.array:
    a, b, c = rotation
    return np.linalg.inv(np.array([
        [cos(a) * cos(c) - sin(a) * cos(b) * sin(c), -cos(a) * sin(c) - sin(a) * cos(b) * cos(c), sin(a) * sin(b)],
        [sin(a) * cos(c) + cos(a) * cos(b) * sin(c), -sin(a) * sin(c) + cos(a) * cos(b) * cos(c), -cos(a) * sin(b)],
        [sin(b) * sin(c), sin(b) * cos(c), cos(b)]
    ]))

# https://www.geeksforgeeks.org/bresenhams-algorithm-for-3-d-line-drawing
def bresenham3_line(begin: Tuple[int, ...], end: Tuple[int, ...]) -> List[Tuple[int, ...]]:
    x1, y1, z1 = begin
    x2, y2, z2 = end
    results = [(x1, y1, z1)]
    dx, dy, dz = abs(x2 - x1), abs(y2 - y1), abs(z2 - z1)
    xs, ys, zs = map(lambda v: 1 if v[1] > v[0] else -1, zip(begin, end))

    # Driving axis is X-axis
    if dx >= dy and dx >= dz:
        p1 = 2 * dy - dx
        p2 = 2 * dz - dx
        while x1 != x2:
            x1 += xs
            if p1 >= 0:
                y1 += ys
                p1 -= 2 * dx
            if p2 >= 0:
                z1 += zs
                p2 -= 2 * dx
            p1 += 2 * dy
            p2 += 2 * dz
            results.append((x1, y1, z1))

    # Driving axis is Y-axis
    elif dy >= dx and dy >= dz:
        p1 = 2 * dx - dy
        p2 = 2 * dz - dy
        while y1 != y2:
            y1 += ys
            if p1 >= 0:
                x1 += xs
                p1 -= 2 * dy
            if p2 >= 0:
                z1 += zs
                p2 -= 2 * dy
            p1 += 2 * dx
            p2 += 2 * dz
            results.append((x1, y1, z1))

    # Driving axis is Z-axis
    else:
        p1 = 2 * dy - dz
        p2 = 2 * dx - dz
        while z1 != z2:
            z1 += zs
            if p1 >= 0:
                y1 += ys
                p1 -= 2 * dz
            if p2 >= 0:
                x1 += xs
                p2 -= 2 * dz
            p1 += 2 * dy
            p2 += 2 * dx
            results.append((x1, y1, z1))
    return results


import ast

from p2l_internals import *
from p2l_supported import *
from p2l_labels import LABEL_PROVIDER

class P2LVisitor(ast.NodeVisitor):
    def __init__(self, compiler):
        self.compiler = compiler

        # [very hacky]
        # we use this flag to distinguish between cases
        # 1) compiling main source code
        # 2) compiling global constants from "stdlib"
        self.process_consts = False

    def visit(self, node):
        # print
        # print 'Visiting', node
        byte_code = ast.NodeVisitor.visit(self, node)
        # print
        # print 'Visited', node
        # print byte_code
        # byte_code.show_without_source()
        assert isinstance(byte_code, ByteCode), str(byte_code)
        return byte_code

    def visit_FunctionDef(self, node):
        # get function parametres
        # and store them in compiler's data structures
        scope = ScopeVariables()

        # in main function of submit mode we don't have
        # any allocated registers
        # hacky!
        if self.compiler.use_submit_mode == True:
            if node.name == P2LConfig.MAIN_IN_SUBMIT_MODE:
                scope.free_index = 0

        all_args = node.args
        # iterate over positional args
        positional_args = all_args.args
        for arg in positional_args:
            arg_name = arg.id
            scope.declare_variable( arg_name, is_local=False )

        self.compiler.local_vars_stack.append(scope)

        # parse function body and add "return"
        byte_code = self.visit_expressions(node.body)
        byte_code.append( ReturnFromFunction() )

        # we store function definition in compiler
        impl = FunctionImpl(node.name, byte_code)
        impl.arity = len(positional_args)

        # scope probably was adjusted (due to local vars) so
        # we probably need to allocate more space
        total_slots = scope.total_slots_allocated()
        impl.dummy_arity = scope.dummy_slots_allocated()

        self.compiler.functions.append(impl)

        # and return empty byte_code
        return ByteCode()

    def visit_Return(self, node):
        # ignore return and just put underlying value on stack
        byte_code = self.visit(node.value)
        return byte_code

    def visit_Compare(self, node):
        assert len(node.ops) == 1
        assert len(node.comparators) == 1
        left = self.visit(node.left)
        right = self.visit(node.comparators[0])

        # we use rewrite rule
        # a < b   < ----- >   b > a
        op = node.ops[0]
        if isinstance(op, ast.Lt):
            op = ast.Gt()
            left, right = right, left

        byte_code = ByteCode()
        byte_code.append_byte_code(left)
        byte_code.append_byte_code(right)

        compare_op = COMPARE_OPERATIONS().get_or_fail(op)
        byte_code.append(compare_op)
        return byte_code

    def visit_expressions(self, expressions):
        byte_code = ByteCode()
        for expr in expressions:
            next = self.visit(expr)
            byte_code.output += next.output
        return byte_code

    def visit_If(self, node):
        condition = self.visit(node.test)
        if_branch = self.visit_expressions(node.body)
        else_branch = self.visit_expressions(node.orelse)

        true_label = LABEL_PROVIDER.next_if_label('true')
        false_label = LABEL_PROVIDER.next_if_label('false')
        finish_label = LABEL_PROVIDER.next_if_label('finish')

        byte_code = ByteCode()
        byte_code.append_byte_code( condition )
        byte_code.append(
            IfBranchLabel(true_label, false_label)
        )

        # if body
        byte_code.append( Label(true_label) )
        byte_code.append_byte_code( if_branch )

        byte_code.append( LoadConstant(0) )
        byte_code.append( JumpLabel(finish_label) )

        # else body
        byte_code.append( Label(false_label) )
        byte_code.append_byte_code( else_branch )

        # continuation
        byte_code.append( Label(finish_label) )
        return byte_code

    def visit_Name(self, node):
        name = node.id
        scope = self.compiler.local_vars()
        global_vars = self.compiler.global_vars

        byte_code = scope.produce_get_byte_code(name)

        if name in global_vars:
            byte_code = ByteCode()
            byte_code.append_byte_code( global_vars[name] )

        if not byte_code:
            raise CompilationError(
                'Unknown variable "{}"'.format(name))
        return byte_code

    def visit_ImportFrom(self, node):
        # Ignore
        return EmptyByteCode()

    def visit_Import(self, node):
        # Ignore
        return EmptyByteCode()

    def visit_Tuple(self, node):
        byte_code = ByteCode()

        for element in node.elts:
            element_code = self.visit(element)
            byte_code.append_byte_code(element_code)

        # combine CONS appropriate number of times
        # compare to list:
        # here we don't have ending 0
        for i in xrange(len(node.elts) - 1):
            byte_code.append( AllocateCons() )

        return byte_code

    def visit_List(self, node):
        byte_code = ByteCode()

        for element in node.elts:
            element_code = self.visit(element)
            byte_code.append_byte_code(element_code)

        byte_code.append( LoadConstant(0) )
        # combine CONS appropriate number of times
        for i in xrange(len(node.elts)):
            byte_code.append( AllocateCons() )

        return byte_code

    def visit_Module(self, node):
        byte_code = ByteCode()
        for expr in node.body:
            next = self.visit(expr)
            byte_code.output += next.output
        byte_code.append( ReturnFromFunction() )
        return byte_code

    def visit_While(self, node):
        condition = self.visit(node.test)
        body = self.visit_expressions(node.body)

        while_label = LABEL_PROVIDER.next_while_label('start')
        body_label = LABEL_PROVIDER.next_while_label('body')
        finish_label = LABEL_PROVIDER.next_while_label('finish')

        byte_code = ByteCode()

        byte_code.append( Label(while_label) )
        byte_code.append_byte_code( condition )
        byte_code.append(
            IfBranchLabel(body_label, finish_label)
        )

        # while body
        byte_code.append( Label(body_label) )
        byte_code.append_byte_code( body )

        # jump on iteration
        byte_code.append( LoadConstant(0) )
        byte_code.append( JumpLabel(while_label) )

        # exit of while
        byte_code.append( Label(finish_label) )
        return byte_code

    def visit_Expr(self, node):
        return self.visit(node.value)

    def visit_Call(self, node):
        func_name = node.func.id

        # special functions
        if func_name == 'ALLOCATE_ARRAY':
            args = node.args
            assert len(args) == 2
            assert_type(args[0], ast.Name)

            size_arg = args[1]
            # HACKING IT:
            if isinstance(size_arg, ast.Num):
                size = args[1].n
            elif isinstance(size_arg, ast.Name):
                constant_name = size_arg.id
                size = self.compiler.global_vars_values[constant_name]
            else:
                raise CompilationError(
                    'Unknown type of 2nd argument in ALLOCATE_ARRAY'.format(
                        str(size_arg)
                ))

            name = args[0].id
            scope = self.compiler.local_vars()
            scope.declare_array(name, size)
            return ByteCode()

        if func_name == 'GET_ARRAY_VALUE':
            args = node.args
            assert len(args) == 2
            assert_type(args[0], ast.Name)

            name = args[0].id
            scope = self.compiler.local_vars()
            offset = scope.array_offset(name)

            output = []
            next = self.visit(args[1])

            output += next.output
            output += [
                LoadConstant(offset),
                IntAddition(),
                LoadEnvGeneric(0)
            ]
            return ByteCode.from_list(output)

        if func_name == 'SET_ARRAY_VALUE':
            args = node.args
            assert len(args) == 3
            assert_type(args[0], ast.Name)

            name = args[0].id
            scope = self.compiler.local_vars()
            offset = scope.array_offset(name)

            output = []

            # parse params
            x_param = self.visit(args[1])
            y_param = self.visit(args[2])

            # we need to add byte code for incrementing offset
            output += x_param.output
            output += [
                LoadConstant(offset),
                IntAddition()
            ]

            output += y_param.output
            output += [
                SaveToEnvGeneric(0)
            ]
            return ByteCode.from_list(output)

        # usual path

        byte_code = ByteCode()
        output = []

        # allocate registers
        if func_name not in BUILTIN_FUNCTIONS:
            # we don't need to allocate for builtin functions
            for i in xrange(P2LConfig.NUM_REGISTERS):
                output.append( LoadConstant(0) )

        for arg in node.args:
            next = self.visit(arg)
            output += next.output

        function = self.compiler.search_function(func_name)
        output.append(function)

        return ByteCode.from_list(output)

    def visit_Assign(self, node):
        assert len(node.targets) == 1
        var_name = node.targets[0].id

        right = self.visit(node.value)

        byte_code = ByteCode()
        byte_code.append_byte_code( right )

        scope = self.compiler.local_vars()

        # TODO: refactor
        # check if variable is already defined
        if scope.is_declared(var_name):
            assign = scope.produce_assign_byte_code(var_name)
            byte_code.append_byte_code( assign )
        else:
            # print 'Need to alocate', var_name
            # allocate new space for variable
            if self.process_consts:
                # add to global array
                # very hacky!
                global_vars = self.compiler.global_vars
                global_vars[var_name] = byte_code

                # also add constants to global
                assert_type(node.value, ast.Num)
                global_vars_values = self.compiler.global_vars_values
                global_vars_values[var_name] = node.value.n
            else:
                scope.declare_variable(var_name, is_local=True)
                assign = scope.produce_assign_byte_code(var_name)
                byte_code.append_byte_code( assign )

        return byte_code

    def visit_UnaryOp(self, node):
        # only nots are supported currently
        assert_type(node.op, ast.Not)

        next = self.visit(node.operand)

        # rewrite rule:
        # not x   <--->   x == 0
        byte_code = ByteCode()
        byte_code.append_byte_code(next)
        byte_code.append( LoadConstant(0) )
        byte_code.append( CompareEqual() )

        return byte_code

    def visit_BoolOp(self, node):
        # only ands are supported currently
        assert_type(node.op, ast.And)
        assert (len(node.values) == 2)

        output = []
        left = self.visit(node.values[0])
        right = self.visit(node.values[1])

        output += left.output
        output += right.output
        # rewrite rule:
        # X and Y  <----> X + Y == 2
        output += [
            IntAddition(),
            LoadConstant(2),
            CompareEqual()
        ]
        return ByteCode.from_list(output)

    def visit_BinOp(self, node):
        # print 'At BinOp', node.op

        byte_code = ByteCode()
        left = self.visit(node.left)
        right = self.visit(node.right)

        byte_code.output += left.output
        byte_code.output += right.output

        binary_op = BINARY_OPERATIONS().get_or_fail(node.op)
        byte_code.append(binary_op)
        # self.generic_visit(node)
        return byte_code

    def visit_Num(self, node):
        byte_code = ByteCode()
        byte_code.append( LoadConstant(node.n) )
        return byte_code


import sys
from collections import deque
inputs = sys.stdin.readline

def bfs(s):
    global visit
    q = deque()
    q.append((0,s))
    visit[s] = 1    # 시작값 => 1
    while q:
        prev,now = q.popleft()
        color = visit[now]      # 현재 노드 색깔
        for num in trees[now]:
            if num == prev:     # 이전에 방문한 노드면 continue
                continue

            if visit[num] == 0:     # 미방문 => 현재 색 반대로 / 큐에 추가
                visit[num] = -color
                q.append((now,num))
            else:                           # 이미 방문했으면
                if visit[num] == color:     # 색이 같으면 => False
                    return False

    return True

K = int(input())
for _ in range(K):
    V,E = map(int,inputs().split())
    trees = [[] for _ in range(V+1)]
    for _ in range(E):
        u,v = map(int,inputs().split())
        trees[u].append(v)
        trees[v].append(u)

    visit = [0] * (V + 1)
    ans = 0
    # 모든 노드 확인
    for i in range(1,V+1):
        if visit[i] == 0:
            check = bfs(i)
            if not check:
                ans = -1
                break

    if ans == 0:
        print("YES")
    else:
        print("NO")


#Author:lzf
#_*_coding:utf-8_*_

import socket,os

# server= socket.socket()
# server.bind(('192.168.2.55',6969)) #绑定要监听的端口
# server.listen()#监听 最大连接，允许最大排队数
#
# print("我要开始等电话了")
# while True:
#     conn,addr=server.accept() #等电话打进来
#     #conn就是客户端连过来而在服务器围棋生成的一个连接实例，因为服务器会有很多等待
#     print(conn,addr)
#
#     print("电话来了")
#     while True:
#         data=conn.recv(1024)
#         print("recv:",data)
#         if not data:
#             print("client has lost...")
#         conn.send(data.upper())
# server.close()

server=socket.socket()
server.bind(('localhost',9998))
server.listen()
while True:
    conn,addr=server.accept()
    print("new conn:",addr)
    while True:
        data=conn.recv(1024)
        if not data:
            print("客户端断开")
            break
        print("执行指令:",data)
        cmd_res = os.popen(data.decode()).read()
        if len(cmd_res)==0:
         cmd_res = b"abc"
        conn.send(str(len(cmd_res.encode())).encode("utf-8"))    #先发客户端

        conn.send(cmd_res.encode("utf-8"))
server.close()


import traceback
import logging
import json

from threading import Thread
from threading import Event

class Promise(object):

    def __init__(self, resolver = None):
        self._event = Event()
        self._rejected = False
        self._result = None

        if resolver:
            self.resolver(resolver)

    def resolver(self, resolver):
        def deferredTask():
            try:
                resolver(self._resolve, self._reject)
            except Exception as e:
                self._reject(e.message)

                traceback.print_exc()

        Thread(target = deferredTask).start()

    def _resolve(self, value):
        # set promise to resolved
        # set result to value
        self._rejected = False
        self._result = value
        self._event.set()

    def _reject(self, reason):
        # set promise to rejected
        # set result to reason
        self._rejected = True
        self._result = reason
        self._event.set()

    def wait(self):
        return self._event.wait()

    def result(self):
        return self._result

    def isRejected(self):
        return self._rejected

    def toJson(self):
        # return a dict containing the current state of the promise
        return {
            'result': self._result,
            'rejected': self._rejected
        }

    def then(self, onFulfilled = None, onRejected = None):
        promise = self.__class__()
        catch = False

        if not onFulfilled and onRejected:
            catch = True

        def deferredTask():
            try:
                self.wait()

                if self._rejected:
                    # the current promise has been rejected
                    # all following onFulfilled methods will be skipped
                    if onRejected:
                        # there is a method for handling onRejected
                        # call method with current value as argument
                        result = onRejected(self.result())

                        if result != None:
                            # the result is not none
                            if catch:
                                # set new promise to resolve to result value
                                promise._resolve(result)
                            else:
                                # this is not an attempt to catch and resolve
                                # set new promise to reject with current value
                                promise._reject(result)
                        else:
                            # the result is none, nothing was returned
                            if catch:
                                # set new promise to resolve to current value
                                promise._resolve(self.result())
                            else:
                                # this is not an attempt to catch and resolve
                                # set new promise to reject with current value
                                promise._reject(self.result())
                    else:
                        # there is no method for handling onRejected
                        # set new promise to reject with current value
                        promise._reject(self.result())
                else:
                    # the current promise has not been rejected
                    # all following onRejected methods will be skipped
                    if onFulfilled:
                        # there is a method for handling onFulfilled
                        # call method with current value as argument
                        result = onFulfilled(self.result())

                        if result != None:
                            # the result is not none
                            # set new promise to resolve to result value
                            promise._resolve(result)
                        else:
                            # the result is none, nothing was returned
                            # set new promise to resolve to current value
                            promise._resolve(self.result())
                    else:
                        # there is no method for handling onFulfilled
                        # set new promise to resolve to current value
                        promise._resolve(self.result())
            except Exception as e:
                # there has been an error along the way
                # set new promise to reject with error message
                promise._reject(e.message)

                traceback.print_exc()

        Thread(target = deferredTask).start()
        #deferredTask()

        return promise

    def catch(self, onRejected):
        # sugar for then(None, onRejected)
        return self.then(None, onRejected)

    @staticmethod
    def resolve(value):
        promise = Promise()

        def deferredTask():
            if isinstance(value, Promise):
                value.wait()

                if value._rejected:
                    promise._reject(value._result)
                else:
                    promise._resolve(value._result)
            elif hasattr(value, '__call__'):
                # the value is callable
                try:
                    result = value()
                except Exception as e:
                    # the called method raises an Exception
                    # reject promise
                    promise._reject(e.message)

                    traceback.print_exc()
                else:
                    # resolve promise with return value from method
                    promise._resolve(result)
            else:
                # resolve promise with value
                promise._resolve(value)

        Thread(target = deferredTask).start()

        return promise

    @staticmethod
    def reject(reason):
        promise = Promise()

        promise._reject(reason)

        return promise

    @staticmethod
    def all(promises):
        new_promise = Promise()
        new_promise_results = []

        def deferredTask():
            for index, promise in enumerate(promises):
                promise.wait()

                if promise.isRejected():
                    new_promise._reject(promise.result())

                    break
                else:
                    new_promise_results.append(promise.result())

            if not new_promise.isRejected():
                new_promise._resolve(new_promise_results)

        Thread(target = deferredTask).start()

        return new_promise

    @staticmethod
    def race(promises):
        threads = []
        new_promise = Promise()

        def deferredTask(promise):
            promise.wait()

            if promise.isRejected():
                new_promise._reject(promise.result())
            else:
                new_promise._resolve(promise.result())

        for index, promise in enumerate(promises):
            threads.append(Thread(target = deferredTask, args = (promise, )).start())

        return new_promise


import pandas as pd

folder = "/path/to/folder/with/cell/barcode/csvs/"
files = ("B-cells", "Malignant", "DC", "Macro", "Mono", "NK", "Other", "pDC",
         "Plasma", "Th", "Tcyt", "Treg") # the changing tags in the names of the csv files

for file in files:
    print(file)
    df = pd.read_csv(folder+file+".csv", header = 1, names = ["drop", "barcode"])
    df = df.drop(["drop"], axis=1)
    df.barcode = df.barcode.str.replace('P12_1670_', '')
    df.barcode = df.barcode.str.replace('-1', '')
    barcodelist = df.barcode.tolist()
    outfile = "/output/path/{}.sam".format(file)
    infile = "/path/to/samfile/samfile.sam"
    with open(outfile, "a") as outsam:
        with open(infile) as insam:
            for line in insam:
                if not line.startswith("@"):
                    a = line
                    line = line.split("\t")
                    d = {}
                    for elem in line:
                        if len(elem) > 7:
                            d[elem[:5]] = elem[5:-2]
                    if "CB:Z:" in d:
                        if d["CB:Z:"] in barcodelist:
                            outsam.write(a)
                else:
                    outsam.write(line)
print("Finished")


from os import path as path

import numpy as np

from ...surface import _read_patch, complete_surface_info, read_curvature, read_surface
from ...utils import _check_fname, _check_option, _validate_type, get_subjects_dir

class _Surface:
    """Container for a brain surface.

    It is used for storing vertices, faces and morphometric data
    (curvature) of a hemisphere mesh.

    Parameters
    ----------
    subject : string
        Name of subject
    hemi : {'lh', 'rh'}
        Which hemisphere to load
    surf : string
        Name of the surface to load (eg. inflated, orig ...).
    subjects_dir : str | None
        If not None, this directory will be used as the subjects directory
        instead of the value set using the SUBJECTS_DIR environment variable.
    offset : float | None
        If 0.0, the surface will be offset such that the medial
        wall is aligned with the origin. If None, no offset will
        be applied. If != 0.0, an additional offset will be used.
    units : str
        Can be 'm' or 'mm' (default).
    x_dir : ndarray | None
        The x direction to use for offset alignment.

    Attributes
    ----------
    bin_curv : numpy.ndarray
        Curvature values stored as non-negative integers.
    coords : numpy.ndarray
        nvtx x 3 array of vertex (x, y, z) coordinates.
    curv : numpy.ndarray
        Vector representation of surface morpometry (curvature) values as
        loaded from a file.
    grey_curv : numpy.ndarray
        Normalized morphometry (curvature) data, used in order to get
        a gray cortex.
    faces : numpy.ndarray
        nfaces x 3 array of defining mesh triangles.
    hemi : {'lh', 'rh'}
        Which hemisphere to load.
    nn : numpy.ndarray
        Vertex normals for a triangulated surface.
    offset : float | None
        If float, align inside edge of each hemisphere to center + offset.
        If None, do not change coordinates (default).
    subject : string
        Name of subject.
    surf : string
        Name of the surface to load (eg. inflated, orig ...).
    units : str
        Can be 'm' or 'mm' (default).
    """

    def __init__(
        self,
        subject,
        hemi,
        surf,
        subjects_dir=None,
        offset=None,
        units="mm",
        x_dir=None,
    ):
        x_dir = np.array([1.0, 0, 0]) if x_dir is None else x_dir
        assert isinstance(x_dir, np.ndarray)
        assert np.isclose(np.linalg.norm(x_dir), 1.0, atol=1e-6)
        assert hemi in ("lh", "rh")
        _validate_type(offset, (None, "numeric"), "offset")

        self.units = _check_option("units", units, ("mm", "m"))
        self.subject = subject
        self.hemi = hemi
        self.surf = surf
        self.offset = offset
        self.bin_curv = None
        self.coords = None
        self.curv = None
        self.faces = None
        self.grey_curv = None
        self.nn = None
        self.labels = dict()
        self.x_dir = x_dir

        subjects_dir = str(get_subjects_dir(subjects_dir, raise_error=True))
        self.data_path = path.join(subjects_dir, subject)
        if surf == "seghead":
            raise ValueError(
                "`surf` cannot be seghead, use "
                "`mne.viz.Brain.add_head` to plot the seghead"
            )

    def load_geometry(self):
        """Load geometry of the surface.

        Parameters
        ----------
        None

        Returns
        -------
        None
        """
        if self.surf == "flat":  # special case
            fname = path.join(
                self.data_path, "surf", "%s.%s" % (self.hemi, "cortex.patch.flat")
            )
            _check_fname(
                fname, overwrite="read", must_exist=True, name="flatmap surface file"
            )
            coords, faces, orig_faces = _read_patch(fname)
            # rotate 90 degrees to get to a more standard orientation
            # where X determines the distance between the hemis
            coords = coords[:, [1, 0, 2]]
            coords[:, 1] *= -1
        else:
            # allow ?h.pial.T1 if ?h.pial doesn't exist for instance
            # end with '' for better file not found error
            for img in ("", ".T1", ".T2", ""):
                surf_fname = path.join(
                    self.data_path, "surf", f"{self.hemi}.{self.surf}{img}"
                )
                if path.isfile(surf_fname):
                    break
            coords, faces = read_surface(surf_fname)
            orig_faces = faces
        if self.units == "m":
            coords /= 1000.0
        if self.offset is not None:
            x_ = coords @ self.x_dir
            if self.hemi == "lh":
                coords -= (np.max(x_) + self.offset) * self.x_dir
            else:
                coords -= (np.min(x_) + self.offset) * self.x_dir
        surf = dict(rr=coords, tris=faces)
        complete_surface_info(surf, copy=False, verbose=False, do_neighbor_tri=False)
        nn = surf["nn"]
        self.coords = coords
        self.faces = faces
        self.orig_faces = orig_faces
        self.nn = nn

    def __len__(self):
        """Return number of vertices."""
        return len(self.coords)

    @property
    def x(self):
        return self.coords[:, 0]

    @property
    def y(self):
        return self.coords[:, 1]

    @property
    def z(self):
        return self.coords[:, 2]

    def load_curvature(self):
        """Load in curvature values from the ?h.curv file."""
        curv_path = path.join(self.data_path, "surf", "%s.curv" % self.hemi)
        if path.isfile(curv_path):
            self.curv = read_curvature(curv_path, binary=False)
            self.bin_curv = np.array(self.curv > 0, np.int64)
            color = (self.curv > 0).astype(float)
        else:
            self.curv = None
            self.bin_curv = None
            color = np.ones((self.coords.shape[0]))
        # morphometry (curvature) normalization in order to get gray cortex
        # TODO: delete self.grey_curv after cortex parameter
        # will be fully supported
        color = 0.5 - (color - 0.5) / 3
        color = color[:, np.newaxis] * [1, 1, 1]
        self.grey_curv = color


'''Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.'''

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if not nums: return 0
        nums = set(nums)
        longest = 1
        while nums:
            curr = 1
            i = j = nums.pop()
            while i - 1 in nums:
                nums.remove(i-1)
                i -= 1
                curr += 1
            while j + 1 in nums:
                nums.remove(j+1)
                j += 1
                curr += 1
            longest = max(longest, curr)
        return longest