import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from matplotlib import pyplot as plt
from tensorflow.keras.models import load_model
from numpy import amax,argmax
from pickle import load

class NLU:

    def __init__(self):
        self.intents_model=load_model("./Models/lstm_classification.h5")
        self.ner_model=load_model("./Models/ner_recognition.h5")
        with open("./Models/Preprocessing" ,"rb") as file:
            self.tokenizer=load(file)

    def predict_intent(self,sentence):
        clear_sentence=self.tokenizer.preprocess_sentence(sentence)
        results = self.intents_model.predict([clear_sentence])[0]
        predictions=[[i,r] for i,r in enumerate(results)]
        predictions.sort(key=lambda x: x[1], reverse=True)
        intents_tag_list=self.tokenizer.intent_tags_list
        if predictions[0][1]<0.60:
            return_class="brak_odpowiedzi"
        else:
            return_class=intents_tag_list[predictions[0][0]]
        return return_class

    def extract_ner(self,sentence):
        vectorized_sentence=self.tokenizer.preprocess_sentence(sentence)
        results = self.ner_model.predict([vectorized_sentence])[0]
        tokens=self.tokenizer.clear_sentence(sentence)
        tokens=self.tokenizer.lemmatize(tokens)
        tokenizer_ner_tags=self.tokenizer.ner_tags_list
        tag2idx=self.tokenizer.tag2idx
        extracted_entity_list=[]
        for p,w in zip(results,tokens):
            class_probability=amax(p)
            if class_probability>0.80:
                class_name=argmax(p)
                if class_name != tag2idx["O"]:
                    extracted_entity_list.append([w,tokenizer_ner_tags[class_name]])
        return extracted_entity_list


# 6. Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
import math

def main():
    circulo = float(input('Qual o valor do circulo C: '))
    raio = circulo / (2 * math.pi)

    area = math.pi * raio ** 2

    print(f'A raio do circulo é: {raio}')
    print(f'A área do círculo é: {area}')

main()


import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
sns.set()

data = pd.read_csv("spotify.csv")
data.head()

from sklearn.preprocessing import MinMaxScaler
datatypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
normarization = data.select_dtypes(include=datatypes)
for col in normarization.columns:
    MinMaxScaler(col)

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=10)
features = kmeans.fit_predict(normarization)
data['features'] = features
MinMaxScaler(data['features'])

class Spotify_Recommendation():
    def __init__(self, dataset):
        self.dataset = dataset
    def recommend(self, songs, amount=1):
        distance = []
        song = self.dataset[(self.dataset.name.str.lower() == songs.lower())].head(1).values[0]
        rec = self.dataset[self.dataset.name.str.lower() != songs.lower()]
        for songs in tqdm(rec.values):
            d = 0
            for col in np.arange(len(rec.columns)):
                if not col in [1, 6, 12, 14, 18]:
                    d = d + np.absolute(float(song[col]) - float(songs[col]))
            distance.append(d)
        rec['distance'] = distance
        rec = rec.sort_values('distance')
        columns = ['artists', 'name']
        return rec[columns][:amount]

recommendations = Spotify_Recommendation(data)
recommendations.recommend("Lovers Rock", 10)


#El Factor Primo Mayot De un Numero x
num=600851475143
vec=[]
inc=1
while(True):
    inc+=1
    if(num%inc==0):
        vec.append(inc)
        num=num/inc
        inc=1
    if(num/inc==1):
        break
print(vec)
print("El Factor Primo Mayor Es: ",max(vec))


import os
import os.path as osp
import shutil
import glob

import torch
import torch.nn.functional as F

from scipy.io import loadmat
from torch_geometric.data import (Data, InMemoryDataset, download_url,
                                  extract_zip)

try:
    import torchvision.models as models
    import torchvision.transforms as T
    from PIL import Image
except ImportError:
    models = None
    T = None
    Image = None

class WILLOWObjectClass(InMemoryDataset):
    r"""The WILLOW-ObjectClass dataset from the `"Learning Graphs to Match"
    <https://www.di.ens.fr/willow/pdfscurrent/cho2013.pdf>`_ paper,
    containing 10 equal keypoints of at least 40 images in each category.
    The keypoints contain interpolated features from a pre-trained VGG16 model
    on ImageNet (:obj:`relu4_2` and :obj:`relu5_1`).

    Args:
        root (string): Root directory where the dataset should be saved.
        category (string): The category of the images (one of :obj:`"Car"`,
            :obj:`"Duck"`, :obj:`"Face"`, :obj:`"Motorbike"`,
            :obj:`"Winebottle"`)
        transform (callable, optional): A function/transform that takes in an
            :obj:`torch_geometric.data.Data` object and returns a transformed
            version. The data object will be transformed before every access.
            (default: :obj:`None`)
        pre_transform (callable, optional): A function/transform that takes in
            an :obj:`torch_geometric.data.Data` object and returns a
            transformed version. The data object will be transformed before
            being saved to disk. (default: :obj:`None`)
        pre_filter (callable, optional): A function that takes in an
            :obj:`torch_geometric.data.Data` object and returns a boolean
            value, indicating whether the data object should be included in the
            final dataset. (default: :obj:`None`)
    """
    url = ('http://www.di.ens.fr/willow/research/graphlearning/'
           'WILLOW-ObjectClass_dataset.zip')

    def __init__(self, root, category, transform=None, pre_transform=None,
                 pre_filter=None):
        assert category in ['Car', 'Duck', 'Face', 'Motorbike', 'Winebottle']
        self.category = category
        super(WILLOWObjectClass, self).__init__(root, transform, pre_transform,
                                                pre_filter)
        self.data, self.slices = torch.load(self.processed_paths[0])

    @property
    def raw_file_names(self):
        return ['Car', 'Duck', 'Face', 'Motorbike', 'Winebottle']

    @property
    def processed_file_names(self):
        return '{}.pt'.format(self.category.lower())

    def download(self):
        path = download_url(self.url, self.root)
        extract_zip(path, self.root)
        os.unlink(path)
        os.unlink(osp.join(self.root, 'README'))
        os.unlink(osp.join(self.root, 'demo_showAnno.m'))
        shutil.rmtree(self.raw_dir)
        os.rename(osp.join(self.root, 'WILLOW-ObjectClass'), self.raw_dir)

    def process(self):
        if models is None or T is None or Image is None:
            raise ImportError('Package `torchvision` could not be found.')

        names = glob.glob(osp.join(self.raw_dir, self.category, '*.png'))
        names = sorted([name[:-4] for name in names])

        vgg16_outputs = []

        def hook(module, x, y):
            vgg16_outputs.append(y)

        vgg16 = models.vgg16(pretrained=True)
        vgg16.eval()
        vgg16.features[20].register_forward_hook(hook)  # relu4_2
        vgg16.features[25].register_forward_hook(hook)  # relu5_1

        transform = T.Compose([
            T.ToTensor(),
            T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])

        data_list = []
        for name in names:
            pos = loadmat('{}.mat'.format(name))['pts_coord']
            x, y = torch.from_numpy(pos).to(torch.float)
            pos = torch.stack([x, y], dim=1)

            # The "Face" category contains a single image with less than 10
            # keypoints, so we need to skip it.
            if pos.size(0) != 10:
                continue

            with open('{}.png'.format(name), 'rb') as f:
                img = Image.open(f).convert('RGB')
            img = transform(img)
            size = img.size()[-2:]
            vgg16_outputs.clear()
            vgg16(img.unsqueeze(0))

            xs = []
            for out in vgg16_outputs:
                out = F.interpolate(out, size, mode='bilinear',
                                    align_corners=False)
                out = out.squeeze(0).permute(1, 2, 0)
                out = out[y.round().long(), x.round().long()]
                xs.append(out)

            data = Data(x=torch.cat(xs, dim=-1), pos=pos)

            if self.pre_filter is not None and not self.pre_filter(data):
                continue
            if self.pre_transform is not None:
                data = self.pre_transform(data)
            data_list.append(data)

        torch.save(self.collate(data_list), self.processed_paths[0])

    def __repr__(self):
        return '{}({}, category={})'.format(self.__class__.__name__, len(self),
                                            self.category)


# ASSOCIATING BETWEEN CLASSES

                        # DEFINE USER CLASS
class User:
    def __init__(self, username = 'unk', email_address = 'unk', num_accts = 1):
        self.user = username
        self.email = email_address
        self.accounts = {}          # create a blank dictionary
        for i in range(num_accts):  # create the number of accounts specified by num_accts
            self.accounts["Account" + str(i+1)] = BankAccount(0, 0.01)
                                    # creates dict accounts =  {"Account1" : BankAccount(balance, interest), etc. }

    def make_deposit(self, amount, acctNum = 'Account1'):
        print(f"{self.user} deposits ${amount} into {acctNum}")
        self.accounts[acctNum].balance += amount
        return self

    def make_withdrawal(self, amount, acctNum = 'Account1'):
        print(f"{self.user} withdraws ${amount} out of {acctNum}")
        self.accounts[acctNum].balance -= amount
        return self

    def display_all_balances(self):
        print("-"*50)
        print(f"{self.user}:")
        for x, y in self.accounts.items():  # iterates through dict returning Key as x and value as y
            print(f"\t{x} Balance:  ${y.balance}")
        print("-"*50)
        return self

    def display_acct_balance(self, acctNum = 'Account1'):
        print(f"{self.user}'s balance in {acctNum}:  ${self.accounts[acctNum].balance}\n", "-"*50)

    def transfer_money(self, other_user, amount = 0, acctOut = 'Account1', acctIn = 'Account1'):
        print(f"{self.user} transfers ${amount} from {acctOut}\nto: {other_user.user}, into {acctIn}.")
        self.accounts[acctOut].balance -= amount
        other_user.accounts[acctIn].balance += amount
        return self

    def yield_all_interest(self):
        for i in self.accounts:
            if self.accounts[i].balance > 0:
                int_yield = self.accounts[i].balance * self.accounts[i].interest
                self.accounts[i].balance += int_yield
                print(f"${int_yield} interest added to {self.user}'s {i}.")
        return self

                    #  Define Bank Account Class
class BankAccount:
    def __init__(self, start_bal = 0, start_int_rate = 0.01):
        self.balance = start_bal
        self.interest = start_int_rate

mike = User("Michael", "mike@here.com", 3)
anna = User("Anna", "annie@here.com", 2)
guido = User("Guido Van Rossum", "guido@python.com", 1)
monty = User("Monty Python", "monty@python.com", 4)

mike.display_all_balances()
mike.display_acct_balance('Account2')

def print_everybody():
    print("*"*50)
    userArray = [mike, anna, guido, monty]
    for i in userArray:
        i.display_all_balances()
    print("*"*50)

print_everybody()

mike.make_deposit(200, 'Account1').make_deposit(100, 'Account2').make_deposit(100, 'Account3').make_withdrawal(75, 'Account1').yield_all_interest().display_all_balances()

anna.make_deposit(100).make_deposit(500, 'Account2').make_withdrawal(50, 'Account2').make_withdrawal(175).yield_all_interest().display_all_balances()

guido.make_deposit(100, 'Account1').make_withdrawal(7.50).make_withdrawal(20).make_withdrawal(54).yield_all_interest().display_all_balances()

mike.transfer_money(monty, 100).yield_all_interest().display_all_balances()

monty.yield_all_interest().display_all_balances()

print_everybody()


from django.db import models
from user.models import User
from django.conf import settings

class Petition(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=False,blank=False)
    image = models.ImageField(upload_to = 'petition')
    dimension = models.FloatField()
    text = models.TextField(blank = False, null = False)
    color = models.IntegerField(blank = True, null = True)
    font = models.IntegerField(blank = True, null = True)
    date = models.DateTimeField(auto_now_add=True)

    def getImage(self):
        if self.image:
            if "petition" in str(self.image.url):
                image =  "https://" + settings.ALLOWED_HOSTS[0] + self.image.url
            else:
                image =  str(self.image)
            return image
        return ''

class StaticPetition(models.Model):
    id = models.AutoField(primary_key=True)
    image = models.ImageField(upload_to = 'static_petition')
    is_active = models.BooleanField(default=True)

    def getImage(self):
        if self.image:
            return "https://" + settings.ALLOWED_HOSTS[0] + self.image.url
        return ''


# -*- coding: utf-8 -*-
from Services import StockDetailFinder, Appendix
from WindPy import *

# The main difference between China and Others are the delivery of contents.
# In China, I need to mention the specific points of going up or down.
# In other markets, it is in no need. But I need to mention all the N markets total performance.
def overview_china(stock_id_list, date):
    output_string = ''
    # print date
    weekday = Appendix.weekday_printer(date=date)
    output_string = output_string + weekday + '，'

    for stock_num in range(len(stock_id_list)):
        stock = stock_id_list[stock_num]
        sec_name, pct_chg, chg, close, amt = StockDetailFinder.Session(stock, date).data_printer()
        # Symbol Generator
        if stock_num < len(stock_id_list)-1:
            symbol = '；'
        else:
            symbol = '。\n'

        if chg < 0:
            output_string = output_string + '{sec_name}跌{pct_chg:.2f}%或{chg:.2f}点，报{close:.2f}点'.format(
                sec_name=sec_name, pct_chg=abs(pct_chg), chg=abs(chg), close=close) + symbol
        elif chg == 0:
            output_string = output_string + '{sec_name}报{close:.2f}点，与开盘价格持平'.format(
                sec_name=sec_name, close=close) + symbol
        else:
            output_string = output_string + '{sec_name}涨{pct_chg:.2f}%或{chg:.2f}点，报{close:.2f}点'.format(
                sec_name=sec_name, pct_chg=abs(pct_chg), chg=abs(chg), close=close) + symbol

    return output_string

def overview_others(market_type, stock_id_list, date):
    output_string = ''
    # print date
    weekday = Appendix.weekday_printer(date=date)
    output_string = output_string + weekday + '，'
    # parameters for save data into dict and generate the overview words of the market
    go_up = 0
    stock_dict = {}
    for stock_num in range(len(stock_id_list)):
        stock = stock_id_list[stock_num]
        stock_dict[stock_num] = {}
        stock_dict[stock_num]['sec_name'], stock_dict[stock_num]['pct_chg'], stock_dict[stock_num]['chg'], stock_dict[stock_num]['close'], stock_dict[stock_num]['amt'] = StockDetailFinder.Session(stock, date).data_printer()
    for stock_num in range(len(stock_id_list)):
        if stock_dict[stock_num]['chg'] > 0:
            go_up = go_up + 1
        else:
            pass
    output_string = output_string + market_type
    if go_up == len(stock_id_list):
        output_string = output_string + '收盘全线上涨。'
    elif go_up >= len(stock_id_list)/2:
        output_string = output_string + '收盘普涨。'
    elif go_up < len(stock_id_list)/2:
        output_string = output_string + '收盘普跌。'
    elif go_up == 0:
        output_string = output_string + '收盘全线下跌。'
    # read data in the dict and print the performance of the market of the day
    for stock_num in range(len(stock_id_list)):
        stock_dict[stock_num]['sec_name'] = {
            '日经225': '日经225指数',
            '韩国综合指数': '韩国综合指数',
            '澳洲标普200': '澳大利亚ASX200指数',
            '道琼斯工业指数': '道琼斯工业平均指',
            '标普500': '标普500指数',
            '纳斯达克指数': '纳斯达克综合指数',
            '富时100': '英国富时100指数',
            '法国CAC40': '法国CAC40指数',
            '德国DAX': '德国DAX指数'
        }.get(stock_dict[stock_num]['sec_name'], 'Error!')
        if stock_num < len(stock_id_list) - 1:
            symbol = '；'
        else:
            symbol = '。\n'
        if stock_dict[stock_num]['chg'] < 0:
            output_string = output_string + '{sec_name}跌{pct_chg:.2f}%，报{close}点'.format(
                sec_name=stock_dict[stock_num]['sec_name'], pct_chg=abs(stock_dict[stock_num]['pct_chg']), close=stock_dict[stock_num]['close']) + symbol
        elif stock_dict[stock_num]['chg'] == 0:
            output_string = output_string + '{sec_name}报{close}点，与开盘价格持平'.format(
                sec_name=stock_dict[stock_num]['sec_name'], close=stock_dict[stock_num]['close']) + symbol
        else:
            output_string = output_string + '{sec_name}涨{pct_chg:.2f}%，报{close}点'.format(
                sec_name=stock_dict[stock_num]['sec_name'], pct_chg=abs(stock_dict[stock_num]['pct_chg']), close=stock_dict[stock_num]['close']) + symbol

    return output_string

def volume(stock_id_list, date):
    output_string = ''
    output_string = output_string + "成交量方面，"
    total_amt_today = 0
    total_amt_yesterday = 0
    # Today volume
    for stock_num in range(len(stock_id_list)):
        stock = stock_id_list[stock_num]
        sec_name, pct_chg, chg, close, amt = StockDetailFinder.Session(stock, date).data_printer()
        sec_name = {
            '上证综指': '沪市',
            '深证成指': '深市',
            '创业板指': '创业板'
        }.get(sec_name, 'Error!')
        amt = amt/100000000
        output_string = output_string + '{sec_name}成交{amt:.2f}亿元'.format(
            sec_name=sec_name, amt=amt) + '，'
        total_amt_today = total_amt_today + amt
    # Yesterday volume
    if Appendix.weekday_returner(date) == '周一':  # TODO: BUGS: 注意节假日避让
        yesterday_date = str(int(date)-3)
    else:
        yesterday_date = str(int(date)-1)
    for stock_num in range(len(stock_id_list)):
        stock = stock_id_list[stock_num]
        sec_name, pct_chg, chg, close, amt = StockDetailFinder.Session(stock, yesterday_date).data_printer()
        amt = amt / 100000000
        total_amt_yesterday = total_amt_yesterday + amt
    output_string = output_string + '总成交额{total_amt_today:.2f}亿元'.format(
        total_amt_today=total_amt_today) + '，'
    if total_amt_today > total_amt_yesterday * 1.2:
        output_string = output_string + '较上一交易日量能明显上升。'
    elif total_amt_yesterday < total_amt_today < total_amt_yesterday * 1.2:
        output_string = output_string + '较上一交易日有所上升。'
    elif total_amt_today < total_amt_yesterday * 0.8:
        output_string = output_string + '较上一交易日成交量显著减小。'
    elif total_amt_today < total_amt_yesterday:
        output_string = output_string + '较上一交易日成交量有所缩小。'

    return output_string

if __name__ == "__main__":
    w.start()
    '''
    print('全球市场')
    # Chinese Market
    Stock_ID_CN = '000001.SH,399001.SZ,399006.SZ'
    Stock_ID_List_CN = Stock_ID_CN.split(',')
    print(overview_china(Stock_ID_List_CN, '20181221'), end='')
    # Asian Market
    Stock_ID_Asia = "N225.GI,KS11.GI,AS51.GI"
    Stock_ID_List_Asia = Stock_ID_Asia.split(',')
    print(overview_others('亚太股市', Stock_ID_List_Asia, '20181221'))
    '''
    print('成交量')
    Stock_ID_CN = '000001.SH,399001.SZ,399006.SZ'
    Stock_ID_List_CN = Stock_ID_CN.split(',')
    print(volume(Stock_ID_List_CN, '20181228'))


import asyncio
import datetime
from typing import Iterable, AsyncGenerator, cast

from fastapi import APIRouter

from playip.bdwgc.bdwgc import getWDB
from playip.bdwgc.sql_import_analytics_tickets import sql_analytics_tickets
from playipappcommons.analytics.contractsanalytics import ContractAnalyticData, ServicePackAnalyticData, \
    ServicePackAndContractAnalyticData,  ImportContractsResult
from playipappcommons.analytics.contractsanalyticsmodels import TicketData, iadr_key
from playipappcommons.analytics.contractsimport import import_contracts_raw
from playipappcommons.basictaskcontrolstructure import getControlStructure
from playipappcommons.infra.endereco import Endereco
from dateutil import tz
from dateutil.tz import tzutc

onGoingImportAnalyticDataResult: ImportContractsResult = None

tzsp = tz.tzoffset('IST', -10800)
def cf(s):
    if s is None:
        return None
    r = s.strip().replace("/","-")
    return r

class ObjRow:
    pass

async def getContratoPacoteServicoTicketIterator() -> AsyncGenerator[ServicePackAndContractAnalyticData, None]:
    wdb = await getWDB()

    global onGoingImportAnalyticDataResult
    res: ImportContractsResult = onGoingImportAnalyticDataResult

    with wdb.cursor() as cursor:
        cursor.execute(sql_analytics_tickets)

        columns = [column[0] for column in cursor.description]
        headers = columns

        rrow = cursor.fetchone()
        while rrow:

            row = ObjRow()
            for h, v in zip(headers, rrow):
                if v is None:
                    pass
                elif isinstance(v, datetime.datetime):
                    #dtv: datetime.datetime = cast(datetime.datetime)
                    if v.tzinfo is None or v.tzinfo.utcoffset(v) is None:
                        # dtv.replace(tzinfo=tzsp)
                        v = datetime.datetime(year=v.year, month=v.month, day=v.day, hour=v.hour, minute=v.minute, second=v.second, microsecond=v.microsecond, tzinfo=tzsp)
                    v = v.timestamp()
                elif isinstance(v, datetime.date):
                    v = datetime.datetime(v.year, v.month, v.day, tzinfo=tzsp)
                    v = v.timestamp()
                elif isinstance(v, str):
                    v = cf(v)
                row.__setattr__(h, v)

            is_radio = row.NM_MEIO == "radio"  # a outra opção no wgc é "fibra"
            medianetwork = "Rádio" if is_radio else "Cabo"
            enderecoInfra: Endereco = Endereco\
            (
                    logradouro=row.logradouro, numero=row.num, complemento=row.complemento, bairro=row.bairro, cep=row.cep,
                    condominio=row.condominio, cidade=row.cidade, uf=row.id_uf, prefix="Infraestrutura-"+medianetwork
            )
            enderecoComercial: Endereco = Endereco\
            (
                    logradouro=row.logradouro, numero=row.num, complemento=row.complemento, bairro=row.bairro, cep=row.cep,
                    condominio=row.condominio, cidade=row.cidade, uf=row.id_uf, prefix="Comercial"
            )
            #for endereco in [enderecoInfra, enderecoComercial]:
            contract: ContractAnalyticData = ContractAnalyticData\
            (
                id_contract=row.ID_CONTRATO,
                DT_ATIVACAO=row.CONTRATO_DT_ATIVACAO,
                DT_CANCELAMENTO=row.CONTRATO_DT_CANCELAMENTO,
                DT_INICIO=row.CONTRATO_DT_INICIO,
                DT_FIM=row.CONTRATO_DT_FIM,
                STATUS_CONTRATO=row.STATUS_CONTRATO,
                enderecos=[enderecoComercial, enderecoInfra]
            )
            service: ServicePackAnalyticData = ServicePackAnalyticData\
            (
                fullName = row.NM_PROD + "/" + row.NM_MEIO + "/" + row.NM_TEC + "/" + row.NM_PACOTE_SERVICO, #+ "/",
                DT_ATIVACAO=row.SERVICO_DT_ATIVACAO,
                DT_DESATIVACAO=row.SERVICO_DT_DESATIVACAO,
                DT_DESISTENCIA=row.SERVICO_DT_DESISTENCIA,
                DT_CADASTRO=row.SERVICO_DT_CADASTRO,
                TX_MOTIVO_CANCELAMENTO=row.SERVICO_TX_MOTIVO_CANCELAMENTO if row.SERVICO_TX_MOTIVO_CANCELAMENTO else "Desconhecido",
                VL_SERVICO=row.VL_PACOTE, # só há um serviço, relevante,então posso jogar o preço do pacote todod nele para fins estatísticos
                download_speed=row.VL_DOWNLOAD,
                upload_speed=row.VL_UPLOAD,
                VL_PACOTE=row.VL_PACOTE
            )
            ticket: TicketData = TicketData\
            (
                DT_ABERTURA=row.DT_ticketAbertura,
                DT_FECHAMENTO=row.DT_ticketFechamento,
                NM_AREA_TICKET=row.ticketArea
            )
            spc: ServicePackAndContractAnalyticData = ServicePackAndContractAnalyticData(contract=contract, service=service, ticket=ticket)

            # try:
            #     spc: ServicePackAndContractAnalyticData = ServicePackAndContractAnalyticData(contract=contract, service=service)
            # except:
            #     res.num_fails += 1
            # res.num_processed += 1
            yield spc

            rrow = cursor.fetchone()

async def getImportContractsResultIntern(mdb, begin:bool) -> ImportContractsResult:
    return cast(ImportContractsResult, await getControlStructure(mdb, iadr_key, begin))

async def importAllContratoPacoteServicoTicket(mdb, iadr:ImportContractsResult):
    it: Iterable[ServicePackAndContractAnalyticData] = getContratoPacoteServicoTicketIterator()
    await import_contracts_raw(it, iadr)

    # onGoingImportAnalyticDataResult = await getImportAnalyticDataResult(True)
    # if onGoingImportAnalyticDataResult.started:
    #     return
    # onGoingImportAnalyticDataResult.started = True
    # await setImportAnalyticDataResult(onGoingImportAnalyticDataResult)
    #
    # it: Iterable[ServicePackAndContractAnalyticData] = getContratoPacoteServicoTicketIterator()
    # await import_contracts_raw(it, onGoingImportAnalyticDataResult)
    #
    # # it: AsyncGenerator[ServicePackAndContractAnalyticData, None] = getContratoPacoteServicoIterator()
    # # await count_events_contracts_raw(it)


# Modified from combo.py

import numpy as np
import torch
from typing import Dict, Union, Tuple, Optional
from offlinerlkit.modules import RcslGaussianModule
from offlinerlkit.policy import BasePolicy

class RcslGaussianPolicy(BasePolicy):
    """
    wrapped rcsl policy
    """

    def __init__(
        self,
        rcsl: RcslGaussianModule,
        rcsl_optim: torch.optim.Optimizer,
        device: Union[str, torch.device]
    ) -> None:
        super().__init__()

        self.rcsl = rcsl
        self.rcsl_optim = rcsl_optim

        self.device = device

    def learn(self, batch: Dict) -> Dict[str, float]:
        obss, actions, rtgs = batch["observations"], batch["actions"], batch["rtgs"]

        mu, logvar = self.rcsl.get_dist_params(obss, rtgs)
        inv_var = torch.exp(-logvar)
        # Average over batch and dim, sum over ensembles.
        mse_loss_inv = (torch.pow(mu - actions.to(mu.device), 2) * inv_var).mean() # MLE for Gaussian
        var_loss = logvar.mean()
        loss = mse_loss_inv + var_loss

        self.rcsl_optim.zero_grad()
        loss.backward()
        self.rcsl_optim.step()

        result =  {
            "loss": loss.item(),
        }

        return result

    @ torch.no_grad()
    def validate(self, batch: Dict) -> Dict[str, float]:
        obss, actions, rtgs = batch["observations"], batch["actions"], batch["rtgs"]

        mu, logvar = self.rcsl.get_dist_params(obss, rtgs)
        inv_var = torch.exp(-logvar)
        # Average over batch and dim, sum over ensembles.
        mse_loss_inv = (torch.pow(mu - actions.to(mu.device), 2) * inv_var).mean() # MLE for Gaussian
        var_loss = logvar.mean()
        loss = mse_loss_inv + var_loss

        result =  {
            "loss": loss.item(),
        }

        return result

    def select_action(self, obs: np.ndarray, rtg: np.ndarray) -> np.ndarray:
        with torch.no_grad():
            dist = self.rcsl.forward(obs, rtg)
            action = dist.rsample()
        return action.cpu().numpy()

    def train(self) -> None:
        self.rcsl.train()

    def eval(self) -> None:
        self.rcsl.eval()


import csv
import sys
from tabulate import tabulate
from time import sleep

# class for current story progress
class Story:
    def __init__(self):
        self.progress = None

    def story_progress(self, room):
        self.progress = room

# class to keep track of and load room data
class Rooms:
    def __init__(self):
        self.room_name = ""
        self.room_text = ""
        self.room_mons = ""
        self.room_branch = ""
        self.room_current = ""
        self.mon_stats = []

    def __str__(self):
        if self.room_mons == "":
            self.room_mons = "\nNo monsters in this room"
        return f'{self.room_name}: {self.room_text}\nMonsters:{self.room_mons}'

    # loads room related variables
    def open_room(self, location):
        self.room_mons = ""
        with open("room.csv") as room:
            room_list = csv.DictReader(room)
            for row in room_list:
                if row["id"] == location:
                    # room name and current location
                    self.room_name = row["name"]
                    self.room_current = row["id"]
                    # room flavour text
                    room_text_no = row["text"]
                    with open("room_text.csv") as text_file:
                        text_list = csv.DictReader(text_file)
                        for line in text_list:
                            if line["id"] == room_text_no:
                                self.room_text = line["text"]
                    # add monsters
                    self.room_monsters(row["mons"])
                    # add next room branch
                    self.room_branch = row["branch"]

    # returns current room
    def room_location(self):
        return self.room_current

    # load monsters into dict
    def room_monsters(self, mons_list_raw):
        if self.mon_stats == []:
            mons_list_split = mons_list_raw.split("/")
            mon_num = 0
            for split in mons_list_split:
                with open("mons.csv") as mons:
                    mons_list = csv.DictReader(mons)
                    for row in mons_list:
                        if row["id"] == split:
                            mon_num += 1
                            self.room_mons += f'\n• {row["name"]}'
                            stats = {"no": mon_num, "name":row["name"], "hp":int(row["hp"]), "attk":row["attk"], "dmg":int(row["dmg"]), "exp":int(row["exp"])}
                            self.mon_stats.append(stats)

    # display monster dict
    def monster_table(self):
        if self.mon_stats == []:
            print("All monsters defeated!")
        else:
            print(tabulate(self.mon_stats, headers="keys", tablefmt="grid"))

    # handles monster damage. target must be an int
    def monster_damage(self, target, damage):
        r = -1
        for row in self.mon_stats:
            r += 1
            if row["no"] == target:
                row["hp"] -= damage
                if row["hp"] <= 0:
                    print(f'You have defeated {row["name"]}')
                    # deletes row index from dict
                    del self.mon_stats[r]

# contains all character class information and functions
class Hero:
    def __init__(self):
        self.job = None
        self.level = 1
        self.exp = 0
        self.expbar = 0
        self.health = 0
        self.health_max = 0
        self.mana = 0
        self.mana_max = 0
        self.attk = 0

    # hero stats as string format
    def __str__(self):
        return (f'⬥ {self.job}\n⬥ LV:{self.level}\n⬥ HP:{self.health}/{self.health_max}\n⬥ MP:{self.mana}/{self.mana_max}\n⬥ ATK:{self.attk}\n⬥ XP:{self.exp}/{self.expbar}')

    # hero stats into a list
    def hero_stats(self):
        stat = [{
            "job": self.job,
            "level": self.level,
            "exp": f'{self.exp}/{self.expbar}',
            "health": f'{self.health}/{self.health_max}',
            "mana": f'{self.mana}/{self.mana_max}',
            "attk": self.attk
            }]
        return stat

    # hero stats displayed using tabulate
    def hero_table(self):
        print(tabulate(self.hero_stats(), headers="keys", tablefmt="grid"))

    # stats used for battles only
    def hero_battle_stat(self):
        stat = [{
            "health": self.health,
            "health_max": self.health_max,
            "mana": self.mana,
            "mana_max": self.mana_max,
            "attk": self.attk
        }]
        return stat

    # only run on initial class selection
    def choose_job(self, job):
        valid_jobs = ("mage", "warrior")
        job_ck = job.lower().strip()
        if job_ck in valid_jobs:
            if job_ck == "mage":
                self.job = "Mage"
            if job_ck == "warrior":
                self.job = "Warrior"
            self.level_up(1)
        else:
            print("Invalid job")

    # function to add xp from fights. Triggers the level_up function
    def exp_gain(self, xp):
        self.exp += xp
        if self.exp >= self.expbar:
            self.level += 1
            print("YOU HAVE LEVELED UP!")
            self.exp = 0
            self.level_up(self.level)

    # Level character up from CSV. Also used to assign level 1 stats on class selection
    def level_up(self, level):
        if self.job == "Warrior":
            file = "warrior.csv"
        if self.job == "Mage":
            file = "mage.csv"
        with open(file) as c:
            character = csv.DictReader(c)
            for row in character:
                if int(row["level"]) == level:
                    self.expbar = int(row["xp"])
                    self.health += int(row["hp"])
                    self.health_max = int(row["hpx"])
                    self.mana += int(row["mp"])
                    self.mana_max = int(row["mpx"])
                    self.attk += int(row["attk"])
                    print(self)

    # damage calc
    def hero_damage(self, dmg):
        self.health -= dmg
        if self.health <= 0:
            print("You have died!")
            sys.exit("GAME OVER!")
        print(f'{self.health}/{self.health_max}HP')

    # healing calc and notices
    def hero_healing(self, heal):
        self.health += heal
        if self.health >= self.health_max:
            self.health == self.health_max
            print(f'{self.health}/{self.health_max}HP, fully healed')
        else:
            print(f'{self.health}/{self.health_max}HP')

    def hero_attack(self):
        return self.attk

def main():
    story = Story()
    room = Rooms()
    hero = Hero()

    # select initial class
    while hero.job == None:
        print("Welcome to the dungeon!")
        print("Are you a Mage or Warrior?")
        choose = input("class: ")
        ## sleep(1)
        hero.choose_job(choose)

    #  load first room
    while story.progress == None:
        sleep(1)
        print("Your adventure starts here!")
        story.progress = "1"

    # loop until story reaches end point branch 0
    while story.progress != "0":
        room.open_room(story.progress)
        sleep(1)
        if room.mon_stats != []:
            print(room)
            if battle_request(room.mon_stats):
                room.mon_stats, herostats, battle_exp = battling(hero.hero_battle_stat(), room.mon_stats)
                # update hero values
                hero.health = herostats[0]["health"]
                hero.mana = herostats[0]["mana"]
                # check if character has leveled up
                sleep(1)
                print(f'You earned {battle_exp}XP!')
                hero.exp_gain(battle_exp)
                sleep(1)
            print("You have defeated all the monsters")
            sleep(1)
            hero.health, hero.mana = recovery(hero.health, hero.health_max, hero.mana, hero.mana_max)
            sleep(1)
        print("Moving to next room")
        story.progress = room.room_branch

    if story.progress == "0":
        print("You have completed the adventure!")

# seperates the battle or flee request
def battle_request(encounter):
    if encounter != []:
        while True:
            sleep(1)
            reply = input("Do you want to fight the monsters Y/N?: ").lower().strip()
            if reply == "y":
                print("Lets battle!")
                sleep(1)
                return True
            if reply == "n":
                sys.exit("You have fled the dungeon\nYour adventure is over")

# function handling battles. Pass in character attack and monster table.
def battling(hero, monster):
    battle_exp = 0
    while monster != []:
        hero_turn = True
        while hero_turn == True:
            sleep(1)
            print(tabulate(monster, headers="keys", tablefmt="grid"))
            sleep(0.5)
            attack_stat = hero[0]["attk"]
            choice = input("What would you like to do?\n1.Attack\n2.Spell\n3.Flee\n4.Stats\n").strip()
            # sum exp from defeated monsters
            if choice == "1":
                monster, exp_sum = make_attack(monster, attack_stat)
                battle_exp += exp_sum
                hero_turn = False
            if choice == "2":
                monster, hero, exp_sum = cast_spell(monster, hero)
                battle_exp += exp_sum
                hero_turn = False
            if choice == "3":
                sys.exit("You flee the dungeon!\nGame over!")
            if choice == "4":
                print(tabulate(hero, headers="keys", tablefmt="grid"))
            if choice not in ["1", "2", "3", "4"]:
                print("Invalid choice")
        if monster != []:
            hero = monster_attack(monster, hero)
    # tuple with adjusted values
    return monster, hero, battle_exp

# validation for battle targeting
def make_attack(monster, damage):
    while True:
        target = input("Which monster do you want to attack? ")
        battle_exp = 0
        valid_targets = []
        for row in monster:
            valid_targets.append(row["no"])
        if target.isdigit():
            if int(target) in valid_targets:
                for row in monster:
                    if row["no"] == int(target):
                        row["hp"] -= damage
                        print(f'You deal {damage} damage to {row["name"]}!')
                        # check if monster defeated, delete row and add exp
                        if row["hp"] <= 0:
                            print(f'You have defeated {row["name"]}!')
                            battle_exp += row["exp"]
                            monster.remove(row)
                return monster, battle_exp
            else:
                print("Invalid target (type number)")
        else:
            print("Wrong input")

def cast_spell(monster, hero):
    while True:
        choice = input("Cast a spell:\n1.Heal 10HP 3MP \n2.Zap 20Dmg 2MP\n")
        options = ["1", "2"]
        battle_exp = 0
        if choice not in options:
            print("Invalid choice")
        # heal spell
        if choice == "1":
            # check mana (min 3)
            sleep(0.5)
            if hero[0]["mana"] < 3:
                print("Not enough mana. Your spell fails!")
                return monster, hero
            hero[0]["mana"] -= 3
            print("You cast Heal!")
            hero[0]["health"] += 10
            # stop health going above max
            if hero[0]["health"] > hero[0]["health_max"]:
                hero[0]["health"] = hero[0]["health_max"]
            print(tabulate(hero, headers="keys", tablefmt="grid"))
            return monster, hero, battle_exp
        if choice == "2":
            sleep(0.5)
            # check mana (min 2)
            if hero[0]["mana"] < 2:
                print("Not enough mana. Your spell fails!")
                return monster, hero, 0
            hero[0]["mana"] -= 2
            # treat as attack with set damage
            target = input("Which monster do you want to attack? ")
            valid_targets = []
            for row in monster:
                valid_targets.append(row["no"])
            if target.isdigit():
                if int(target) in valid_targets:
                    for row in monster:
                        if row["no"] == int(target):
                            row["hp"] -= 25
                            print(f'You deal 20 damage to {row["name"]}!')
                            # check if monster defeated, delete row and add exp
                            if row["hp"] <= 0:
                                print(f'You have defeated {row["name"]}!')
                                battle_exp += row["exp"]
                                monster.remove(row)
                    return monster, hero, battle_exp
                else:
                    print("Invalid target")
            else:
                print("Invalid target")

def monster_attack(monster, hero):
    sleep(1)
    for row in monster:
        sleep(0.5)
        print(f'• {row["name"]} attacks you with {row["attk"]} for {row["dmg"]} damage!')
        hero[0]["health"] -= int(row["dmg"])
        print(f'⬦ You have {hero[0]["health"]}/{hero[0]["health_max"]}HP')
        if hero[0]["health"] < 1:
            sys.exit("Your hero has died. Game over!")
    return hero

def recovery(hp, hpx, mp, mpx):
    hp_rec = int(hpx/2)
    mp_rec = int(mpx/2)
    while True:
        choice = input(f'Do you want to recover {hp_rec}HP or {mp_rec}MP?').lower().strip()
        if choice == "hp":
            hp += hp_rec
            if hp > hpx:
                hp = hpx
            return hp, mp
        if choice == "mp":
            mp += mp_rec
            if mp > mpx:
                mp = mpx
            return hp, mp
        else:
            print("Invalid choice, HP or MP")

if __name__ == "__main__":
    main()


import pygame
import sys
from pygame.locals import *
from PIL import Image
from number_reader import Reader

pygame.init()

screen_size = 500
screen = pygame.display.set_mode((screen_size, screen_size+75))
clock = pygame.time.Clock()
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (73, 159, 104)
blue = (134, 187, 216)
dark_blue = (45, 49, 66)
mouse_position = None
dragging_mouse = False
drawing = False
screen.fill(black)

def make_text(font_size, label, color, background_color, x_offset=0, y_offset=0):
    text = pygame.font.SysFont('silomttf', font_size)
    text_surf = text.render(label, 1, color, background_color)
    x = (screen_size-text_surf.get_width())//2 + x_offset
    y = (screen_size-text_surf.get_height())//2 + y_offset
    return screen.blit(text_surf, (x, y))

def read_num():
    # just call the other script for reading numbers
    guessing = True
    rect = pygame.Rect(0, 0, screen_size, screen_size)
    sub = screen.subsurface(rect)
    pygame.image.save(sub, 'number.png')
    reader = Reader('mnist.pt', 'number.png')
    digit_guess = reader.read()
    print(digit_guess)

    circle = pygame.draw.circle(
        screen, green, (screen_size//2, screen_size//2), screen_size//2-50, 0)
    text = "did you guess %s?" % digit_guess

    while guessing:
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        make_text(40, text, blue, green)
        y = make_text(40, 'yeah', green, blue, x_offset=-75, y_offset=100)
        n = make_text(40, 'nope', green, blue, x_offset=75, y_offset=100)

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
            if y.collidepoint(pos) or n.collidepoint(pos):
                guessing = False
                screen.fill(dark_blue)
                break
        pygame.display.update()
    main_loop()

def drawCircle(pos):
    if pos is not None and pos[1] <= screen_size:
        pygame.draw.circle(screen, white, pos, 30, 0)

def intro():
    global drawing
    intro_running = True
    screen.fill(dark_blue)
    while intro_running:
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        make_text(100, 'digits.ai', blue, None)
        b = make_text(50, 'start', blue, green, x_offset=0, y_offset=150)

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
            if b.collidepoint(pos):
                intro_running = False
                drawing = True
                screen.fill(dark_blue)
                break

        pygame.display.update()

def main_loop():
    # function was tryna make it's own local mouse_position variable, so I had to point
    # it to the right one (the global one)
    global mouse_position, dragging_mouse, drawing
    running = True

    g = make_text(30, 'guess', blue, green, x_offset=0,
                  y_offset=screen_size//2+55)

    while running:
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse_position = event.pos
            if mouse_position[1] < screen_size:
                dragging_mouse = True
            elif g.collidepoint(mouse_position):
                read_num()
                drawing = False
        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                dragging_mouse = False
        elif event.type == pygame.MOUSEMOTION:
            if dragging_mouse:
                mouse_position = event.pos
        if drawing:
            drawCircle(mouse_position)

        pygame.display.update()
        clock.tick(50)

intro()
main_loop()
pygame.quit()
sys.exit()


import requests

MONTH2NUMBER = {
    "January": 1,
    "February": 2,
    "March": 3,
    "April": 4,
    "May": 5,
    "June": 6,
    "July": 7,
    "August": 8,
    "September": 9,
    "October": 10,
    "November": 11,
    "December": 12
}

# Element '0' is empty, because this needs to associate the month number as in MONTH2NUMBER
NUMBER2MESE = ["", "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"]

def getWeatherCsv(city, year, month, filename=None):
    """
    This program is used to download weather data.
    The input parameters are:
    - city: name of the city (str)
    - year: int/str
    - month: can be in italian, english (str) or number (int)
    - filename: (str) optional file name

    The function returns the file name
    """

    base_url = "https://www.ilmeteo.it/portale/archivio-meteo/"      #Torino/2018/Dicembre?format=csv

    cityname = city.capitalize()

    if isinstance(month, int):
        monthNum = month
        mese = NUMBER2MESE[month]
    elif isinstance(month, str):
        if month in MONTH2NUMBER.keys():
            monthNum = MONTH2NUMBER[month.capitalize()]
            mese = NUMBER2MESE[monthNum]
        elif month in NUMBER2MESE:
            monthNum = NUMBER2MESE.index(month.capitalize())
            mese = month
        else:
            raise ValueError("Invalid month!")
    else:
        raise ValueError("Invalid month!")

    anno = str(year)

    if filename is None:
        filename = "csv_ilMeteo/" + cityname + '-' + anno + '-' + str(monthNum).zfill(2) + mese + '.csv'

    full_url = base_url + cityname + '/' + anno + '/' + mese + '?format=csv'

    r = requests.get(full_url)

    content = r.content

    with open(filename, 'wb') as f:
        f.write(content)
        f.close()

    return filename

if __name__ == "__main__":
    getWeatherCsv("Torino", 2016, "May")


from flask import *
from models import *

'''
Action types:

1 - Add
2 - Remove
3 - Modify
4 - View
5 - Everything

Flow should be something like this:

1. Get user
2. Is the user an admin? Open the gate
3. Does the user have permission to do this?
    a. Yes: open the gate
    b. No: gtfo

'''

def makeAdmin(user_id, account_id):
    permission = Permission(account_id, user_id, 99, 5)
    db.session.add(permission)
    db.session.commit()
    return 1

def addPermission(user_id, account_id, permission_type, permission, team_id=0):
    if team_id != 0:
        permission = Permission(account_id, user_id, permission_type, permission, team_id=team_id)
        db.session.add(permission)
        db.session.commit()
    else:
        permission = Permission(account_id, user_id, permission_type, permission)
        db.session.add(permission)
        db.session.commit()
    return 1

def getPermissions(user_id, account_id, context, team_id=0):
    if team_id !=0:
        permissions = Permission.query.filter_by(user_id=user_id).filter_by(account_id=account_id).filter_by(team_id=team_id).filter_by(permission_type=context).all()
    else:
        permissions = Permission.query.filter_by(user_id=user_id).filter_by(account_id=account_id).filter_by(permission_type=context).all()
    return permissions

def checkPermissions(permissions, action, permission_type):
    action = int(action)
    for permission in permissions:
        if permission.permission_type == permission_type and permission.permission == action:
            return True
    return False

def checkSemiAdmin(user_id, account_id, context, team_id=0):
    if team_id != 0:
        permission = Permission.query.filter_by(user_id=user_id).filter_by(account_id=account_id).filter_by(permission_type=context).filter_by(team_id=team_id).filter_by(permission=5).first()
    else:
        permission = Permission.query.filter_by(user_id=user_id).filter_by(account_id=account_id).filter_by(permission_type=context).filter_by(permission=5).first()
    if permission:
        return True
    else:
        return False

def checkAdmin(user_id, account_id):
    check = Permission.query.filter_by(account_id=account_id).filter_by(user_id=user_id).filter_by(permission_type=99).first()
    if check:
        # yep, its an admin
        return True
    else:
        # nope, its a dirty user!
        return False

def teamGatekeeper(user_id, team_id, account_id, action):
    # check perms
    is_admin = checkAdmin(user_id, account_id)
    if is_admin:
        # its an admin, open gate
        return True
    else:
        # proceed
        context_admin = checkSemiAdmin(user_id, account_id, 1, team_id=team_id)
        if context_admin:
            # hes a semi admin, open gate
            return True
        else:
            # proceed
            permissions = getPermissions(user_id, account_id, 1, team_id=team_id)
            gatekeeper_status = checkPermissions(permissions, action, 1)
            if gatekeeper_status:
                # if permission found, open gate
                return True
            else:
                # nope, no dice, gate stays closed
                return False

def accountGatekeeper(user_id, account_id, action):
    # check perms
    is_admin = checkAdmin(user_id, account_id)
    if is_admin:
        # its an admin, open gate
        return True
    else:
        # proceed
        context_admin = checkSemiAdmin(user_id, account_id, 2)
        if context_admin:
            # hes a semi admin, open gate
            return True
        else:
            # proceed
            permissions = getPermissions(user_id, account_id, 2)
            gatekeeper_status = checkPermissions(permissions, action, 2)
            if gatekeeper_status:
                # if permission found, open gate
                return True
            else:
                # nope, no dice, gate stays closed
                return False


# from timemanager import Timemanager
import time

class Timemanager:

    # def __init__(self):
        # self.tickertape = None
        # self.weather = None
        # self.clockface = None
        # now = time.localtime()
        # self.lastRefreshedTime = 0
        # self.lastRefreshedNews = 0
        # self.lastRefreshedWeather = 0

    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Timemanager, cls).__new__(cls)
        return cls.instance

    @staticmethod
    def getInstance():
        if Timemanager.instance is None:
            return Timemanager()

        return Timemanager.instance

    def setTickerTape(self,tickertape):
        Timemanager().tickertape = tickertape

    def setWeather(self,weather):
        Timemanager().weather = weather

    def setClockFace(self,clockface):
        Timemanager().clockface = clockface

    def updateInstance(self, dt):
        now = time.localtime()
        hours = now[3]
        minutes = now[4]

        #CLOCK
        Timemanager().clockface.setTime(now)
        if hours >= 18 or hours <=7:
            Timemanager().clockface.setColor(0x200000)
        else:
            Timemanager().clockface.setColor(0x006600)

        # #NEWS
        if Timemanager().tickertape.getLastRefreshed() + 3 <= hours or Timemanager().tickertape.getLastRefreshed() > hours:
            Timemanager().tickertape.setLastRefreshed(hours)
            Timemanager().tickertape.getArticles()
            print("Refreshing articles")

        if hours >=20 or hours <=7:
          Timemanager().tickertape.fadeOff()
          Timemanager().weather.setOff()
        else:
          Timemanager().tickertape.fadeIn()
          Timemanager().weather.setOn()

        #WEATHER
        # print(f"lrw:{Timemanager().weather.getLastRefreshed()} minutes:{minutes}")
        if Timemanager().weather.getLastRefreshed() + 30 <= minutes or Timemanager().weather.getLastRefreshed() > minutes:
            print("Refreshing Weather")
            Timemanager().weather.setLastRefreshed(minutes)
            Timemanager().weather.getWeather()

        return


import json
import h5py
import os
from os.path import dirname
import cv2
import numpy as np
import pycocotools
import random
import detectron2.data.transforms as T
import scipy.io as scio
from detectron2.structures import BoxMode
import argparse

def get_particular_files(dir, end = 'depth.png'):
    all_files = os.listdir(dir)
    p_files = []
    for file in all_files:
        if file.endswith(end):
            p_files.append(file)
    return p_files

def get_dicts(args):
    idx = 0
    dataset_dicts = []
    depth_dir = os.path.join(os.getcwd(), args.name, args.phase, 'gray')
    seg_dir = os.path.join(os.getcwd(), args.name, args.phase, 'label')
    meta_dir = os.path.join(os.getcwd(), args.name, 'meta')

    for file in os.listdir(depth_dir):
        record = {}
        ## occulusion ##
        meta_path = os.path.join(meta_dir, file.split('.')[0]+'.mat')
        meta = scio.loadmat(meta_path)
        print(file)
        occulist = meta['oc'][0]
        depth_path = os.path.join(depth_dir, file)
        seg_path = os.path.join(seg_dir, file)
        record['file_name'] = depth_path
        record['image_id'] = idx
        idx += 1
        a = cv2.imread(depth_path)
        height, width, _ = a.shape
        record['height'] = height
        record['width'] = width

        seg_img = cv2.imread(seg_path)[:,:,0]
        seg_ids = np.unique(seg_img)
        # seg_img = file['label'][:]
        # seg_ids = np.unique(seg_img)

        seg_ids = [id for id in seg_ids if id != 0]
        objs = []
        for id in seg_ids:
            if id > len(occulist)-1:
                continue
            occ_r = occulist[id]
            bit_mask = (seg_img == id)
            # cv2.imshow('a', bit_mask.astype('uint8')*255)
            # cv2.waitKey(0)
            y_idxs, x_idxs = np.where(bit_mask == True)
            size_label = np.sum(bit_mask == True)

            if (y_idxs.size != 0) and (x_idxs.size != 0) and (occ_r > args.oc):
                rle = pycocotools.mask.encode(np.asarray(bit_mask, order="F"))
                rle['counts'] = rle['counts'].decode()
                obj = {
                    "bbox": [int(np.min(x_idxs)), int(np.min(y_idxs)), int(np.max(x_idxs)), int(np.max(y_idxs))],
                    "bbox_mode": BoxMode.XYXY_ABS,
                    "segmentation": rle,
                    "category_id": 0,
                    "occulusion": occ_r
                }
                objs.append(obj)
        record["annotations"] = objs
        dataset_dicts.append(record)

    return dataset_dicts

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--phase', default='train')
    parser.add_argument('--name', default='09')
    parser.add_argument('--oc', default=0.9)
    args = parser.parse_args()
    out_dir = os.path.join(args.name, 'json')
    os.makedirs(out_dir, exist_ok=True)
    jname = args.phase + '.json'
    jdict = get_dicts(args)
    with open(out_dir+'/'+ jname,'w') as f:
        json.dump(jdict, f)
        print("json file: %s accomplished!"%jname)


import Logger as lg

from Data.View.BaseDataView import BaseDataView
from Data.View.FilterItem import FilterItem
from Data.Filter.BaseFilter import BaseFilter

from typing import List
class FilterDataView(BaseDataView):
    def __init__(self):
        super().__init__(['ID','Type','Settings'])

    def load_data(self, filters: List[BaseFilter]):
        try:
            self.clear_datalist()

            for filter in filters:
                self.add_item(filter.uid, filter.get_type_value(), filter.get_settings_value())

            self.refresh_dataframe()
        except Exception as err:
            lg.log_error(f'Unable to load filter data: {err}')

    def add_item(self, filter_id: str, type: str, settings: str):
        self.datalist.append(FilterItem(filter_id, type, settings))

    def refresh_dataframe(self):
        self.clear_dataframe()

        if len(self.datalist) > 0:
            for item in self.datalist:
                self.dataframe = self.dataframe.append({
                                                        "UID": item.uid,
                                                        "Type": item.type,
                                                        "Settings": item.settings,
                                                        "Selected": item.selected,
                                                        "Checked": item.checked,
                                                    }, ignore_index=True)

            # If no items are selected,
            if len(self.dataframe.loc[self.dataframe["Selected"] == True]) == 0:
                # set the first one as selected.
                self.dataframe.at[0, 'Selected'] = True


import cv2
import numpy as np
from tkinter import Tk
from tkinter.filedialog import askopenfilename

Tk().withdraw()
filename = askopenfilename()

Img = cv2.imread(filename)
Img = cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)

Css = open("A.css",'w+')

Css.write(".Img\n{\nwidth: 1px;\nheight: 1px;\nbox-shadow:\n")

for i in range(len(Img)):
    for j in range(len(Img[0])):
        if i == len(Img)-1 and j == len(Img[0])-1:
            Css.write(str(j) + "px " + str(i) + "px rgb(" + str(Img[i][j][0])+ ',' + str(Img[i][j][1]) + ',' + str(Img[i][j][2]) + ");\n")
        else:
            Css.write(str(j) + "px " + str(i) + "px rgb(" + str(Img[i][j][0])+ ',' + str(Img[i][j][1]) + ',' + str(Img[i][j][2]) + "),\n")

Css.write("}")
Css.close()

html = open("A.html",'w+')

html.write('<link rel="stylesheet" href="A.css">\n

')
html.close()


import torch
from torch import nn as nn
from torch.autograd import Function
from typing import Tuple

from ..ball_query import ball_query
from . import group_points_ext
from .group_points import GroupAll, GroupingOperation

class QueryAndGroupV2(nn.Module):
    """Query and Group. 修改的地方主要在于 L109 多了一个self.return_triple

    Groups with a ball query of radius

    Args:
        max_radius (float): The maximum radius of the balls.
        sample_num (int): Maximum number of features to gather in the ball.
        min_radius (float): The minimum radius of the balls.
        use_xyz (bool): Whether to use xyz.
            Default: True.
        return_grouped_xyz (bool): Whether to return grouped xyz.
            Default: False.
        normalize_xyz (bool): Whether to normalize xyz.
            Default: False.
        uniform_sample (bool): Whether to sample uniformly.
            Default: False
        return_unique_cnt (bool): Whether to return the count of
            unique samples.
            Default: False.
    """

    def __init__(self,
                 max_radius,
                 sample_num,
                 min_radius=0,
                 use_xyz=True,
                 return_grouped_xyz=False,
                 normalize_xyz=False,
                 uniform_sample=False,
                 return_unique_cnt=False,
                 return_triple=False):
        super(QueryAndGroupV2, self).__init__()
        self.max_radius = max_radius
        self.min_radius = min_radius
        self.sample_num = sample_num
        self.use_xyz = use_xyz
        self.return_grouped_xyz = return_grouped_xyz
        self.normalize_xyz = normalize_xyz
        self.uniform_sample = uniform_sample
        self.return_unique_cnt = return_unique_cnt
        if self.return_unique_cnt:
            assert self.uniform_sample
        self.return_triple = return_triple

    def forward(self, points_xyz, center_xyz, features=None):
        """forward.

        Args:
            points_xyz (Tensor): (B, N, 3) xyz coordinates of the features.
            center_xyz (Tensor): (B, npoint, 3) Centriods. 采样的中心定位点
            features (Tensor): (B, C, N) Descriptors of the features.

        Return：
            Tensor: (B, 3 + C, npoint, sample_num) Grouped feature.
        """
        idx = ball_query(self.min_radius, self.max_radius, self.sample_num,
                         points_xyz, center_xyz)

        if self.uniform_sample:
            unique_cnt = torch.zeros((idx.shape[0], idx.shape[1]))
            for i_batch in range(idx.shape[0]):
                for i_region in range(idx.shape[1]):
                    unique_ind = torch.unique(idx[i_batch, i_region, :])
                    num_unique = unique_ind.shape[0]
                    unique_cnt[i_batch, i_region] = num_unique
                    sample_ind = torch.randint(
                        0,
                        num_unique, (self.sample_num - num_unique, ),
                        dtype=torch.long)
                    all_ind = torch.cat((unique_ind, unique_ind[sample_ind]))
                    idx[i_batch, i_region, :] = all_ind

        xyz_trans = points_xyz.transpose(1, 2).contiguous()
        # (B, 3, npoint, sample_num)
        grouped_xyz = grouping_operation(xyz_trans, idx)
        grouped_xyz -= center_xyz.transpose(1, 2).unsqueeze(-1)  # 返回的坐标都是减去中心点坐标之后的相对坐标了
        if self.normalize_xyz:
            grouped_xyz /= self.max_radius

        if features is not None:
            grouped_features = grouping_operation(features, idx)
            if self.use_xyz:
                # (B, C + 3, npoint, sample_num) 将xyz 和 feature 拼接到一起
                new_features = torch.cat([grouped_xyz, grouped_features],
                                         dim=1)
            else:
                new_features = grouped_features
        else:
            assert (self.use_xyz
                    ), 'Cannot have not features and not use xyz as a feature!'
            new_features = grouped_xyz

        ret = [new_features]
        if self.return_grouped_xyz:
            ret.append(grouped_xyz)
        if self.return_unique_cnt:
            ret.append(unique_cnt)
        if self.return_triple:
            ret.append(torch.cat([grouped_xyz, grouped_features], dim=1))
        if len(ret) == 1:
            return ret[0]
        else:
            return tuple(ret)

grouping_operation = GroupingOperation.apply


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

# @Author : 石张毅
# @Site :东莞实业投资控股集团 http://www.dgsy.com.cn
# @introduce:

import scrapy
import copy
from Qinghai.tools.utils import Utils_
from Qinghai.tools.DB_mysql import *
from Qinghai.tools.re_time import Times
import datetime
from Qinghai.tools.uredis import Redis_DB
class DgsySpider(scrapy.Spider):
    name = 'dgsy'
    allowed_domains = ['dgsy.com.cn']
    start_urls = ['http://dgsy.com.cn/']

    def __init__(self, *args, **kwargs ):
        super(DgsySpider, self).__init__()
        self.cates = [
            {"cate": "zbgg", "pages": 1},  # 招标公告

        ]
        self.t = Times()
        self.c_time = datetime.datetime.utcnow() - datetime.timedelta(days=5)

    def start_requests(self):
        url = "http://www.dgsy.com.cn//www/main.jsp?f_treeCode=00190001"

        yield scrapy.FormRequest(url=url, callback=self.parse)

    def parse(self, response):
        # print(response.text)

    #     # 列表页链接和发布时间
        list_url = response.xpath('//*[@class="article_list"]//dd/a/@href').getall()
        # print(list_url)
        titles = response.xpath('//*[@class="article_list"]//dd/a/strong[1]/text()').getall()
        # print(titles)
        pub_times = response.xpath('//*[@class="article_list"]//dd/a/strong[1]/preceding::span[1]/text()').getall()
        #循环遍历
        for href, title, pub_time in zip(list_url, titles, pub_times):
            # print(response.urljoin(href))
            item = {}
            item['link'] = response.urljoin(href.strip())
            item['title'] = title.strip()
            if item['title'] is None:
                continue
            PUBLISH = self.t.datetimes(pub_time)
            item['publish_time'] = PUBLISH.strftime('%Y-%m-%d')  # 发布时间
            item['uid'] = 'zf' + Utils_.md5_encrypt(item['title'] + item['link'] + item['publish_time'])
            ctime = self.t.datetimes(item['publish_time'])

            if Redis_DB().Redis_pd(item['uid']) is True:  # 数据去重
                print(item['uid'], '\033[0;35m <=======此数据已采集=======> \033[0m')
                return
            if ctime < self.c_time:
                print('文章发布时间大于规定时间，不予采集', item['link'])
                return
            yield scrapy.Request(item['link'], callback=self.parse_info, meta={'item': copy.deepcopy(item)},dont_filter=True)

    def parse_info(self, response):
        if response.status != 200:
            return
        item = response.meta['item']
        # 标题
        item['uuid'] = ''

        item['intro'] = ''
        item['abs'] = '1'
        from lxml import etree
        html = etree.HTML(response.text)
        div_data = html.xpath('//*[@class="content_con"]')
        item['content'] = etree.tostring(div_data[0], encoding='utf-8').decode()
        # 购买人
        item['purchaser'] = ''
        item['create_time'] = str(datetime.datetime.now().strftime('%Y-%m-%d'))
        # 代理人
        item['proxy'] = ''
        item['update_time'] = ''

        item['deleted'] = ''
        # 省 份
        item['province'] = '广东|东莞'
        # 基础
        item['base'] = ''
        item['type'] = '招采公告、文件'
        # 行业
        item['items'] = ''
        # 类型编号
        item['data_source'] = '00148'
        item['end_time'] = ''
        item['status'] = ''
        # 采购编号
        item['serial'] = ''

        yield item


from os.path import join
import pandas as pd
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules

"""Functions"""
def chromiumpercent(x):
    if x<0.13:
        return 0
    elif x>0.24:
        return 0
    else:
        return 1
def nickelpercent(x):
    if x<0.08:
        return 0
    elif x>0.18:
        return 0
    else:
        return 1
def molybdenumpercent(x):
    if x<0.016 or x>0.05:
        return 0
    else:
        return 1
def nitomo(x):
    if x<3.0 or x>6.0:
        return 0
    else:
        return 1
def crtomo(x):
    if x<4.0 or x>9.6:
        return 0
    else:
        return 1
def crtoni(x):
    if x<1.0 or x>2.0:
        return 0
    else:
        return 1

"""Load results"""
filename="sample.xlsx"
#linuxpath='/home/purity/Desktop/Data'
winpath='C:\\Users\\yyan\\Documents\\Data\\ICPMS\\Alldata'
filepath=join(winpath,filename)
#df=pd.read_excel(filepath,sheetname="Sheet2",parse_cols=6,index_col=0)
df_sample=pd.read_excel(filepath,sheetname="sample",parse_cols="A:H")
df_elements=pd.read_excel(filepath,sheetname="sample",parse_cols="J:AM")

"""Initial data cleaning for association later"""
data_3ele=df_elements[['Mo','Ni','Cr']]
data_3ele_ratio=pd.DataFrame(data=None,columns=['Ni/Mo','Cr/Mo','Cr/Ni'])
data_3ele_ratio['Ni/Mo']=data_3ele.Ni/data_3ele.Mo
data_3ele_ratio['Cr/Mo']=data_3ele.Cr/data_3ele.Mo
data_3ele_ratio['Cr/Ni']=data_3ele.Cr/data_3ele.Ni
#---Convert to zero and one-----
data_3ele_basket=data_3ele_ratio
data_3ele_basket['Ni/Mo']=data_3ele_basket['Ni/Mo'].apply(nitomo)
data_3ele_basket['Cr/Mo']=data_3ele_basket['Cr/Mo'].apply(crtomo)
data_3ele_basket['Cr/Ni']=data_3ele_basket['Cr/Ni'].apply(crtoni)
#basket["Mo%"]=basket["Mo%"].apply(molybdenumpercent)
#basket["Ni%"]=basket["Ni%"].apply(nickelpercent)
#basket["Cr%"]=basket["Cr%"].apply(chromiumpercent)
#newcolnames=["Ni/Mo3-6","Cr/Mo4-9.6","Cr/Ni1-2","Mo%1.6-5","Ni%8-18","Cr%13-24"]
#df.columns=newcolnames"""

"""Association rule"""
frequent_items=apriori(data_3ele_basket,min_support=0.005,use_colnames=True)
frequent_items=frequent_items.sort_values("support",ascending=False)
#rule_by_lift=association_rules(frequent_items,metric="lift",min_threshold=36)
#rule_by_lift=rule_by_lift.sort_values(["lift","confidence"],ascending=[False,False])
#rule_by_confidence=association_rules(frequent_items,metric="confidence",min_threshold=0.9)
#rule_by_confidence=rule_by_confidence.sort_values(["confidence","lift"],ascending=[False,False])

"""End of script"""
print("end of script")


#
# @lc app=leetcode.cn id=206 lang=python3
#
# [206] 反转链表
#

# @lc code=start
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head
        curr = head.next
        pre=head
        pre.next =None
        while curr is not None:
            next = curr.next
            curr.next = pre
            pre=curr
            curr= next

        return pre

# @lc code=end


import datetime

def str2time(time_raw, pattern):
    """pattern: %Y-%m-%d, %H:%M:%S"""
    try:
        return datetime.datetime.strptime(time_raw, pattern)
    except ValueError as _:
        return None

def time2str(date_time, pattern):
    """pattern: %Y-%m-%d, %H:%M:%S"""
    if not date_time:
        return None
    return date_time.strftime(pattern)


def maxSubArraySum(arr,N):
        import math
        ##Your code here
        """
        sumstore=[]
        temp=[]
        sumstore.append(max(arr))
        sumstore.append(max(arr))
        i=2
        while i<=N:
            temp=[]
            j=0
            while j<N:
                k=0
                ax=0
                while k<i:
                    if(j+k)<N:
                        ax=ax+arr[(j+k)]
                        k+=1
                    else:
                        break
                temp.append(ax)
                j+=1
            #print("temp for length ",i,temp)
            sumstore.append(max(temp))
            #print("sumstore for length ",i,sumstore)
            i+=1
        maxx=max(sumstore)
        return maxx
        """
        localmax=0
        globalmax=-math.inf
        i=0
        while i<N:
            localmax=max(arr[i],arr[i]+localmax)
            if localmax>globalmax:
                globalmax=localmax
            i+=1
        return globalmax
n=int(input("Enter a Natural number"))
array=[]
for i in range(0,n):
    element=int(input("Enter the number"))
    array.append(element)
Soln=maxSubArraySum(array,n)
print("Maximum sum is:",Soln)


import math

def hf(x):
	return math.cos(x)-x*math.sin(x)

def f(x, y, a):
	return y-hf(a)*(x-a)

alpha = 0
beta = 0

arquivo = open("arquivo.pts", 'w')

x_anterior = 0
y_anterior = 1
pontos_negativos = []

#Cálculo dos pontos no intervalo [-6:0] a partir do ponto ponto (0, f(x)).
while(beta >= -6):
	x_anterior = beta+0.1

	if(beta == 0):
		print("PONTO CONHECIDO")
		pontos_negativos.append(str(beta)+ " " + str(f(0, 1, beta)) + "\n")
		y_anterior = f(0, 1, beta)
	else:
		pontos_negativos.append(str(beta) + " " + str(f(x_anterior, y_anterior, beta)) + "\n")
		y_anterior = f(x_anterior, y_anterior, beta)

	beta -= 0.1

#Escrita em ordem crescente
for i in reversed(pontos_negativos):
	arquivo.write(i)

x_anterior = 0
y_anterior = 1

#Cálculo dos pontos no intervalo [0:6] a partir do ponto ponto (0, f(x)).
while(alpha <= 6):
	x_anterior = alpha-0.1

	if(alpha == 0):
		print("PONTO CONHECIDO")
		y_anterior = f(0, 1, alpha)
	else:
		arquivo.write(str(alpha) + " " + str(f(x_anterior, y_anterior, alpha)) + "\n")
		y_anterior = f(x_anterior, y_anterior, alpha)

	alpha += 0.1

arquivo.close()


import hashlib
from . import ureg

def hash_password(pw, salt):
    hasher = hashlib.sha256()
    hasher.update(f"{pw}{salt}".encode())
    return hasher.hexdigest()[:50]

def average_price(ingredients):
    """
    Assumes ingredients is a list of tuples of the form (quantity, units).
    It assumes all items in ingredients are of the same type.
    Returns the average ingredient price as a float and the unit as a string.
    """
    # Empty case
    if not ingredients:
        return (0, "")

    # Check if unit exists in registry. If not, skip.
    quantities = [ureg.Quantity(i[0], i[1]) for i in ingredients if i[1] in ureg]
    item_units = [item.units for item in quantities]
    # Determine most frequent unit in list. This will be our unit basis.
    freq_unit = max(set(item_units), key=item_units.count)
    return (
        sum([i.to(freq_unit).magnitude for i in quantities]) / len(quantities),
        str(freq_unit),
    )

def online_stats(data):
    """
    Calculates mean and variance in one pass.
    https://math.stackexchange.com/questions/198336/how-to-calculate-standard-deviation-with-streaming-inputs
    """
    means = [0] * len(data)
    variances = [0] * len(data)
    M2 = 0.0

    for i, x in enumerate(data):
        if i == 0:
            means[i] = x

        else:
            delta = x - means[i - 1]
            means[i] = means[i - 1] + delta / (i + 1)
            M2 += delta * (x - means[i])
            variances[i] = M2 / i

    return means, variances


import mysql.connector as mysql
con = mysql.connect(host="localhost", user="root", password="")
cursor = con.cursor()
cursor.execute("use studdb")
print("Welcome to student management portal...")

def insert():
    print("Provide your details")
    name = input("Enter your name: ")
    Branch = input("Enter your branch: ")
    class_year = input("Enter your academic year: ")
    fees = eval(input("Enter your fees: "))
    status = input("What is your status: ")
    contact = input("Enter your contact number: ")
    email = input("Enter your email: ")

    q = "insert into stud(Name, Branch, Class_year, Fees, Status, Contact, Email) values('" + \
        name+"', '"+Branch+"','"+class_year+"','" + \
        str(fees)+"','"+status+"', '"+contact+"', '"+email+"' )"
    cursor.execute(q)
    con.commit()
    print("Details are saved..")

def showAll():
    q = "select * from stud"
    cursor.execute(q)
    records = cursor.fetchall()
    for record in records:
        print(record)

def selectOne():
    name = input("Provide your name to get records: ")
    q = "select * from stud where name = '"+name+"'"
    cursor.execute(q)
    record = cursor.fetchone()
    print(record)

def change():
    id = input("Provide your Id: ")
    choice = input(
        "Select what you want to update: \nname, Branch, class_year, fees, status, contact, email or All:  ").lower()
    if (choice == "all"):
        name = input("Provide new name: ")
        branch = input("Enter new branch: ")
        class_year = input("Provide new Academic year: ")
        fees = input("Provide new fees: ")
        status = input("Enter new status: ")
        contact = input("Enter new contact number: ")
        email = input("Provide new email: ")
        q = "update stud set Name = '"+name+"', Branch = '"+branch+"', Class_year = '"+class_year+"', Fees = '" + \
            fees+"', Status = '"+status+"', Contact = '"+contact + \
            "', Email = '"+email+"' where id = '"+id+"'"
        cursor.execute(q)
        con.commit()
        print("Details updated...")
    elif (choice == "name"):
        name = input("Provide new name: ")
        q = "update stud set Name = '"+name+"' where id = '"+id+"'"
        cursor.execute(q)
        con.commit()
        print("Details updated...")
    elif (choice == "branch"):
        branch = input("Enter new branch: ")
        q = "update stud set Branch = '"+branch+"' where id = '"+id+"'"
        cursor.execute(q)
        con.commit()
        print("Details updated...")
    elif (choice == "Class_year"):
        class_year = input("Provide new Academic year: ")
        q = "update stud set Class_year = '"+class_year+"' where id = '"+id+"'"
        cursor.execute(q)
        con.commit()
        print("Details updated...")
    elif (choice == "Fees"):
        fees = input("Provide new fees: ")
        q = "update stud set Fees = '"+fees+"' where id = '"+id+"'"
        cursor.execute(q)
        con.commit()
        print("Details updated...")
    elif (choice == "Status"):
        status = input("Enter new status: ")
        q = "update stud set Status = '"+status+"' where id = '"+id+"'"
        cursor.execute(q)
        con.commit()
        print("Details updated...")
    elif (choice == "Contact"):
        contact = input("Enter new contact number: ")
        q = "update stud set Status = '"+contact+"' where id = '"+id+"'"
        cursor.execute(q)
        con.commit()
        print("Details updated...")
    elif (choice == "email"):
        email = input("Provide new email: ")
        q = "update stud set Email = '"+email+"' where id = '"+id+"'"
        cursor.execute(q)
        con.commit()
        print("Details updated...")

    else:
        print("Provide valid details!...")

def delete():
    name = input("Provide your name to delete your data: ")
    q = "delete from stud where Name = '"+name+"'"
    cursor.execute(q)
    con.commit()
    print("Records deleted...")

choice = int(input("What you want to do..\nEnter:-\n 1 to insert data\n 2 to get all the data\n 3 to update the data \
    \n 4 to select the specific data\n 5 to delete your data\n Select any one: "))
print()
if (choice == 1):
    insert()
elif (choice == 2):
    showAll()
elif (choice == 3):
    change()
elif (choice == 4):
    selectOne()
elif (choice == 5):
    delete()
else:
    print("Provid valid choice...")


import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms import Resize

from third_party.disttrans import *
from third_party.raster import exp
from third_party.composite import *

from utils.shared import args
from utils.shared import stroke_config as config

class Renderer(nn.Module):
    def __init__(self, image_size, canvas_size):
        """Initialize Differentiable Rasterizer.

        Args:
            image_size (int): Resolution of the image to generate
            canvas_size (int): Resolution of the grid to actually rasterize
            stroke_config (dict): Stroke configuration
            device (str, optional): Device. Defaults to 'cuda:0'.
        """
        super(Renderer, self).__init__()

        self.image_size = image_size
        self.device = args.device
        self.canvas_size = canvas_size
        if image_size == canvas_size:
            self.resize = lambda x: x
        else:
            self.resize = Resize(image_size)

        r = torch.linspace(-1, 1, canvas_size)
        c = torch.linspace(-1, 1, canvas_size)
        grid = torch.meshgrid(r, c)
        self.grid = torch.stack(grid, dim=2).to(self.device)

        self.set_sigma2(0.0)

    def set_sigma2(self, progress):
        """Anneals the sharpness of the rasterized stroke by the training progress.

        Args:
            progress (float): The overall progress in training, a value between 0 and 1.
        """
        ratio = config.power_f / config.power_i
        self.power = config.power_i * (ratio**progress)
        self.sigma2 = ((1 - ratio) * progress + ratio) * config.radius

    def reshape_params(self, stroke, background="keep"):
        assert background in ["keep", "remove", "only"]
        # the latent_to_linecoord process will map the input latent vector to control points
        bs = stroke["position"].shape[0]
        device = self.device
        n_back = config.n_back

        if background == "keep":
            nlines = config.n_lines
            idx_i = 0
            idx_f = nlines
        elif background == "remove":
            nlines = config.n_lines - n_back
            idx_i = 0
            idx_f = nlines
        elif background == "only":
            nlines = n_back
            if n_back == 0:
                idx_i = config.n_lines
            else:
                idx_i = -n_back
            idx_f = config.n_lines

        nsegments = config.n_segments
        coordpairs = config.coordpairs
        nc = config.n_color

        p_pos = stroke["position"][:, idx_i:idx_f]

        if "radius" not in stroke:  # use default thickness (1^2 for foreground, 5^2 for background)
            p_rad = torch.ones(bs, nlines, 1).to(device)
            if background == "keep":
                if n_back != 0:
                    p_rad[:, -n_back:] *= 25
            elif background == "only":
                p_rad *= 25
        else:
            p_rad = stroke["radius"][:, idx_i:idx_f] ** 2

        if "color" not in stroke:  # use default color (black)
            p_col = torch.zeros(bs, nlines, nc).to(device)
        else:
            p_col = stroke["color"][:, idx_i:idx_f]

        if "background" not in stroke:  # use default color (white)
            p_back = torch.ones(bs, nc).to(device)
        else:
            p_back = stroke["background"]

        lines = p_pos.view(bs, nlines, -1, 2)                                                           # [batch, nlines, npoints, 2]
        stacked_pos = [lines[:, :, coordpairs[:, i]] for i in range(coordpairs.shape[1])]
        lines_ = torch.stack(stacked_pos, dim=-2)                                                       # [batch, nlines, nsegments, ncoords, 2]
        if config.smooth and config.line_style == "bezier":
            # reflect control point vectors
            lines_[:, :, 1:, 1] = 2 * lines_[:, :, 1:, 0] - lines_[:, :, 1:, 1]

        lines_ = lines_.view(bs, nlines * nsegments, -1, 2)                                             # [batch, nlines*nsegments, ncoords, 2]
        sigma = p_rad.view(bs, -1, 1, 1).repeat_interleave(nsegments, dim=1) * self.sigma2              # [batch, nlines*nsegments, 1, 1]
        color = p_col.view(bs, nlines, nc, 1, 1).repeat_interleave(nsegments, dim=1)                    # [batch, nlines*nsegments, 3, 1, 1]
        background = p_back.view(bs, nc, 1, 1).expand(-1, -1, *self.grid.shape[:2])                     # [batch, 3, r, c]

        return lines_, sigma, color, background

    def create_euclidean_distance_square(self, lines):
        if config.line_style == "line":
            edt2 = line_edt2(lines, self.grid)

        elif config.line_style == "bezier":
            edt2 = curve_edt2_polyline(lines, self.grid, 10)

        elif config.line_style == "point":
            edt2 = point_edt2(lines.squeeze(2), self.grid)

        else:
            raise NotImplementedError(f"line style {config.line_style} not implemented")

        return edt2

    def rendering_reshaped_params(self, params, canvas=None):
        lines, sigma, color, background = params

        # Will overlay strokes on top of canvas and will optionally use the background color instead of canvas.
        if config.enable_b or canvas is None:
            canvas = background

        canvas = canvas.unsqueeze(1)

        distance_square = self.create_euclidean_distance_square(lines)                                  # [bs, nlines*nsegments, row, col]
        intensity = exp(distance_square, sigma, self.power)

        intensity = intensity.unsqueeze(2).repeat_interleave(config.n_color, dim=2)                     # [bs, nlines*nsegments, 3, row, col]
        rasters = color * intensity
        rasters = torch.cat([rasters, canvas], dim=1)

        # intensity without color
        intensity_ = torch.cat([intensity, torch.ones_like(canvas)], dim=1)
        linv = 1 - intensity_ + 1e-10
        images = over(rasters, linv, dim=1, keepdim=False)                                              # [bs, 3, row, col]

        return self.resize(images).clip(0, 1)

    def render_full(self, stroke):
        reshaped = self.reshape_params(stroke, background="keep")
        return self.rendering_reshaped_params(reshaped)

    def render_foreground(self, stroke, colored=True):
        if config.n_lines == config.n_back:
            return self.white_canvas(stroke["position"].shape[0])

        reshaped = self.reshape_params(stroke, background="remove")
        p, s, c, b = reshaped
        if not colored:
            c_ = torch.zeros_like(c)
            b_ = torch.ones_like(b)
            reshaped = p, s, c_, b_
        return self.rendering_reshaped_params(reshaped)

    def render_background(self, stroke):
        if config.n_back == 0:
            return self.white_canvas(stroke["position"].shape[0])

        reshaped = self.reshape_params(stroke, background="only")
        return self.rendering_reshaped_params(reshaped)

    def render_each_stroke(self, stroke):
        for key in stroke.keys():
            if stroke[key] is not None:
                stroke[key] = stroke[key].detach()

        results = []
        import copy
        for idx in range(config.n_lines - config.n_back):
            params_ = copy.deepcopy(stroke)
            c = params_["color"][:, idx]
            params_["color"] = 0.8 + params_["color"] * 0.2
            params_["color"][:, idx] = c

            permute = torch.arange(0, config.n_lines)
            permute[: idx + 1] -= 1
            permute[0] = idx

            params_["color"] = params_["color"][:, permute]
            params_["position"] = params_["position"][:, permute]

            reshaped = self.reshape_params(params_, background="remove")
            results.append(self.rendering_reshaped_params(reshaped))

        return results

    def white_canvas(self, batch_size):
        return torch.ones((batch_size, config.n_color, self.image_size, self.image_size)).to(self.device)

    def forward(self, stroke, sketch_type=["color", "black", "background", "foreground"]):
        sketch_fn = {
            "color": self.render_full,
            "black": lambda x: self.render_foreground(x, colored=False),
            "foreground": lambda x: self.render_foreground(x, colored=True),
            "background": self.render_background,
            "single": self.render_each_stroke,
        }

        if isinstance(sketch_type, list) or isinstance(sketch_type, tuple):
            return [sketch_fn[type_](stroke) for type_ in sketch_type]

        return sketch_fn[sketch_type](stroke)


__author__ = 'Neil Butcher'

from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal

from model_roles_all import AllRolesModel
from Rota_System.UI.Roles.commands_roles_sublist import CommandExcludeRole, CommandIncludeRole

class SelectionOfRolesModel(AllRolesModel):
    """
    used to manipulate a selection of the roles
    """

    commandIssued = pyqtSignal(QtGui.QUndoCommand)

    def __init__(self, all_roles_list, rolelist):
        AllRolesModel.__init__(self, all_roles_list)
        self.roleListSelection = rolelist
        rolelist.rolesChanged.connect(self.roles_changed)

    @QtCore.pyqtSlot()
    def roles_changed(self):
        self.reset()

    def flags(self, index):
        return QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid():
            return None
        if not ((role == QtCore.Qt.DisplayRole) | (role == QtCore.Qt.CheckStateRole)):
            return None

        if index.column() == 0:
            if role == QtCore.Qt.DisplayRole:
                return self.rolelist.roles[index.row()].description
            if role == QtCore.Qt.CheckStateRole:
                return self.roleListSelection.includes(self.rolelist.roles[index.row()])
            else:
                return QtCore.QVariant()
        else:
            return QtCore.QVariant()

    def setData(self, index, value, role=QtCore.Qt.EditRole):
        if not index.isValid():
            return False
        if not (role == QtCore.Qt.CheckStateRole):
            return False
        if index.column() == 0:
            if not self.data(index, role):
                command = CommandIncludeRole(self.roleListSelection, self.rolelist.roles[index.row()])
                self.commandIssued.emit(command)
            else:
                command = CommandExcludeRole(self.roleListSelection, self.rolelist.roles[index.row()])
                self.commandIssued.emit(command)
        else:
            return False
        return True


import sys
sys.stdin=open('hexaCode.txt')

T=int(input())
decryptor=['1123','']

for i in range(T):
    N, M = map(int, input().split())
    code=''
    for k in range(N):
        wholetext=input()[::-1]
        if wholetext.isdigit()==True:
            continue
        else:
            code=wholetext.replace('0','')
        print(code)


import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization
from tensorflow.keras.layers import MaxPool2D, GlobalAvgPool2D
from tensorflow.keras.layers import Add, ReLU, Dense
from tensorflow.keras import Model, layers
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler
from tensorflow.keras.callbacks import ReduceLROnPlateau

'''' citation =
@ONLINE {beansdata,
    author="Makerere AI Lab",
    title="Bean disease dataset",
    month="January",
    year="2020",
    url="https://github.com/AI-Lab-Makerere/ibean/"
}
'''
seed = 10
batch_size = 64
width = 500
height = 500
channel = 3
lr = 1e-3
epochs = 1
num_classes=3
# model_dir = "/Users/xavier/Documents/NTU/CZ4171/Assignment"
model_dir = "/home/FYP/xavi0007/iotNN"
device_name = tf.test.gpu_device_name()

def load_data():
    (ds_train, ds_test), ds_info = tfds.load(
    'beans',
    split=['train', 'validation'],
    shuffle_files=True,
    as_supervised=True,
    with_info=True,
    )

    return ds_train, ds_test, ds_info

def preprocess(ds_train,ds_test, ds_info):

    ds_train = ds_train.cache().shuffle(ds_info.splits['train'].num_examples)
    ds_train = ds_train.batch(batch_size)
    ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)

    ds_test = ds_test.batch(batch_size)
    ds_test = ds_test.cache().prefetch(tf.data.experimental.AUTOTUNE)

    return ds_train, ds_test

def lr_schedule(epoch):
    lr = 1e-3
    if epoch > 180:
        lr *= 0.5e-3
    elif epoch > 160:
        lr *= 1e-3
    elif epoch > 120:
        lr *= 1e-2
    elif epoch > 80:
        lr *= 1e-1
    print('Learning rate: ', lr)
    return lr

def model_convert_to_lite(saved_model_dir):
    # Convert the model
    converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
    tflite_model = converter.convert()

    # Save the model.
    with open('model.tflite', 'wb') as f:
        f.write(tflite_model)

def lr_schedule(epoch):
    lr = 1e-3
    if epoch > 180:
        lr *= 0.5e-3
    elif epoch > 160:
        lr *= 1e-3
    elif epoch > 120:
        lr *= 1e-2
    elif epoch > 80:
        lr *= 1e-1
    print('Learning rate: ', lr)
    return lr

def build_model():
    model = keras.models.Sequential([
    #augmentation layers
    keras.layers.experimental.preprocessing.RandomCrop(500, 500, seed = seed, input_shape=(500,500,3)),
    keras.layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"),
    keras.layers.experimental.preprocessing.Rescaling(1./255),
    keras.layers.experimental.preprocessing.RandomRotation(0.2),
    keras.layers.experimental.preprocessing.RandomZoom(0.2),
    keras.layers.Input(shape=(500,500,3)),
    keras.layers.Conv2D(filters=96, kernel_size=(11,11), strides=(4,4), activation='relu'),
    keras.layers.BatchNormalization(),
    keras.layers.MaxPool2D(pool_size=(3,3), strides=(2,2)),
    keras.layers.Conv2D(filters=256, kernel_size=(5,5), strides=(1,1), activation='relu', padding="same"),
    keras.layers.BatchNormalization(),
    keras.layers.MaxPool2D(pool_size=(3,3), strides=(2,2)),
    keras.layers.Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), activation='relu', padding="same"),
    keras.layers.BatchNormalization(),
    keras.layers.Conv2D(filters=384, kernel_size=(1,1), strides=(1,1), activation='relu', padding="same"),
    keras.layers.BatchNormalization(),
    keras.layers.Conv2D(filters=256, kernel_size=(1,1), strides=(1,1), activation='relu', padding="same"),
    keras.layers.BatchNormalization(),
    keras.layers.MaxPool2D(pool_size=(3,3), strides=(2,2)),
    keras.layers.Flatten(),
    keras.layers.Dense(4096, activation='relu'),
    keras.layers.Dense(4096, activation='relu'),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(num_classes, activation='softmax')
    ])

    return model

def model_predict(model, x_test,y_test):
    results = model.evaluate(x_test, y_test, verbose=1, batch_size=256)
    return results

def plot_graph(_history):

    acc = _history.history['accuracy']
    val_acc = _history.history['val_accuracy']
    loss = _history.history['loss']
    val_loss = _history.history['val_loss']

    plt.plot(range(1, len(loss) + 1), loss, label='Train')
    plt.plot(range(1, len(val_loss) + 1), val_loss, label='Test')
    plt.title('Model Loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend()
    filename_loss = "images/"+"_loss.png"
    plt.savefig(os.path.join(model_dir,str(filename_loss)))
    plt.close()

    # Save the plot for accuracies
    plt.plot(range(1, len(acc) + 1), acc, label='Train')
    plt.plot(range(1, len(val_acc) + 1), val_acc, label='Test')
    plt.title('Model Accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend()

    filename_acc = "images/"+"_acc.png"
    plt.savefig(os.path.join(model_dir, str(filename_acc)))
    plt.close()

def train_model(ds_train, ds_test, model):
    with tf.device(str(device_name)):

        optimizer = tf.keras.optimizers.Adam(learning_rate = lr_schedule(0))

        lr_scheduler = LearningRateScheduler(lr_schedule)

        lr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1),
                                    cooldown=0,
                                    patience=5,
                                    min_lr=0.5e-6)

        model.compile(optimizer=optimizer,
                    loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
                    metrics=['accuracy'])

        history = model.fit(
            ds_train,
            epochs=epochs,
            validation_data=ds_test,
            callbacks=[lr_reducer, lr_scheduler],
            verbose = 1
            )

    return model, history

def main():
    ds_train, ds_test, ds_info = load_data()
    print(ds_info)
    ds_train, ds_test = preprocess(ds_train,ds_test,ds_info)
    model = build_model()
    model, history = train_model(ds_train, ds_test, model)
    plot_graph(history)
    model.save(os.path.join(model_dir,str("ibean")))

if __name__ == "__main__":
    main()


import hou
import os
import shutil

########CONFIG ME HERE ###########

extension = ".rat"

############END CONFIG ############

def run():

    nodes = hou.selectedNodes()

    c = Converter(nodes)
    #Print Result
    c.finish()

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

#HelperClass
class Entry:
    texPath = ""
    node = ""
    parm = ""

    def __init__(self, path, node, parm):
        self.texPath = path
        self.node = node
        self.parm = parm

#Converter Class
class Converter():

    def __init__(self, nodes):
        self.textures = []
        self.errors = []
        self.count = 0
        self.nodes = nodes

        #Convert stuff
        self.gatherTextures()
        self.convertFiles()

        return

    #Returns Count
    def getCount(self):
        return self.count

    #Gathers Textures to be changed
    def gatherTextures(self):

        for n in self.nodes:
            if n.type().name() == "texture::2.0" or n.type().name() == "principledshader::2.0" or n.type().name() == "displacetexture" :
                for p in n.parms():
                    if p.parmTemplate().type() == hou.parmTemplateType.String:
                        # Get Parm as String
                        s = p.evalAsString()
                        occur = s.rfind("/")
                        #Filter out non Files - go to next if none
                        if occur == -1:
                            continue
                        if s.startswith(hou.getenv("HSITE")):   #Leave if already in place
                            continue
                        if not os.path.exists(s):
                            #global errors
                            s = (s + " does not exist \n")
                            self.errors.append(s)
                            continue

                        #Append string to Converted List
                        if not s.endswith('.rat'):
                            self.textures.append(Entry(s, n, p))

            if n.type().name() == "materialbuilder":
                #Create a new Instance of this Class for SubChildren
                ch = Converter(n.children())
                self.count += ch.getCount()

    #Converts Files
    def convertFiles(self):

        cop = hou.node("/img")
        img = cop.createNode("img", "tmp")

        read = img.createNode("file")
        rop = img.createNode("rop_comp")
        rop.setInput(0,read,0)
        rop.parm("trange").set(0)

        #Convert Stuff
        for f in self.textures:
            filename = f.texPath
            read.parm("filename1").set(filename)

            #Change Filename
            namePos = filename.rfind(".")
            name = filename[:namePos]
            name += extension

            #Render
            rop.parm("copoutput").set(name)
            rop.parm("execute").pressButton()

            #Change Original Material/Texture
            f.node.parm(f.parm.name()).set(name)

            self.count += 1

        #Cleanup
        img.destroy()

    #Cleanup after Converting
    def finish(self):
        text = str(self.count) + " Textures converted. \n "

        if errors:
            text = self.printErrors(text)
        hou.ui.displayMessage(text)

    #Print Errors if happend - no exception to continue other files
    def printErrors(text):

        text = text + "Errors: \n"
        msg = ""
        for s in errors:
            msg = msg + s + "\n"

        text = text + msg
        return text