from node1 import *
import turtle
class linked_list:
    def __init__(self):
        self.head=None
        self.tail=None
        self.size=0

    def size(self):
        self.size=size
        print (self.size)

    def insertfirst(self,elem):
        new=node(elem)
        new.next=self.head
        self.head=new
        self.size=self.size+1
        print (self.head.data)

    def insertlast(self,elem):
        new=node(elem)
       #new.next=None
        self.tail.next=new
        self.tail=new
        new.next=None
        self.size=self.size+1
        print (self.tail)

    def first(self):
        if self.isempty()==1:
            print ("the list is empty")
        else:
            print ("first element is ")
            print (self.head.data)

    def last(self):
        p=self.head
        while p!=None:
            if p.next==None:
                print ("last element is ")
                print (p.data)
            p=p.next

    def removefirst(self):
        if self.isempty()==1:
            print ("list is empty")
        else:
            print ("the firstelement removed  is:",self.head.data)
            self.head=self.head.next
            self.size=self.size-1
            #n=node(self.head)

    #def removelast(self):
    def insertafter(self,p,elem):
        node1=self.head
        while(node1):
            if(node1.data==p):
                new=node(elem)
                x=node1.get_next()
                #new.data=elem
                new.next=x
                node1.next=new
                self.current=new
                break
            else:
                node1=node1.next
                self.size=self.size+1
        print ("the element",elem," is insertd after",p)

    def find(self,elem):
        current = self.head
        found = False
        while current != None and not found:
            if current.get_data() == elem:

                found = True
            else:
                current = current.get_next()
        if found==False:
            print ("false")
            print ("the element "),elem,("is not found")
        else:
             print ("true")
             print ("the element ",elem,"is found")

    def display(self):
        print("DISPLAY:")
        p=self.head
        while p.next!=None:
            print (p.data)
            p=p.next
        print (p.data)

    def isempty(self):
        if self.head==None:
            return 1
        else:
            return 0

    def remove(self,elem):
        current = self.head
        previous = None
        found = False
        while not found:
            if current.get_data() == elem:
                found = True
            else:
                previous = current
                current = current.get_next()
        if previous == None:
            self.head = current.get_next()
        else:
            previous.set_next(current.get_next())

        print ("the element ",elem,"is removed")

    def removeafter(self,elem):
         current = self.head
         found = False
         while current != None and not found:
             if current.get_data() == elem:
                 found = True

                 print ("the elemnt found is"),elem
             else:
                 current = current.get_next()

         if found==True:
             p=current.get_next()
             self.head=p.get_next()

             print ("the element is removed")
         else:
             print ("the element is not found")
    def disturtle(self):
        node1 = self.head
        i=0
        while (node1):
            if(node1.next!=None):
                i+=10
                turtle.goto(5*i,0)
            else:
                i+=10
                turtle.goto(5*i,0)
            turtle.pendown()
            turtle.write(node1.data)
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)
            node1=node1.next
    def tutrremove(self,elem):
        node1 = self.head

        count=0
        while(node1):
            if(node1.next!=None):
                if(count==elem):
                    turtle.pendown()
                    turtle.forward(30)
                    turtle.pencolor("white")
                    turtle.left(90)
                    turtle.forward(30)
                    turtle.left(90)
                    turtle.forward(30)
                    turtle.left(90)
                    turtle.forward(30)
                    turtle.left(90)
                    turtle.penup()
                    turtle.pencolor("black")
                    node1=node1.next

                #turtle.goto(50*count,0)
            else:

                turtle.goto(50*count,0)
            turtle.penup()
            #turtle.write(node1.data)
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)
            turtle.forward(30)
            turtle.left(90)
            node1=node1.next
            count=count+1

m=linked_list()
print("*** insertfirst function is called***")
m.insertfirst(23)
m.insertfirst(24)
m.insertfirst(25)
m.insertfirst(26)
m.insertfirst(27)
m.insertfirst(28)
m.insertfirst(29)
m.display()
print ("*****list ends****")
print ("\n")
m.disturtle()
#turtle.reset()
print ("**** first() function called***")
m.first()
print ("\n")
print ("**** last() function called***")
m.last()
print ("\n")
print ("***find() function called***")
m.find(24)
print ("\n")
print ("***find() function called***")
m.find(50)
print ("\n")
print("*** remove() function is called***")
#m.remove(26)
m.tutrremove(3)
print ("\n")
m.display()
print ("****list ends****")
print ("\n")
print("*** removefirst() function is called***")
m.removefirst()
print ("\n")
#m.disturtle()
#turtle.reset()
print("*** insertafter() function is called***")
m.insertafter(25,25.5)
print ("\n")
m.display()
print ("****list ends****")
print ("\n")
#m.disturtle()
#turtle.reset()
turtle.exitonclick()


from typing import List
from pony.orm import *
from app.api.models.app import *
from app.api.models.master import MasterBase
from app.db.base import db

@db_session
def read_apps() -> List[AppInResponse]:
    apps: List[AppInResponse] = []
    rows = select(r for r in db.App)[:]
    for row in rows:
        app = row.to_dict()
        if row.app_langs is not None:
            langs: List[AppLangBase] = []
            for al in row.app_langs:
                applang = AppLangBase(
                    lang=al.lang.to_dict(),
                    filename=al.filename,
                    version=al.version)
                langs.append(applang)
            app['app_langs'] = langs
        apps.append(app)
    return apps

@db_session
def read_app_for_name(name: str) -> AppInResponse:
    row = db.App.get(name=name)
    if row:
        return row.to_dict()

@db_session
def create_app(row: AppCreate):

    app = db.App(
        name=row.name,
        description=row.description,
        version=row.version,
    )

    if row.app_langs:
        for lang in row.app_langs:
            l = db.Lang.get(id=lang.lang.id)
            db.App_lang(
                app=app,
                lang=l,
                version=lang.version,
                filename=lang.filename)

    return row

@db_session
def update_app(id: int, app: AppInUpdate):
    sql_debug(True)
    updatedApp = db.App.get(id=id)
    if not updatedApp:
        return updatedApp
    else:
        if app.name:
            updatedApp.name = app.name
        if app.description:
            updatedApp.description = app.description
        if app.version:
            updatedApp.version = app.version
        if app.app_langs:
            appLangs = app.app_langs
            for al in appLangs:
                lang = db.Lang.get(id=al.lang.id)
                app = db.App.get(id=id)
                applang = db.App_lang.get(app=app, lang=lang)
                if applang:

                    updatedAppLang = [a for a in set(
                        updatedApp.app_langs) if a.app == app and a.lang == lang][0]

                    updatedAppLang.set(
                        version=al.version,
                        filename=al.filename)
                else:
                    print('crear')
                    db.App_lang(
                        app=app,
                        lang=lang,
                        version=al.version,
                        filename=al.filename)
        commit()
    return updatedApp

@db_session
def delete_app(id: int):
    sql_debug(True)
    db.App[id].delete()

@db_session
def delete_applang(idapp: int, idlang: int):
    sql_debug(True)
    db.App_lang.select(
        lambda al: al.app.id == idapp and al.lang.id == idlang).delete(bulk=True)


# Find kth smallest element in the sorted array
a=[[2,3,4,9],[3,5,5,10],[4,7,7,17],[8,10,12,19]]
k=4

def checkSmaller(a,k):
    count=0
    for row in a:
        upperBound=0
        start=0
        end=len(row)-1
        while(start<=end):
            mid=(start+end)//2
            # print("Mid:",mid)
            if(row[mid]>k):
                end=mid-1
                upperBound=mid
            else:
                start=mid+1
        count+=upperBound
        # print("upper BOund",upperBound)
    # print("Count",count)
    return count
def func(a,k):
    n=len(a)
    start=a[0][0]
    end=a[n-1][n-1]
    ans=-1
    while(start<=end):
        mid=(start+end)//2
        # print("Start:",start,"End:",end,"Mid",mid)
        count=checkSmaller(a,mid)
        if(count>=k):
            end=mid-1
            ans=mid
        else:
            start=mid+1
    return ans

print("ans:",func(a,k))

# The overall time complexity of the algorithm is O(n log w), where n is the number of rows in the matrix and w is the range of values in the matrix. This is because the checkSmaller function performs binary search on each row of the matrix, which takes O(log w) time, and is called once for each value of mid in the func function, which performs binary search on the range of values in the matrix, also taking O(log w) time.

# The space complexity of the algorithm is O(1), since only constant amount of extra space is used to store variables for the binary search and counting.


#!/usr/bin/env python
import os
import sys

import dotenv

# Configs for running coverage from https://adamj.eu/tech/2019/04/30/getting-a-django-application-to-100-percent-coverage/

if __name__ == "__main__":
    dotenv.load_dotenv()

    try:
        command = sys.argv[1]
    except IndexError:
        command = "help"

    running_tests = (command == 'test')

    if running_tests:
        os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.test"
        from coverage import Coverage
        cov = Coverage()
        cov.erase()
        cov.start()
    else:
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

    if running_tests:
        cov.stop()
        cov.combine()
        cov.save()
        covered = cov.report()
        cov.erase()
        # Not sure if we want this. It needs to be kept in sync with our .coveragerc fail value
        # if covered < 80:
        #     sys.exit(1)


from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='nettraffic',
    version='0.0.1',
    description='Small SNMP helper library for network traffic calculations',
    long_description=long_description,
    url='https://github.com/ojarva/python-network-traffic',
    author='Olli Jarva',
    author_email='olli@jarva.fi',
    license='BSD',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
	'Topic :: System :: Networking :: Monitoring',
	'Topic :: System :: Networking',
	'Topic :: System :: Monitoring',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
    keywords='snmp network traffic',
    packages=["nettraffic"],
    install_requires=[],
    test_suite="tests",

    extras_require = {
        'dev': ['twine', 'wheel'],
    },
)


import logging
from autotest.client.shared import error
from virttest import virsh, libvirt_xml

def check_list(filter_ref):
    """
    Return True if filter found in nwfilter-list

    :param filter_ref: filter name or uuid
    :return: True if found, False if not found
    """
    filter_list = []
    cmd_result = virsh.nwfilter_list(options="",
                                     ignore_status=True, debug=True)
    output = cmd_result.stdout.strip().split('\n')
    for i in range(2, len(output)):
        filter_list.append(output[i].split())
    for i in range(len(filter_list)):
        if filter_ref in filter_list[i]:
            return True

    return False

def run(test, params, env):
    """
    Test command: virsh nwfilter-undefine.

    1) Prepare parameters.
    2) Run nwfilter-undefine command.
    3) Check result.
    4) Clean env
    """
    # Prepare parameters
    filter_ref = params.get("undefine_filter_ref", "")
    options_ref = params.get("undefine_options_ref", "")
    status_error = params.get("status_error", "no")

    # Backup filter xml
    if filter_ref:
        new_filter = libvirt_xml.NwfilterXML()
        filterxml = new_filter.new_from_filter_dumpxml(filter_ref)
        logging.debug("the filter xml is: %s" % filterxml.xmltreefile)
        filter_xml = filterxml.xmltreefile.name

    # Run command
    cmd_result = virsh.nwfilter_undefine(filter_ref, options=options_ref,
                                         ignore_status=True, debug=True)
    status = cmd_result.exit_status

    # Check result
    if status_error == "yes":
        if status == 0:
            raise error.TestFail("Run successfully with wrong command.")
    elif status_error == "no":
        if status:
            raise error.TestFail("Run failed with right command.")
        chk_result = check_list(filter_ref)
        if chk_result:
            raise error.TestFail("filter %s show up in filter list." %
                                 filter_ref)

    # Clean env
    if status == 0:
        virsh.nwfilter_define(filter_xml, options="",
                              ignore_status=True, debug=True)


import sys
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from tqdm import tqdm
from kmeans import KMeans

SIGMA_CONST = 1e-6
LOG_CONST = 1e-32

class GMM(object):
    def __init__(self, X, K, max_iters = 100): # No need to change
        """
        Args:
            X: the observations/datapoints, N x D numpy array
            K: number of clusters/components
            max_iters: maximum number of iterations (used in EM implementation)
        """
        self.points = X
        self.max_iters = max_iters

        self.N = self.points.shape[0]        #number of observations
        self.D = self.points.shape[1]        #number of features
        self.K = K                           #number of components/clusters

    #Helper function for you to implement
    def softmax(self, logit): # [5pts]
        """
        Args:
            logit: N x D numpy array
        Return:
            prob: N x D numpy array. See the above function.
        """
        exp_logit = np.exp(logit - np.max(logit,axis= -1, keepdims= True))

        return exp_logit/np.sum(exp_logit,axis = -1, keepdims= True)

    def logsumexp(self, logit): # [5pts]
        """
        Args:
            logit: N x D numpy array
        Return:
            s: N x 1 array where s[i,0] = logsumexp(logit[i,:]). See the above function
        """
        exp_logit = np.exp(logit - np.max(logit,axis= -1, keepdims= True))

        return np.log(np.sum(exp_logit,axis = -1, keepdims= True)) + np.max(logit,axis=-1,keepdims=True)

    #for undergraduate student
    def normalPDF(self, logit, mu_i, sigma_i): #[5pts]
        """
        Args:
            logit: N x D numpy array
            mu_i: 1xD numpy array, the center for the ith gaussian.
            sigma_i: 1xDxD numpy array, the covariance matrix of the ith gaussian.
        Return:
            pdf: 1xN numpy array, the probability distribution of N data for the ith gaussian

        Hint:
            np.diagonal() should be handy.
        """
        N, D = np.shape(logit)
        if len(np.shape(sigma_i)) == 2:
            sigma_i = np.diagonal(sigma_i)
        else:
            sigma_i = sigma_i.reshape(1,-1)
            sigma_i = np.diagonal(sigma_i * sigma_i.T)
        pdf = np.ones((1, N))
        for i in range(D):
            exp = ((-2 * sigma_i[i] )**-1) * np.square(logit[:, i] - mu_i[i])
            pdf *= ((2 * np.pi * sigma_i[i])**-0.5) * np.exp(exp)
        return pdf.reshape((logit.shape[0],))

    #for grad students
    def multinormalPDF(self, logits, mu_i, sigma_i):  #[5pts]
        """
        Args:
            logit: N x D numpy array
            mu_i: 1xD numpy array, the center for the ith gaussian.
            sigma_i: 1xDxD numpy array, the covariance matrix of the ith gaussian.
        Return:
            normal_pdf: 1xN numpy array, the probability distribution of N data for the ith gaussian

        Hint:
            np.linalg.det() and np.linalg.inv() should be handy.
        """
        raise NotImplementedError

    def _init_components(self, **kwargs): # [5pts]
        """
        Args:
            kwargs: any other arguments you want
        Return:
            pi: numpy array of length K, prior
            mu: KxD numpy array, the center for each gaussian.
            sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian.
                You will have KxDxD numpy array for full covariance matrix case
        """
        pi = np.full((self.K,),1/self.K )
        sigma = np.zeros((self.K, self.D, self.D))
        mu = np.zeros((self.K, self.D))
        for k in range(self.K):
            mu[k] = self.points[int(np.random.uniform(0,self.K))]
            sigma[k] = np.eye(self.D)

        return pi, mu, sigma

    def _ll_joint(self, pi, mu, sigma, full_matrix = False, **kwargs): # [10 pts]
        """
        Args:
            pi: np array of length K, the prior of each component
            mu: KxD numpy array, the center for each gaussian.
            sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian. You will have KxDxD numpy
            array for full covariance matrix case
            full_matrix: whether we use full covariance matrix in Normal PDF or not. Default is True.

        Return:
            ll(log-likelihood): NxK array, where ll(i, k) = log pi(k) + log NormalPDF(points_i | mu[k], sigma[k])
        """
        ll = np.zeros((self.K,self.N))
        for k in range(self.K):
            ll[k] = np.log(pi[k]+ 10**(-32)) + np.log(self.normalPDF(self.points, mu[k], sigma[k]) + 10**(-32))

        return ll.T

    def _E_step(self, pi, mu, sigma, **kwargs): # [5pts]
        """
        Args:
            pi: np array of length K, the prior of each component
            mu: KxD numpy array, the center for each gaussian.
            sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian.You will have KxDxD numpy
            array for full covariance matrix case
        Return:
            gamma(tau): NxK array, the posterior distribution (a.k.a, the soft cluster assignment) for each observation.

        Hint:
            You should be able to do this with just a few lines of code by using _ll_joint() and softmax() defined above.
        """
        ll = self._ll_joint(pi, mu, sigma)
        gamma = self.softmax(ll)
        return gamma

    def _M_step(self, gamma, full_matrix = False, **kwargs): # [10pts]
        """
        Args:
            gamma(tau): NxK array, the posterior distribution (a.k.a, the soft cluster assignment) for each observation.
        Return:
            pi: np array of length K, the prior of each component
            mu: KxD numpy array, the center for each gaussian.
            sigma: KxDxD numpy array, the diagonal standard deviation of each gaussian. You will have KxDxD numpy
            array for full covariance matrix case

        Hint:
            There are formulas in the slide and in the above description box.
        """
        N, D = np.shape(self.points)
        K = np.shape(gamma)[1]
        N_k = np.sum(gamma, axis=0)
        mu = np.zeros((self.K, self.D))

        pi = N_k / N
        mu = (np.matmul(gamma.T, self.points).T / N_k).T

        sigma = np.zeros((K, D, D))

        for k in range(K):
            temp = np.matmul((self.points - mu[k]).reshape((N, D, 1)), (self.points - mu[k]).reshape((N, 1, D)))
            sigma[k] = np.dot(np.transpose(temp, (1, 2, 0)), gamma[:,k])
            sigma[k] /= N_k[k]
            sigma[k] = sigma[k]*np.eye(self.D)

        return pi, mu, sigma

    def __call__(self, full_matrix = False, abs_tol=1e-16, rel_tol=1e-16, **kwargs): # No need to change
        """
        Args:
            abs_tol: convergence criteria w.r.t absolute change of loss
            rel_tol: convergence criteria w.r.t relative change of loss
            kwargs: any additional arguments you want

        Return:
            gamma(tau): NxK array, the posterior distribution (a.k.a, the soft cluster assignment) for each observation.
            (pi, mu, sigma): (1xK np array, KxD numpy array, KxDxD numpy array)

        Hint:
            You do not need to change it. For each iteration, we process E and M steps, then update the paramters.
        """
        pi, mu, sigma = self._init_components(**kwargs)
        pbar = tqdm(range(self.max_iters))

        for it in pbar:
            # E-step
            gamma = self._E_step(pi, mu, sigma)

            # M-step
            pi, mu, sigma = self._M_step(gamma, full_matrix)

            # calculate the negative log-likelihood of observation
            joint_ll = self._ll_joint(pi, mu, sigma, full_matrix)
            loss = -np.sum(self.logsumexp(joint_ll))
            if it:
                diff = np.abs(prev_loss - loss)
                if diff < abs_tol and diff / prev_loss < rel_tol:
                    break
            prev_loss = loss
            pbar.set_description('iter %d, loss: %.4f' % (it, loss))
        return gamma, (pi, mu, sigma)


from __future__ import print_function
import os.path
from os import path
import asyncio
import platform
import math
import sys
import re

from bleak import BleakClient, BleakScanner
from bleak.exc import BleakError

header = """#####################################################################
    ------------------------BLE OTA update---------------------
    Arduino code @ https://github.com/fbiego/ESP32_BLE_OTA_Arduino
#####################################################################"""

UART_SERVICE_UUID = "c78cfcf9-cdb1-4962-b69d-ac1c380c0001"
UART_RX_CHAR_UUID = "eac38323-5642-48ca-9d34-a316c2dc0002"
UART_TX_CHAR_UUID = "eac38323-5642-48ca-9d34-a316c2dc0003"

PART = 16000
MTU = 250

end = True
clt = None
fileBytes = None
total = 0
sent = 0
#device = None

def get_bytes_from_file(filename):
    print("Reading from: ", filename)
    return open(filename, "rb").read()

async def start_ota():
    device = None
    while device == None:
        devices = await BleakScanner.discover()
        for d in devices:
            if d.name == "InFlow":
                print("Connecting to InFlow")
                device = d

    #device = await BleakScanner.find_device_by_address(ble_address, timeout=20.0)
    disconnected_event = asyncio.Event()

    def handle_disconnect(_: BleakClient):
        global disconnect
        disconnect = False
        print(": Device disconnected")
        exit()
        disconnected_event.set()

    async def handle_rx(_: int, data: bytearray):
        print("handle rx: " + str(data))
        if (data[0] == 0xAA):
            print("Transfer mode:", data[1])
            printProgressBar(0, total, prefix = 'Progress:', suffix = 'Complete', length = 50)
            if data[1] == 1:
                for x in range(0, fileParts):
                    await send_part(x, fileBytes, clt)
                    printProgressBar(x + 1, total, prefix = 'Progress:', suffix = 'Complete', length = 50)
            else:
                await send_part(0, fileBytes, clt)

        if (data[0] == 0xF1):
            nxt = int.from_bytes(bytearray([data[1], data[2]]), "big")
            await send_part(nxt, fileBytes, clt)
            printProgressBar(nxt + 1, total, prefix = 'Progress:', suffix = 'Complete', length = 50)
        if (data[0] == 0xF2):
            ins = 'Installing firmware'
            #print("Installing firmware")
        if (data[0] == 0x0F):
            result = bytearray([])
            for s in range(1, len(data)):
                result.append(data[s])
            print("OTA result: ", str(result, 'utf-8'))
            global end
            end = False
        #print("received:", data)

    async def send_part(position: int, data: bytearray, client: BleakClient):
        start = (position * PART)
        end = (position + 1) * PART
        if len(data) < end:
            end = len(data)
        parts = (end - start) / MTU
        for i in range(0, int(parts)):
            toSend = bytearray()
            for y in range(0, MTU):
                toSend.append(data[(position*PART)+(MTU * i) + y])
            await send_data(client, toSend, False)
        if (end - start)%MTU != 0:
            rem = (end - start)%MTU
            toSend = bytearray()#([int(parts)])
            for y in range(0, rem):
                toSend.append(data[(position*PART)+(MTU * int(parts)) + y])
            await send_data(client, toSend, False)
        #update = bytearray([int((end - start)/256), int((end - start) % 256), int(position/256), int(position % 256) ])
        #await send_data(client, update, True)

    async def send_data(client: BleakClient, data: bytearray, response: bool):
        global sent
        print("sending " + str(len(data)))
        sent = sent + len(data)
        print("sent " + str(sent) + " total")
        await client.write_gatt_char(UART_TX_CHAR_UUID, data, response)
        await asyncio.sleep(0.2)

    if not device:
        print("-----------Failed--------------")
        print(f"Device with address {ble_address} could not be found.")
        return
        #raise BleakError(f"A device with address {ble_address} could not be found.")
    async with BleakClient(device, disconnected_callback=handle_disconnect) as client:
        #await client.start_notify(UART_RX_CHAR_UUID, handle_rx)
        await asyncio.sleep(1.0)

        #await send_data(client, bytearray([0xFD]), False)

        global fileBytes
        fileBytes = get_bytes_from_file("firmware.bin")
        global clt
        clt = client
        fileParts = math.ceil(len(fileBytes) / PART)
        fileLen = len(fileBytes)
        fileSize = bytearray([fileLen >>  24 & 0xFF, fileLen >>  16 & 0xFF, fileLen >>  8 & 0xFF, fileLen & 0xFF])
        #await send_data(client, fileSize, False)
        print("file size: " + str(fileLen))
        global total
        total = fileParts
        otaInfo = bytearray([int(fileParts/256), int(fileParts%256), int(MTU / 256), int(MTU%256) ])
        #await send_data(client, otaInfo, False)
        print("file parts: " + str(fileParts))
        for x in range(0, fileParts):
            await send_part(x, fileBytes, clt)

        print("All data sent")
        while end:
            await asyncio.sleep(1.0)
        print("Waiting for disconnect... ", end="")
        await disconnected_event.wait()
        print("-----------Complete--------------")

"""
ble_address = (
    "98:CD:AC:D3:6B:E2"
    if platform.system() != "Darwin"
    else "B9EA5233-37EF-4DD6-87A8-2A875E821C46"
)
"""

def isValidAddress(str):

    # Regex to check valid
    # MAC address
    regex = ("^([0-9A-Fa-f]{2}[:-])" +
             "{5}([0-9A-Fa-f]{2})|" +
             "([0-9a-fA-F]{4}\\." +
             "[0-9a-fA-F]{4}\\." +
             "[0-9a-fA-F]{4}){17}$")
    regex2 = "^[{]?[0-9a-fA-F]{8}" + "-([0-9a-fA-F]{4}-)" + "{3}[0-9a-fA-F]{12}[}]?$"

    # Compile the ReGex
    p = re.compile(regex)
    q = re.compile(regex2)

    # If the string is empty
    # return false
    if (str == None):
        return False

    # Return if the string
    # matched the ReGex
    if(re.search(p, str) and len(str) == 17):
        return True
    else:
        if (re.search(q, str) and len(str) == 36):
            return True
        else:
            return False

if __name__ == "__main__":
    print(header)
    print("Trying to start OTA update")
    asyncio.run(start_ota())


import cdsapi
import xarray as xr
import zarr
import numcodecs
import os
from huggingface_hub import HfApi
api = HfApi()
files = api.list_repo_files("openclimatefix/era5-reanalysis", repo_type="dataset")
data_files = [file for file in files if file.startswith("data/")]
c = cdsapi.Client()

for year in range(2022,2015,-1):
    for month in range(1,13):
        files = api.list_repo_files("openclimatefix/era5-reanalysis", repo_type="dataset")
        data_files = [file for file in files if file.startswith("data/")]
        for day in range(1,31):
            data_files = [file for file in files if file.startswith("data/")]
            if f"data/air/{year}/{str(month).zfill(2)}/{year}_{str(month).zfill(2)}_{str(day).zfill(2)}.zarr.zip" in data_files:
                continue
            try:
                c.retrieve(
                    'reanalysis-era5-pressure-levels',
                    {
                        'product_type': 'reanalysis',
                        'variable': [
                            'divergence', 'fraction_of_cloud_cover', 'geopotential',
                            'ozone_mass_mixing_ratio', 'potential_vorticity', 'relative_humidity',
                            'specific_cloud_ice_water_content', 'specific_cloud_liquid_water_content', 'specific_humidity',
                            'specific_rain_water_content', 'specific_snow_water_content', 'temperature',
                            'u_component_of_wind', 'v_component_of_wind', 'vertical_velocity',
                            'vorticity',
                        ],
                        'pressure_level': [
                            '1', '2', '3',
                            '5', '7', '10',
                            '20', '30', '50',
                            '70', '100', '125',
                            '150', '175', '200',
                            '225', '250', '300',
                            '350', '400', '450',
                            '500', '550', '600',
                            '650', '700', '750',
                            '775', '800', '825',
                            '850', '875', '900',
                            '925', '950', '975',
                            '1000',
                        ],
                        'year': str(year),
                        'month': str(month).zfill(2),
                        'day': str(day).zfill(2),
                        'time': [
                            '00:00', '01:00', '02:00',
                            '03:00', '04:00', '05:00',
                            '06:00', '07:00', '08:00',
                            '09:00', '10:00', '11:00',
                            '12:00', '13:00', '14:00',
                            '15:00', '16:00', '17:00',
                            '18:00', '19:00', '20:00',
                            '21:00', '22:00', '23:00',
                        ],
                        'format': 'netcdf',
                    },
                    f'download_air.nc')
                data = xr.open_dataset("/home/jacob/Downloads/download_air.nc", engine="netcdf4")
                print(data)
                encoding = {var: {"compressor": numcodecs.get_codec(dict(id="zlib", level=5))} for var in data.data_vars}
                if f"data/air/{year}/{str(month).zfill(2)}/{year}_{str(month).zfill(2)}_{str(day).zfill(2)}_{str(i).zfill(2)}.zarr.zip" in data_files:
                    continue
                d = data.chunk({"time": 1})
                with zarr.ZipStore(f'/run/media/jacob/Elements/{year}_{str(month).zfill(2)}_{str(day).zfill(2)}.zarr.zip', mode='w') as store:
                    d.to_zarr(store, encoding=encoding, compute=True)
                api.upload_file(
                    path_or_fileobj=f'/run/media/jacob/Elements/{year}_{str(month).zfill(2)}_{str(day).zfill(2)}.zarr.zip',
                    path_in_repo=f"data/air/{year}/{str(month).zfill(2)}/{year}{str(month).zfill(2)}{str(day).zfill(2)}.zarr.zip",
                    repo_id="openclimatefix/era5-reanalysis",
                    repo_type="dataset",
                    )
                os.remove(
                    f'/run/media/jacob/Elements/{year}_{str(month).zfill(2)}_{str(day).zfill(2)}.zarr.zip')
            except:
                continue


import json

# Author: Chris Petrich
# Date: Apr 2018

# massively reduced version of the original version
#   maintaining original interface of save()

def _to_json(dct):
    """convert keys to str, py2 and py3"""
    if isinstance(dct, dict):
        return {str(key).replace(' ',''):dct[key] for key in dct}
    return dct

def _str2inttuple(s):
    """parse string as tuple of integers"""
    return tuple([int(v) for v in s.split('(',1)[1].split(')',1)[0].split(',')])

def _from_json(dct):
    """convert string keys back to tuples"""
    if not isinstance(dct, dict): return dct
    for key in dct:
        break
    if isinstance(key, str) and key.startswith('('):
        return {_str2inttuple(key): dct[key] for key in dct}
    return dct

def save(filename, head_module, data_dict):
    """Outputs only data_dict"""
    # NB: zipping this up could reduce space to 30%.
    # remove .py and add .json
    filename = filename[:-3] if filename.lower().endswith('.py') else filename
    filename = filename if filename.lower().endswith('.json') else filename+'.json'
    with open(filename,'w') as f:
        json.dump({outer_key:_to_json(data_dict[outer_key]) for outer_key in data_dict}, f, separators=(',', ':'))

def load(filename):
    # remove .py and add .json
    filename = filename[:-3] if filename.lower().endswith('.py') else filename
    filename = filename if filename.lower().endswith('.json') else filename+'.json'
    with open(filename) as f:
        data=json.load(f)
    return {'data':{key:_from_json(data[key]) for key in data}}


'''
@author: Dallas Fraser
@author: 2019-03-13
@organization: MLSB API
@summary: Tests all the bot submit scores APIs
'''
from api.helper import loads
from api.routes import Routes
from api.model import Team
from base64 import b64encode
from api.test.BaseTest import \
    TestSetup, ADMIN, PASSWORD, INVALID_ID, addGame
from api.errors import \
    PlayerNotSubscribed, GameDoesNotExist, InvalidField
headers = {
    'Authorization': 'Basic %s' % b64encode(bytes(ADMIN + ':' +
                                                  PASSWORD, "utf-8")
                                            ).decode("ascii")
}

class testSubmitScores(TestSetup):

    def testMain(self):
        # add some background
        game = addGame(self)
        team_model = Team.query.get(game['home_team_id'])
        team = team_model.json()
        player = self.add_player("Test Bot Captain", "testbot@mlsb.ca", "m")
        self.add_player_to_team(team, player, captain=True)
        route = Routes['botsubmitscore']

        # invalid captain
        data = {'player_id': INVALID_ID,
                'game_id': game['game_id'],
                'score': 1,
                'hr': [player['player_id']],
                'ss': []}
        expect = {'details': INVALID_ID,
                  'message': PlayerNotSubscribed.message}
        rv = self.app.post(route, json=data, headers=headers)
        self.output(loads(rv.data))
        self.output(expect)
        error = Routes['botsubmitscore'] + " POST: invalid bot user name"
        code = PlayerNotSubscribed.status_code
        self.assertEqual(rv.status_code, code, error)
        self.assertEqual(expect, loads(rv.data), error)

        # invalid game
        data = {'player_id': player['player_id'],
                'game_id': INVALID_ID,
                'score': 1,
                'hr': [player['player_id']],
                'ss': []}
        expect = {'details': INVALID_ID, 'message': GameDoesNotExist.message}
        rv = self.app.post(route, json=data, headers=headers)
        self.output(loads(rv.data))
        self.output(expect)
        error = Routes['botsubmitscore'] + " POST: invalid game id"
        self.assertEqual(rv.status_code, GameDoesNotExist.status_code, error)
        self.assertEqual(expect, loads(rv.data), error)

        # more hr than runs scored
        data = {'player_id': player['player_id'],
                'game_id': game['game_id'],
                'score': 1,
                'hr': [player['player_id'], player['player_id']],
                'ss': []}
        expect = {'details': 'More hr than score',
                  'message': InvalidField.message}
        rv = self.app.post(route, json=data, headers=headers)
        self.output(loads(rv.data))
        self.output(expect)
        error = Routes['botsubmitscore'] + " POST: more hr than runs"
        self.assertEqual(rv.status_code, InvalidField.status_code, error)
        self.assertEqual(expect, loads(rv.data), error)

        # normal request
        self.submit_a_score(player, game, 1, hr=[player['player_id']])


import tkinter as tk
from tkinter import END, ttk
from tkinter import messagebox
import mysql.connector
#import modelo e DAO
from produto import Produto
from produtoDAO import ProdutoDAO

class TelaInserir():
    # criar uma instância da classe modelo (Produto)
    __prod = Produto()
    # criar nova instância da classe DAO (ProdutoDAO)
    __prodDAO = ProdutoDAO()

    def __init__(self,window):
        window = tk.Toplevel()
        window.title('Inserir Produtos')

        self.__frame1 = ttk.Frame(window)
        self.__frame1.pack()

        ttk.Label(self.__frame1,text = 'Nome do Produto:').grid(row=0,column=0,sticky=tk.W)
        vcmdC1 = (self.__frame1.register(self.mudarCorNome), '%P')
        self.__txtNomeProduto = tk.Entry(self.__frame1)
        self.__txtNomeProduto.config(validate='key',validatecommand=vcmdC1)
        self.__txtNomeProduto.grid(row=0,column=1,sticky=tk.W)

        ttk.Label(self.__frame1,text = 'Descrição').grid(row=1,column=0,sticky=tk.W)
        vcmdC2 = (self.__frame1.register(self.mudarCorDesc), '%P')
        self.__txtDescProduto = tk.Entry(self.__frame1)
        self.__txtDescProduto.config(validate='key',validatecommand=vcmdC2)
        self.__txtDescProduto.grid(row=1,column=1,sticky=tk.W)

        ttk.Label(self.__frame1,text = 'Estoque').grid(row=2,column=0,sticky=tk.W)
        vcmd = (self.__frame1.register(self.verificarNum), '%P')
        self.__txtqtdEstoque = tk.Entry(self.__frame1)
        self.__txtqtdEstoque.config(validate = 'key',validatecommand=vcmd)
        self.__txtqtdEstoque.grid(row=2,column=1,sticky=tk.W)
        # - (validatecommand) comando enquanto em execução, independente de uma ação não relacionado
        # com apertar um botão, isso é com o command

        ttk.Label(self.__frame1,text = 'Preço R$:').grid(row=3,column=0,sticky=tk.W)
        vcmdR = (self.__frame1.register(self.verificarNumReal), '%P')
        self.__txtPrecoProduto = tk.Entry(self.__frame1)
        self.__txtPrecoProduto.config(validate = 'key', validatecommand = vcmdR)
        self.__txtPrecoProduto.grid(row=3,column=1,sticky=tk.W)

        self.__btnSalvar = ttk.Button(self.__frame1,text = 'Salvar', command = self.saveadd)
        self.__btnSalvar.grid(row=4,column=0,columnspan=2,sticky=tk.W)

    def saveadd(self):
        # 1º passo - trazer info dos txts para as váriaveis
        if self.__txtNomeProduto.get() == '' or self.__txtDescProduto.get() == '' or self.__txtqtdEstoque.get() == '' or self.__txtPrecoProduto.get() == '':
            messagebox.showerror('Inserir','Preencher as informações em vermelho !!!')
            if self.__txtNomeProduto.get() == '' :
                self.__txtNomeProduto['bg'] = 'red'
            if self.__txtDescProduto.get() == '' :
                self.__txtDescProduto['bg'] = 'red'
            if self.__txtqtdEstoque.get() == '' :
                self.__txtqtdEstoque['bg'] = 'red'
            if self.__txtPrecoProduto.get() == '' :
                self.__txtPrecoProduto['bg'] = 'red'
        else:
            # - trazer infos para as váriaveis que estão no txt da tela
            # e armazenar na instância da classe modelo (Produto)
            self.__prod.nomeProd = self.__txtNomeProduto.get()
            self.__prod.descProd = self.__txtDescProduto.get()
            self.__prod.qtdEstoque = self.__txtqtdEstoque.get()
            self.__prod.precoProd = self.__txtPrecoProduto.get().replace(',','.')

            self.__prodDAO.prod = self.__prod
            self.__prodDAO.Inserir()

            # limpar os txt's
            self.__txtNomeProduto.delete(0, END)
            self.__txtDescProduto.delete(0, END)
            self.__txtqtdEstoque.delete(0, END)
            self.__txtPrecoProduto.delete(0, END)
        ####################################################################
            messagebox.showinfo('Informação','Dados Cadastrados com Sucesso!')

    def verificarNum(self,valor):
        if valor.isdigit():
            self.__txtqtdEstoque ['bg'] = 'white'
            return True
        else:
             messagebox.showwarning('Aviso!','Digitar Apenas Números Inteiros!!!')
             self.__txtqtdEstoque.focus()
             return False

    def verificarNumReal(self,valor):
        valor = valor.replace(',',".")
        try:
            float(valor)
            self.__txtPrecoProduto ['bg'] = 'white'
            return True
        except:
             messagebox.showwarning('Aviso!','Digitar Números!!!')
             self.__txtPrecoProduto.focus()
             return False

    def mudarCorNome(self,valor):
        self.__txtNomeProduto ['bg'] = 'white'
        return True
    def mudarCorDesc(self,valor):
        self.__txtDescProduto ['bg'] = 'white'
        return True

Projects/BackEnd/Python/BackEnd ex1 - Mercadinho - DAO/telaInserir.py


import os
import json
import tabulate as tbl
import tkinter.messagebox as mb
from constants import *

def add_to_basket(store_articles: 'list[list]', basket: 'list[list]', article_to_add: str):
    price = 0
    article_name = ''
    # Removing the article from the the store
    for article in store_articles:
        if article[0] == article_to_add:
            price = article[3]
            article_name = article[1]
            article[2] -= 1
            if article[2] == 0:
                store_articles.remove(article)

    # adding the article to the basket
    is_already_there = False
    for article in basket:
        if article[0] == article_to_add:
            article[2] += 1
            is_already_there = True
    if not is_already_there:
        basket.append([article_to_add, article_name, 1, price, price*1])

def remove_from_basket(store_articles: 'list[list]', basket: 'list[list]', article_to_remove: str):

    price = 0
    article_name = ''
    # removing article to the basket
    for article in basket:
        if article[0] == article_to_remove:
            price = article[3]
            article_name = article[1]
            article[2] -= 1
            if (article[2] == 0):
                basket.remove(article)

    # HERE: restoring the article to the store
    is_already_there = False
    for article in store_articles:
        if article[0] == article_to_remove:
            article[2] += 1
            is_already_there = True
    if not is_already_there:
        store_articles.append(
            [article_to_remove, article_name, 1, price])

def validate_purchase(basket: 'list[list]', name_of_the_client: str) -> str:
    clients: list[dict] = json.load(open('./data/clients.json', 'r'))
    # TODO: check if the client is already in the database
    # if true, check the number of visists and the articles puchases
    # if the number of purchases is >2 for an article, we do a reduction

    client: dict = {}
    # find the rig client:
    is_already_exist = False
    for cl in clients:
        if cl["name"] == name_of_the_client:
            is_already_exist = True
            cl['visits'] += 1
            client = cl
            cl['purchases'].append(basket)

    if not is_already_exist:
        client = {
            'name': name_of_the_client,
            'visits': 1,
            'purchases': [basket]
        }
        clients.append(client)

    "saving the client in the clients file"
    with open('./data/clients.json', 'w') as client_file:
        json.dump(clients, client_file)

    # Now we can process the bill by modifiying the basket content

    for new_purchase in basket:

        # calculate the total price
        new_purchase[4] = new_purchase[2] * \
            new_purchase[3]
        hasReduction = False
        if client['visits'] > 2:
            for old_purchases in list(client['purchases'][:-1]):

                for old_purchase in old_purchases:
                    if old_purchase[0] == new_purchase[0] and old_purchase[2] >= 2:
                        # we have to accord the reduction
                        hasReduction = True
                        new_purchase[4] *= 0.98
        if hasReduction:
            mb.showinfo(
                "Reductions😍", f"Felicitations vous beneficiez d'une reduction de 2% sur l'article {new_purchase[1]}")

    # Data that will be contained in a bill
    bill = {
        'client_name': name_of_the_client,
        'bill_path': generate_bill_path(name_of_the_client, client['visits']),
        'purchases': basket
    }
    # savaing the new bill in the invoices file, and
    invoices = json.load(open('./data/invoices.json', 'r'))
    invoices.append(bill)
    with open('./data/invoices.json', 'w') as invoices_file:
        json.dump(invoices, invoices_file)

    # generate the bill_file
    bill_writter(bill)
    basket = []
    return bill['bill_path']

def bill_writter(bill: dict) -> None:
    basket: list = bill['purchases']
    count, total = 0, 0
    for article in basket:
        count += article[2]
        total += article[4]
    basket.append(['TOTAL', '', count, '', total])
    headers = ['Code', 'Article',  'Quantité',
               'Prix Unitaire', 'Prix total']
    with open(f'{bill["bill_path"]}', 'w', encoding="utf-8") as bill_file:
        table = tbl.tabulate(basket, headers=headers,
                             tablefmt='fancy_grid', showindex=True)
        name = str(bill['client_name']).title()
        bill_file.write(f"Nom du client: {name}\n{table}\n\nMerci d'avoir fait vos achats chez {SHOP_NAME}")

def generate_bill_path(client_name: str, visits_nbr: int) -> str:
    base = './data/bills/'+client_name
    if os.path.exists(base):
        return base+f'/{client_name}{visits_nbr-1}.txt'
    os.mkdir(base)
    return base+f'/{client_name}.txt'


from django.contrib.admin import AdminSite

class TestPlatAdminSite(AdminSite):

    def get_app_list(self, request):
        """
        Return a sorted list of all the installed apps that have been
        registered in this site.
        """
        app_ordering = {
            '测试平台': 1,
            'Celery结果': 2,
            '周期性任务': 3,
            '认证和授权': 4,
            '内容类型': 5
        }
        app_dict = self._build_app_dict(request)

        # Sort the apps alphabetically.
        app_list = sorted(app_dict.values(), key=lambda x: app_ordering[x["name"]])

        model_ordering = {
            '测试项目': 1,
            '接口定义': 2,
            '接口执行履历': 3,
            '用例': 4,
            '用例执行履历': 5,
            '用例套件': 6,
            '用例套件执行履历': 7,
            '测试批次(报告)': 8,
            '用例接口': 9,
            '项目成员': 10,
            '部署环境': 11,
        }
        # Sort the models alphabetically within each app.
        for app in app_list:
            if app['name'] == '测试平台':
                app["models"].sort(key=lambda x: model_ordering[x["name"]])
            else:
                app["models"].sort(key=lambda x: x["name"])
        return app_list


import nltk
from nltk import word_tokenize
from nltk import FreqDist
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import random
import sys

stopWords = set(stopwords.words('english'))#setting stop words

if len(sys.argv)<2:#checking for sysarg
	print("No file name provided")
	exit()

fileName = sys.argv[1]

f = open(fileName)#open and read file
yourList = f.read()

xx = word_tokenize(yourList)#tokenize
y = len(set(xx))#how many unique strings
z = len(xx)#how many tokens
g = y/z#calc lexical diversity
g= round(g,2)#round lexical diversity to two digits
print("Lexical diversity is %d", g)

def preprocessing(x):#preprocessing method
	lemmatizer = WordNetLemmatizer()
	zz = []
	for t in x:#make new list zz with lowercase, alpha, in stopwords, and length<5
		if t.isalpha() and t.islower() and t not in stopWords and len(t)>5:
			tt = lemmatizer.lemmatize(t)#lemmatize words whichc fit the criteria
			zz.append(tt)
	kk = list(set(zz))#only unique words
	acount = len(kk)#how many unique words
	kk = nltk.pos_tag(kk)#pos tag the unique words and get only the nouns
	#print(kk[0:20])
	Nlist = []
	hList = ["NN","NNS","NNP","NNPS"]
	for x in kk:
		if x[1] in hList:
			Nlist.append(x)
	dcount = len(Nlist)#how many nounds

	superList = []
	for x in Nlist:
		superList.append(x[0])#elimate pos, and only keep word

	print("Number of tokens from step A is "+ str(acount) + " and nouns from step D is " + str(dcount))
	return((zz,superList))#return as tuple
(a,b) = preprocessing(xx) #call preprocessing and unpack tuple

fdist = FreqDist(a)# find the frequency of the nouns
dicty = {}
for one, two in fdist.items():
	if one in b:
		dicty[one] = two#dict with keys being the unique nouns, and the values being the frequency
sorted_values = sorted(dicty.values())#sort and reverse the dict
sorted_values = sorted_values[::-1]
sorted_dicty = {}
for i in sorted_values:
    for k in dicty.keys():
        if dicty[k] == i:
            sorted_dicty[k] = dicty[k]
keys = sorted_dicty.keys()
keys = list(keys)
dictList = []
x = 0
while x<50:#print top 50 nouns
	dictList.append(keys[x])
	print(str(x+1) + ". " + str(keys[x]) + ": " + str(dicty[keys[x]]))
	x+=1

actualWord = random.choice(dictList)#get random word from top 50
placeholder = len(actualWord)*'_'#set placeholder with underscores

score = 5
guess = ""

while score > 0 and guess != "!" and "_" in placeholder:
	print(placeholder + ", score: " + str(score))#print status
	guess = input("Enter your guess: \n")
	hit = 0 #toggle to see if guess was sucessfull
	if guess != "!":#if they made a valid guess
		for x in range(len(actualWord)):#if the guess is correct, then replace all instances of that letter in the placeholder
			if guess == actualWord[x]:
				s = list(placeholder)
				s[x] = guess
				placeholder = "".join(s)
				hit = 1
	else:#messages to player after each round
		print("Game exited")
	if hit == 0:
		print("Sorry, guess again")
		score = score-1
	else:
		print("Right!!")
		score = score+1

print("Word was " + actualWord + ", score: " + str(score))


__author__ = 'DUDE'

import numpy

class GNSFile:
    TEXTURE = 5889
    LARGE_R = 11777
    MED_R = 12033
    SMALL_R = 12289

    def __init__(self, file_name):

        storage = numpy.dtype({'names': ['index1', 'arrange', 'environment', 'resource_type',
                                         'resource_lba', 'resource_size'],
                               'formats': ['<H', '<B', '<B', '<H', '<I', '<I'],
                               'offsets': [ 0x0,  0x2,  0x3,  0x4,  0x8,  0xc],
                               'itemsize': 20})

        self._data = numpy.fromfile(file_name, dtype=storage)

    @property
    def situations(self):
        try:
            #return index1, arrange, environment, and resource_type limited to our resource data
            return self._data[self._data['resource_type'] <= GNSFile.SMALL_R][['index1',
                                                                               'arrange',
                                                                               'environment',
                                                                               'resource_type']]
        except AttributeError:
            print('Data not initialized.')

    @property
    def texture_data(self):
        try:
            return self._data[self._data['resource_type'] == GNSFile.TEXTURE]
        except AttributeError:
            print('Texture data not initialized.')

    @property
    def type0_data(self):
        try:
            return self._data[self._data['resource_type'] == GNSFile.LARGE_R]
        except AttributeError:
            print('Resource data not initialized.')

    @property
    def type1_data(self):
        try:
            return self._data[self._data['resource_type'] == GNSFile.MED_R]
        except AttributeError:
            print('Resource data not initialized.')

    @property
    def type2_data(self):
        try:
            return self._data[self._data['resource_type'] == GNSFile.SMALL_R]
        except AttributeError:
            print('Resource data not initialized.')

if __name__ == "__main__":
    gns_file = GNSFile('C:\\Users\\DUDE\\PycharmProjects\\Ganesha-0.60\\FINALFANTASYTACTICS\\MAP\\MAP001.GNS')
    print(gns_file.situations)


from selenium import webdriver
from selenium.common.exceptions import JavascriptException, ElementNotInteractableException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
import time
import bs4

def obtain_cookies_and_thread_meta(browser, keyword):
    browser.get('https://hackforums.net/member.php?action=login')

    time.sleep(7)    # wait for the possible identity check to finish

    username_elem = browser.find_element_by_name('username')
    username_elem.send_keys('Napoleon')

    password_elem = browser.find_element_by_name('password')
    password_elem.send_keys('LillyTheDog1!')
    password_elem.send_keys(Keys.RETURN)

    time.sleep(5)    # have to wait for the login cookies to be transferred

    cookies = __extract_login_cookies(browser.get_cookies())

    browser.get('https://hackforums.net/search.php')
    # searchElem = browser.find_elements_by_name('keywords')

    num_replies_elem = browser.find_element_by_name("numreplies")
    num_replies_elem.send_keys('30')

    search_elems = browser.find_elements_by_name('keywords')
    for search_elem in search_elems:
        try:
            search_elem.send_keys(keyword)
            search_elem.send_keys(Keys.RETURN)
            break    # do not attempt to find the others
        except ElementNotInteractableException:
            continue

    threads = []
    threads.append(__extract_threads_on_page(browser))
    while __next_page(browser):
        threads.append(__extract_threads_on_page(browser))

    threads = [item for sublist in threads for item in sublist]
    return (cookies, threads)

def __extract_threads_on_page(browser):
    time.sleep(3)    # wait for page to load

    # 1st page
    page_soup = bs4.BeautifulSoup(browser.page_source, 'html.parser')
    current_rows = page_soup.find_all("tr", {"class" : "inline_row"})

    threads_meta = []
    for row in current_rows:
        threads_meta.append(__get_thread_meta(row))

    return threads_meta

def __next_page(browser):
    try:
        next_button = browser.find_element_by_class_name('pagination_next')
        next_button.click()
        return True
    except:
        return False    # next button cannot be found or clicked, means on the last page

def __get_thread_meta(row_soup):
    info = row_soup.find_next('a', href=True)
    tid = info['href'].split('&')[0].split('=')[1]
    title = info.get_text()

    author = row_soup.find_next('div', {"class" : "author smalltext"}).get_text()

    reply_count = row_soup.find_next('td', {"class" : "trow1 mobile-remove"}).get_text()
    views = row_soup.find_next('td', {"class" : "trow1 mobile-remove"}).get_text()

    return (tid, author, title, reply_count, views)

def __extract_login_cookies(cookies_list):
    cookie_string = ''

    for cookie in cookies_list:
        cookie_string += cookie['name']
        cookie_string += '='
        cookie_string += cookie['value']
        cookie_string += '; '

    return cookie_string[:-2]    # remove the final '; '

if __name__ == '__main__':
    print('testing')
    # cookies = obtain_cookies_and_thread_meta('fortnite')
    # print(cookies)


class InvalidCsv(Exception):
    pass

class CsvParser:
    def __init__(self, filename, sep=',', header=True):
        self.filename = filename
        self.sep = sep
        self.header = header
        self.columns = []
        self.count_features = None

    def open_csv(self):
        with open(self.filename) as fd:
            if self.header:
                self.columns = next(fd).strip('\n').split(',')
                self.count_features = len(self.columns)
            else:
                self.columns = range(int(1e6))
            for row in fd:
                yield row.strip()

    def read_csv(self):
        for row in self.open_csv():
            row_dict = {}
            flag = False
            column_idx = 0
            for obj in row.strip('\n').split(self.sep):
                try:
                    row_dict[self.columns[column_idx]] = row_dict.get(
                        self.columns[column_idx], '') + obj.strip('"')
                except IndexError:
                    raise InvalidCsv

                if obj.count('"') == 1:
                    flag = not flag

                if flag:
                    row_dict[self.columns[column_idx]] += self.sep
                else:
                    column_idx += 1
            if self.count_features is None:
                self.count_features = len(row_dict)
            if len(row_dict) != self.count_features:
                raise InvalidCsv
            yield row_dict


# -*- coding: utf-8 -*-
# @Time    : 2022/9/6 9:18 AM
# @Author  : Hush
# @Email   : crush@tju.edu.cn

import numpy as np
import matplotlib.pyplot as plt

class LinearRegression:
    def __init__(self, data, data_test):
        self.m = data.shape[0]
        self.cols = data.shape[1] + 1
        self.w = np.zeros(self.cols)
        self.b = np.ones(self.m).reshape(self.m, 1)
        self.lr = 0.000016
        self.train_X = np.hstack([self.b, data])

        self.m_test = data_test.shape[0]
        self.b_test = np.ones(self.m_test).reshape(self.m_test, 1)
        self.test_X = np.hstack([self.b_test, data_test])

    def fit(self, X, Y, X_test, Y_test, epochs):
        i = 0
        loss_record = []
        mae_record = []
        mae_test_record = []
        for i in range(epochs):
            ## predict
            y_hat = self.predict(X)

            ## compute loss
            loss = (np.sum(np.square(Y - y_hat)) / (2 * self.m))
            loss_record.append(loss)

            ## compute gradiant
            grad = (np.dot(X.T, (y_hat - Y)))

            ## update weight----gradient_descent
            self.w = self.w - self.lr * grad

            mae = (np.sum(np.abs(y_hat - Y)) / self.m)
            mae_record.append(mae)

            ## test each epoch
            mae_test = self.test(X_test, Y_test)
            mae_test_record.append(mae_test)
        self.plot_history(loss_record, mae_record, mae_test_record, epochs)
        return loss_record, mae_record, mae_test_record

    def predict(self, X):
        return np.dot(X, self.w)

    def test(self, X, Y):
        mae_test = (np.sum(np.abs(self.predict(X) - Y)) / self.m_test)
        return mae_test

    def plot_history(self, loss_record, acc_record, acc_test_record, epochs):
        plt.figure(figsize=(10, 5))
        plt.subplot(2, 2, 1)
        plt.xlabel('Epoch')
        plt.ylabel('loss')
        plt.plot(range(epochs), loss_record, label='loss')
        plt.legend()
        plt.subplot(2, 2, 2)
        plt.xlabel('Epoch')
        plt.ylabel('mae_train')
        plt.plot(range(epochs), acc_record, label='acc_train')
        plt.subplot(2, 1, 2)
        plt.xlabel('Epoch')
        plt.ylabel('mae_test')
        plt.plot(range(epochs), acc_test_record, label='acc_test', color='red')
        plt.show()


#!/usr/bin/env python3
import sys
import glob
import json
import cv2
import numpy as np

from dataset import resize_image, scale_image, get_name_with_uid
from eval import predict
import config as cfg

def main(picture):
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    img = cv2.imread(picture)

    pic_w, pic_h, pic_d = img.shape

    # img = scale_image(img, 1.5)

    # cv2.imshow('source', img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor = 1.2,
        minNeighbors = 5,
        minSize = (10, 10),
        flags = cv2.CASCADE_SCALE_IMAGE
    )

    face = np.array([], dtype = 'uint8')

    print(len(faces))

    if len(faces) > 0:
        print('Reading model...')
        recognizer = cv2.face.LBPHFaceRecognizer_create()
        recognizer.read(cfg.MODEL_PATH)

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x - 2, y - 2), (x + w + 2, y + h + 5), (255, 0, 0), 5)
        predict_id, percent = predict(recognizer, gray[y : y + h, x : x + w])
        name = get_name_with_uid(predict_id)
        cv2.putText(img, name, (x, y + h), 0, 0.5, (255, 255, 0), 1, cv2.LINE_AA)

    cv2.imwrite('image.jpg', img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

def show_video():
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    video = cv2.VideoCapture(0)

    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.read(cfg.MODEL_PATH)

    while True:
        ret, img = video.read()
        if not ret:
            break
        img = cv2.flip(img, 1)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(
            gray,
            scaleFactor = 1.2,
            minNeighbors = 5,
            minSize = (100, 100),
            flags = cv2.CASCADE_SCALE_IMAGE
        )

        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x - 2, y - 2), (x + w + 2, y + h + 5), (255, 255, 0), 2)
            predict_id, percent = predict(recognizer, gray[y : y + h, x : x + w])
            name = get_name_with_uid(predict_id)
            cv2.putText(img, name, (x, y + h), 0, 0.5, (255, 255, 255), 1, cv2.LINE_AA)

        cv2.imshow('video', img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

if __name__ == '__main__':
    if len(sys.argv) == 2:
        main(sys.argv[1])
    elif len(sys.argv) == 1:
        show_video()
    else:
        print("ERROR")


from ode.rigid_body.rigid_body_dynamics import *
from ode.rigid_body.forces import *
from ode.rotation.rot import *
from ode.utils.plot_frame import *
from ode.control.pid import *
from ode.control.models import *

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numpy import linalg as LA

def main():

    print(' test rigid body dynamics')

    rigid_body      = RigidBodyDynamics()
    rigid_body.m    = 1.0
    dt              = 1.0/1000.0
    t               = 10.0 # time of simulation [s]
    g               = 9.81
    num_steps       = int(t / dt)

    rigid_body.set_position(np.zeros(3))

    record          = np.zeros((3 + 3 + 3,num_steps))
    record_pid      = np.zeros((6 + 6,num_steps))
    Fg              = get_Fg(rigid_body.m,g=9.81)

    config_pid      = {            # position | orientation
                        'Kp' : np.array([4,4,4,4,4,4],dtype=float),
                        'Ki' : np.array([0,0,0,0,0,0],dtype=float),
                        'Kd' : np.array([3,3,3,3,3,3],dtype=float),
                        'max':  50, # [N]
                        'min': -10, # [N]
                        'dt' : dt
                      }

    grav_model      = GravityModel(m = rigid_body.m,g=g)
    uC              = np.zeros(6)
    uC[0:3]         = grav_model.get_control()
    pid             = PID(config_pid)

    pid.add_model_constant(uC)
    pid.set_target(np.array([3,2,1,0,0,np.pi * 0.95],dtype=float))

    for i in range(0,num_steps):

        # controller
        r       = rigid_body.get_position()
        theta   = rigid_body.get_orientation()
        s       = np.append(r,theta)
        u       = pid.update(s)
        Fu      = u[0:3]    # force
        Tu      = u[3:6]    # torque

        F       = Fg + Fu
        T       = np.zeros(3) + Tu

        rigid_body.update(force=F,torque=T,dt=dt)

        record[0:3,i]       = rigid_body.get_position()
        record[3:6,i]       = rigid_body.get_velocity()
        record[6:9,i]       = rigid_body.get_orientation()
        record_pid[0:3,i]   = F
        record_pid[3:6,i]   = T
        record_pid[6:12,i]  = pid.e

    return record_pid, record

def plot_pid(record_pid,record_pos):

    Fu    = record_pid[0:3,:]
    Tu    = record_pid[3:6,:]
    Fe    = record_pid[6:9,:]
    Te    = record_pid[9:12,:]
    r     = record_pos[0:3,:]
    theta = record_pos[6:9,:]

    fig = plt.figure()

    """ Plot for Force """

    ax  = fig.gca
    plt.subplot(321)
    plt.plot(Fu[0,:],'-k',label='Fx')
    plt.plot(Fu[1,:],'--k',label='Fy')
    plt.plot(Fu[2,:],':k',label='Fz')
    plt.legend(loc="upper left", ncol=1, shadow=True, fancybox=True)
    plt.xlabel('t')
    plt.ylabel('[N]')
    plt.title('Control: Force',fontsize=18)

    plt.subplot(323)
    plt.plot(Fe[0,:],'-k',color='r',label='ex')
    plt.plot(Fe[1,:],'--k',color='r',label='ey')
    plt.plot(Fe[2,:],':k',color='r',label='ez')
    plt.legend(loc="upper left", ncol=1, shadow=True, fancybox=True)
    plt.title('Target error',fontsize=18)
    plt.xlabel('t')
    plt.ylabel('[m]')

    plt.subplot(325)
    plt.plot(r[0,:],'-k',color='b',label='x')
    plt.plot(r[1,:],'--k',color='b',label='y')
    plt.plot(r[2,:],':k',color='b',label='z')
    plt.legend(loc="upper left", ncol=1, shadow=True, fancybox=True)
    plt.title('Position',fontsize=18)
    plt.xlabel('t')
    plt.ylabel('[m]')

    """ Plot for Torque """

    plt.subplot(322)
    plt.plot(Tu[0,:],'-k',label='Ta')
    plt.plot(Tu[1,:],'--k',label='Tb')
    plt.plot(Tu[2,:],':k',label='Tg')
    plt.legend(loc="upper left", ncol=1, shadow=True, fancybox=True)
    plt.xlabel('t')
    plt.ylabel('[Nm]')
    plt.title('Control: torque',fontsize=18)

    ax = plt.subplot(324)
    plt.plot(Te[0,:],'-k',color='r',label='ea')
    plt.plot(Te[1,:],'--k',color='r',label='eb')
    plt.plot(Te[2,:],':k',color='r',label='eg')
    ax.set_yticks([-np.pi,-np.pi/2.0, 0, np.pi/2.0, np.pi])
    ax.set_yticklabels([r"$-\pi$", r"$-\frac{1}{2}\pi$",r"$0$", r"$\frac{1}{2}\pi$",r"$\pi$"],fontsize=20)
    plt.legend(loc="upper left", ncol=1, shadow=True, fancybox=True)
    plt.title('Target error',fontsize=18)
    plt.xlabel('t')
    plt.ylabel('[rad]')

    ax = plt.subplot(326)
    plt.plot(theta[0,:],'-k', color='b',label='x')
    plt.plot(theta[1,:],'--k',color='b',label='y')
    plt.plot(theta[2,:],':k', color='b',label='z')
    ax.set_yticks([-np.pi,-np.pi/2.0, 0, np.pi/2.0, np.pi])
    ax.set_yticklabels([r"$-\pi$", r"$-\frac{1}{2}\pi$",r"$0$", r"$\frac{1}{2}\pi$",r"$\pi$"],fontsize=20)
    plt.legend(loc="upper left", ncol=1, shadow=True, fancybox=True)
    plt.title('Orientation',fontsize=18)
    plt.xlabel('t')
    plt.ylabel('[rad]')

    return fig

def plot_trajectory(record,start_v):
    x     = record[0:3,:]
    v     = record[3:6,:]
    euler = record[6:9,:]

    line_v1 = np.stack(  (x[:,0],x[:,0] +  v[:,0])  )

    g               = 9.81
    start_x         = x[:,0]

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    dim  = 5
    X, Y = np.meshgrid([-dim, dim], [-dim, dim])
    Z = np.zeros((2, 2))

    RF_1 = Plot_frame(ax)
    RF_2 = Plot_frame(ax)

    RF_1.update_pos(x[:,0])
    RF_1.update_rot(euler[:,0])

    RF_2.update_pos(x[:,-1])
    RF_2.update_rot(euler[:,-1])

    fig.hold(True)
    ax.plot_surface(X, Y, Z, color='green', alpha=.5, linewidth=0, zorder=1)
    ax.plot(line_v1[:,0], line_v1[:,1], line_v1[:,2], color='r')

    # plot simulation
    ax.scatter(x[0,0], x[1,0], x[2,0],color='g',s=100.0)
    ax.plot(x[0,:], x[1,:], x[2,:],color='r')
    ax.scatter(x[0,-1], x[1,-1], x[2,-1],color='r')

    RF_1.draw()
    RF_2.draw()

    ax.set_xlabel('x [m]')
    ax.set_ylabel('y [m]')
    ax.set_zlabel('z [m]')
    ax.set_xlim([-50,50])
    ax.set_ylim([-50,50])

    return fig

if __name__ == '__main__':

  record_pid, record = main()

  plt.close('all')

  plot_pid(record_pid,record)

  plt.show()


from __future__ import annotations
from typing import Iterator, Mapping, Any, List, Optional, Callable

from spil import Sid, Getter, Finder
from spil.conf import default_path_config, path_data_suffix  # type: ignore

class GetByFinder(Getter):
    """
    Some Getters first use a Finder to retrieve the Sids,
    then, in a second distinct step, retrieve the data.
    For example, GetFromPaths which stores data in json "sidecar" files.

    This "GetByFinder" is an abstract Getter, implementing shared methods for Getters that use a Finder.

    These Getters can inherit GetByFinder, and:
    - override the constructor and define self.finder
    - or pass it to the constructor (inherited from GetByFinder)
    - and implement get_data()
    """

    def __init__(self, finder: Finder):
        self.finder = finder

    def get(
        self,
        search_sid: str | Sid,
        attributes: Optional[List[str]] = None,
        sid_encode: Callable = str,
    ) -> Iterator[Mapping[str, Any]]:
        """
        See Getter.
        """
        for sid in self.finder.find(search_sid=search_sid, as_sid=True):
            data = self.get_data(sid, attributes=attributes, sid_encode=sid_encode) or {}
            yield data

    def do_get(
        self,
        search_sids: List[Sid],
        attributes: Optional[List[str]] = None,
        sid_encode: Callable = str,
    ) -> Iterator[Mapping[str, Any]]:
        """
        See Getter.
        """
        for sid in self.finder.do_find(search_sids=search_sids, as_sid=True):
            data = self.get_data(sid, attributes=attributes, sid_encode=sid_encode) or {}
            yield data

    def get_data(
        self, sid: str | Sid, attributes: Optional[List[str]] = None, sid_encode: Callable = str
    ) -> Mapping[str, Any]:
        """
        See Getter.
        """
        raise NotImplementedError("To be used, GetByFinder should be inherited, and get_data overriden.")

    def __str__(self):
        return f'[spil.{self.__class__.__name__} -- Finder: "{self.finder}"]'

if __name__ == "__main__":
    from spil import FindInPaths

    finder = FindInPaths()
    print(GetByFinder(finder))


import discord
import json
from discord.ext import commands
import random
import datetime
from pytz import common_timezones, timezone
import time
from jikanpy import Jikan
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient

bot = commands.Bot(command_prefix='$')

@bot.command()
async def on_message(ctx):
    embedVar = discord.Embed(title="Title", description="Desc", color=0x00ff00)
    embedVar.add_field(name="Field1", value="hi", inline=False)
    embedVar.add_field(name="Field2", value="hi2", inline=False)
    await ctx.send(embed=embedVar)

#kick an member from the server.
@bot.command()
async def kick(ctx, member: discord.Member, *, reason=None):
    await member.kick(reason=reason)
    await ctx.send(f'User {member} has kicked.')

@bot.command()
async def sai(ctx, member: discord.Member,*, reason=None):
    await member.edit(voice_channel=None)
    await ctx.send(f'User {member} foi de base.')

#its a russian roulet thats kicks from the channel you if get an double $roleta 100
@bot.command()
async def roleta(ctx, i:int):
    n = random.randint(0,i)
    await ctx.send(f'numero {n}')
    ultimo_digito = n % 100
    z = ultimo_digito % 11
    if(z == 0):
        await sai(ctx, ctx.author)

@bot.command()
async def converter(ctx, horario: str, tz1: str, tz2 : str):
    try:
        agora = datetime.datetime.now()
        horario_obj = time.strptime(horario, '%H:%M:%S')
        horario_obj2 = datetime.time(horario_obj.tm_hour,horario_obj.tm_min, horario_obj.tm_sec)
        horario_combinado = datetime.datetime.combine(agora, horario_obj2)
        recebe_tz1 = timezone(tz1)
        recebe_tz2 = timezone(tz2)
        horario_combinadotz1 = recebe_tz1.localize(horario_combinado)
        horario_timezone = horario_combinadotz1.astimezone(recebe_tz2)
        h_formatado = horario_timezone.strftime('%H:%M:%S')
        await ctx.send(f'Horario {horario} na time zone {tz2} é de: {h_formatado}')
    except:
        await ctx.send(f'Digitou o formato do horario errado, ou o TIMEZONE errado')

@bot.command()
async def timezones(ctx):
    i = common_timezones
    n = 6
    len_i = len(i)
    i_splited = []
    for x in range(n):
        start = int(x*len_i/n)
        end = int((x+1)*len_i/n)
        i_splited.append(i[start:end])
    for item in i_splited:
        await ctx.send(f'{item}')

@bot.command()
async def rankedmapsby(ctx, user:str):
    osuid = oauth_osu.get(f'https://osu.ppy.sh/api/v2/users/{user}') #pegando id do usuario
    id = osuid.json()["id"] #pegou id do usuario
    mapsearch= oauth_osu.get(f'https://osu.ppy.sh/api/v2/beatmapsets/search/?q={id}&sort=ranked_desc') #procurando os mapas do usuario pelo id
    beatmapsets = mapsearch.json()['beatmapsets'] #pega a resposta do site do osu e transforma em um dicionario do python

    def chave(beatmap): #retorna a dificuldade do beatmap.
        return beatmap['difficulty_rating']

    for set in beatmapsets:
        artista = set["artist"]
        titulo = set["title"]
        beatmaplink = f'https://osu.ppy.sh/beatmapsets/{set["id"]}'
        cover = set["covers"]["card"]
        beatmaps = sorted(set['beatmaps'], key = chave)
        dificuldades = []

        for diff in beatmaps:
            novadificuldade = diff["version"]
            ar = str(diff["ar"])
            accuracy = str(diff['accuracy'])
            cs = str(diff["cs"])
            bpm = str(diff["bpm"])
            #max_combo = str(diff["max_combo"]) max combo ficou meio ruim na exibicao

            dificuldades.append(novadificuldade + ' | AR: ' + ar + ' | CS: ' + cs + ' | OD: ' + accuracy + ' | bpm: ' + bpm) #+ ' max combo: '+ max_combo)
        dificuldadejuntas = '\n'.join(dificuldades)

        embedVar = discord.Embed(title= titulo,url=beatmaplink, description= artista, color=0x00ff00)
        embedVar.add_field(name="Link", value=beatmaplink, inline=False)
        embedVar.add_field(name="Dificuldades", value=dificuldadejuntas, inline=False)
        embedVar.set_image(url=cover)

        await ctx.send(embed=embedVar)

@bot.command()
async def followson(ctx, user:str):
    twitch_id = oauth_twitch.get(f'https://api.twitch.tv/helix/users?login={user}')
    id = twitch_id.json()['data'][0]['id']
    follows_response = oauth_twitch.get(f'https://api.twitch.tv/helix/users/follows?from_id={id}&first=100')
    lista_de_follows = (follows_response.json()['data'])
    lista_de_ids = []

    #pega os campos to id no follow e aloca no lista_de_ids
    for follow in lista_de_follows:
        lista_de_ids.append(follow['to_id'])

    #ver na lista de ids se o streamer esta
    for follow_id in lista_de_ids:
        verifica_on_response = oauth_twitch.get(f'https://api.twitch.tv/helix/streams?user_id={follow_id}')
        esta_on = verifica_on_response.json()['data']
        if not len(esta_on) == 0:
            nome = esta_on[0]['user_login']
            jogo = esta_on[0]['game_name']
            titulo = esta_on[0]['title'][:100].replace("\n"," ")
            thumb = esta_on[0]['thumbnail_url'].format(width = 250, height = 200)
            link = (f"https://twitch.tv/{nome}")

            embedVar = discord.Embed(title= nome,url=link , description= jogo, color=0x00ff00)
            embedVar.add_field(name="Link", value=link, inline=False)
            embedVar.add_field(name="Titulo", value=titulo, inline=False)
            embedVar.set_image(url=thumb)

            await ctx.send(embed=embedVar)

f = open("config.json", "r")
config = json.load(f)

def criar_client_twitch():
    client_id_twitch = config['twitch-client-id']
    client_secret_twitch = config['twitch-client-secret']
    #scopes_twitch = ['user:read:follows']
    client_twitch = BackendApplicationClient(client_id=client_id_twitch)
    oauth_twitch =  OAuth2Session(client=client_twitch)
    oauth_twitch.headers.update({'Client-Id': client_id_twitch, 'Client-Secret': client_secret_twitch} )
    token = oauth_twitch.fetch_token(include_client_id= True, token_url='https://id.twitch.tv/oauth2/token', client_id= client_id_twitch, client_secret= client_secret_twitch)
    return oauth_twitch

def criar_client_osu():
    client_id = config['osu-client-id']
    client_secret = config['osu-client-secret']
    scopes = ['public']
    client_osu = BackendApplicationClient(client_id=client_id, scope = scopes)
    oauth = OAuth2Session(client=client_osu, scope = scopes)
    token = oauth.fetch_token(token_url='https://osu.ppy.sh/oauth/token', client_id=client_id, client_secret=client_secret)
    return oauth

oauth_osu = criar_client_osu()
oauth_twitch = criar_client_twitch()
bot.run(config['token'])