# -*- coding: UTF-8 -*-

import ConfigParser
import os
import inspect

class Settings():

    rules = {
        'credentials': ['api', 'url', 'room'],
        'aws': ['access_key', 'secret_key']
    }

    default_conf_name = 'example.conf'

    def __init__(self, filename=False):
        """
            Create config object, read config data from file and make
            friendly format ot access to config data
        """

        self.APP_DIR = os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]) + '/../'

        self.CONF_DIR = self.APP_DIR + 'conf/'

        if not filename:
            filename = self.default_conf_name
            self.FILENAME = self.CONF_DIR + filename

        self.CONF_NAME = filename

        config = ConfigParser.ConfigParser()
        config.readfp(open(self.CONF_DIR + filename))

        for section in self.rules.keys():
            data = {}
            for item in self.rules[section]:
                try:
                    data.update({item: str(config.get(section, item)).strip()})
                except ConfigParser.NoOptionError:
                    data.update({item: ''})
                except ConfigParser.NoSectionError:
                    for option in self.rules[section]:
                        data.update({option: False})
                    break

                if data[item].lower() == 'false':
                    data[item] = False

            setattr(self, section, data)


import sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn import naive_bayes, svm, linear_model
from sklearn import neighbors
from sklearn.metrics import accuracy_score

# Use five basic machine learning prediction models to predict:
def train_models(model_name, X_train, y_train):
    if model_name == "Random Forest":
        model = RandomForestClassifier(n_estimators = 200, random_state=0)
    elif model_name == "Naive Bayes":
        model = naive_bayes.MultinomialNB()
    elif model_name == "Logistic Regression":
        model = linear_model.LogisticRegression(penalty = 'l2')
    elif model_name == "SVM":
        model = svm.SVC(kernel = 'linear')
    elif model_name == "KNN":
        model = neighbors.KNeighborsClassifier(n_neighbors=5)

    model.fit(X_train, y_train)
    return model

# Use the model to predict and gives accuracy:s
def make_prediction(model, X_test, y_test):
    predictions = model.predict(X_test)
    accuracy = accuracy_score(predictions, y_test)
    return predictions, accuracy


import numba
import numpy as np

from covid_model_seiir_pipeline.lib.ode_mk2.constants import (
    # Indexing tuples
    COMPARTMENT,
    TRACKING_COMPARTMENT,
    TRACKING_COMPARTMENT_TYPE,
    VARIANT,
    VARIANT_GROUP,
    VACCINE_STATUS,
    EPI_MEASURE,
    AGG_INDEX_TYPE,
    # Indexing arrays
    NEW_E,
    RATES,
    EFFECTIVE_SUSCEPTIBLE,
    COMPARTMENTS,
    TRACKING_COMPARTMENTS,
    # Mappings
    BETA_MAP,
    VACCINE_STATUS_MAP,
    EPI_MEASURE_MAP,
    VACCINE_COUNT_MAP,
)
from covid_model_seiir_pipeline.lib.ode_mk2.debug import (
    DEBUG,
    Printer
)
from covid_model_seiir_pipeline.lib.ode_mk2.utils import (
    cartesian_product,
)

@numba.njit
def compute_tracking_compartments(t: float,
                                  dy: np.ndarray,
                                  new_e: np.ndarray,
                                  effective_susceptible: np.ndarray,
                                  beta: np.ndarray,
                                  rates: np.ndarray,
                                  transition_map: np.ndarray) -> np.ndarray:
    for agg_idx, epi_idx in BETA_MAP:
        beta_idx = TRACKING_COMPARTMENTS[TRACKING_COMPARTMENT_TYPE.Beta, VARIANT.none, VARIANT.none, agg_idx]
        dy[beta_idx] = beta[epi_idx]

    for tc, epi_measure in EPI_MEASURE_MAP:
        for variant_from, variant_to in cartesian_product((np.array(VARIANT), np.array(VARIANT))):
            for agg_vaccine_status, vaccine_status in VACCINE_STATUS_MAP:
                infections = new_e[NEW_E[vaccine_status, variant_from, variant_to]]
                if epi_measure == EPI_MEASURE.infection:
                    rate = 1.0
                else:
                    rate = rates[RATES[vaccine_status, variant_from, variant_to, epi_measure]]
                measure = infections * rate
                if variant_from == VARIANT.none:
                    dy[TRACKING_COMPARTMENTS[tc, VARIANT.none, VARIANT_GROUP.all, AGG_INDEX_TYPE.all]] += measure
                    if vaccine_status == VACCINE_STATUS.course_0:
                        dy[TRACKING_COMPARTMENTS[tc, variant_from, VARIANT_GROUP.all, agg_vaccine_status]] += measure
                        dy[TRACKING_COMPARTMENTS[tc, variant_from, variant_to, agg_vaccine_status]] += measure
                dy[TRACKING_COMPARTMENTS[tc, VARIANT_GROUP.all, VARIANT_GROUP.all, AGG_INDEX_TYPE.all]] += measure
                dy[TRACKING_COMPARTMENTS[tc, VARIANT_GROUP.all, VARIANT_GROUP.all, agg_vaccine_status]] += measure
                dy[TRACKING_COMPARTMENTS[tc, VARIANT_GROUP.all, variant_to, AGG_INDEX_TYPE.all]] += measure

    tc_effs = TRACKING_COMPARTMENT.EffectiveSusceptible
    for variant in VARIANT:
        for tc, agg_idx, from_vax, to_vax in VACCINE_COUNT_MAP:
            dy[TRACKING_COMPARTMENTS[tc, VARIANT_GROUP.all, VARIANT_GROUP.all, agg_idx]] += (
                transition_map[COMPARTMENTS[COMPARTMENT.S, from_vax, variant],
                               COMPARTMENTS[COMPARTMENT.S, to_vax, variant]]
            )

        for variant_from, vaccine_status in cartesian_product((np.array(VARIANT), np.array(VACCINE_STATUS))):
            dy[TRACKING_COMPARTMENTS[tc_effs, VARIANT_GROUP.all, variant, AGG_INDEX_TYPE.all]] += (
                effective_susceptible[EFFECTIVE_SUSCEPTIBLE[vaccine_status, variant_from, variant]]
            )

    if DEBUG:
        assert np.all(np.isfinite(dy))
    return dy


'''
Desenvolver um programa que pergunte dois números inteiros, e apresente como resultado se o segundo
número informado é ou não um divisor do primeiro número informado.
'''

num1 = int(input("Me informe um número: "))
num2 = int(input("Me informe outro número: "))

resto = num1 % num2

if(resto == 0 ):
    print(f"O {num2} é um divisor de {num1}.")
else:
    print(f"O {num2} não é um divisor de {num1}")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
txtToExcel.py
Created on Mon Aug  2 00:55:05 2021

@author: paulmason

program that reads the contents of text files in the current directoy and inserts them
into an Excel spreadsheet with one line per row
the lines of file one will be in column A, file two in B, and so on

steps:
    1. get the cd using os library function getcwd()
    2. use openpyxl library to create a new blank Workbook object and get the active sheet
    3. use the os library's listdir() method to find all .txt files
    4. use the readlines() File method to get the list of strings per line in the .txt file then use
       a for loop to insert each line into the blank Workbook object
    5. save the Workbook object and name it 'txtSpreadsheet.xlsx'
"""

#import openpyxl to create a blank workbook object and save to it and os to get the cd and find all txt files
import openpyxl, os
#import get_column_letter function to switch from index value to letter values for columns
from openpyxl.utils import get_column_letter

#step 1
#output what the program does to the user
print('This program puts each line of .txt files in the CWD into an Excel file.')
#get the current working directory
cwd = os.getcwd()
#output the cwd
print('The current working directoy is: %s' % (cwd))

#step 2
#create a blank workbook
wb = openpyxl.Workbook()
#get the active sheet in the workbook
sheet = wb.active

#step 3
#create an empty list to store the text files in
txtFiles = []
#loop through all files in the cwd using listdir() method
for file in os.listdir(cwd):
    #make sure the file ends with '.txt'
    if file.endswith('.txt'):
        #append the txt file to txtFiles
        txtFiles.append(file)

#step 4
#loop through the txtFiles list but get the index to make adding the the workbook easier
for i in range(len(txtFiles)):
    #output to user what file is being openned
    print('Opening file: %s...' % txtFiles[i])
    #open the .txt file
    f = open(txtFiles[i], 'r')
    #store the lines of the file in a list called lines
    lines = f.readlines()

    #loop through lines getting the index of each line to make it easier to add to the workbook
    for j in range(len(lines)):
        #get the column letter from i's value (add one since Excel sheets start at 1 not 0)
        colLetter = get_column_letter(i + 1)
        #output to user what column and row is being created
        print('Inserting text into row %s column %s...' % (str(j+1), colLetter))
        #now insert the value in lines in cell 'ij'
        sheet[colLetter + str(j + 1)] = lines[j]

#step 5
#save the workbook with name txtSpreadsheet
wb.save('txtSpreadsheet.xlsx')
#output to user program is done
print("Done, Excel file created in CWD titled: 'txtSpreadsheet.xlsx'")

Chapter 13 - Working with Excel Spreadsheets/txtToExcel.py


from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from io import BytesIO
import pandas as pd

def create_pdf(dataframe, filename, chat_log, selected_data):
    # Crie um buffer de bytes para armazenar o PDF
    buffer = BytesIO()

    # Crie um documento PDF com o ReportLab
    doc = SimpleDocTemplate(buffer, pagesize=letter)

    # Adicione os dados selecionados ao PDF
    elements = []

    styles = getSampleStyleSheet()

    # Adicione os dados da tabela
    data = [dataframe.columns.tolist()] + dataframe.values.tolist()
    table = Table(data)

    centered_title_style = ParagraphStyle(
        'CenteredTitle',
        parent=styles['Heading1'],
        alignment=1,  # 1 significa centralizado
    )

    # Adicione "RELATÓRIO FORD" centralizado
    title = Paragraph("RELATÓRIO FORD", centered_title_style)
    elements.append(title)
    elements.append(Spacer(1, 20))

    # Estilize a tabela
    style = TableStyle([('BACKGROUND', (0, 0), (-1, 0), (0.8, 0.8, 0.8)),
                        ('TEXTCOLOR', (0, 0), (-1, 0), (0, 0, 0)),
                        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                        ('BACKGROUND', (0, 1), (-1, -1), (0.95, 0.95, 0.95)),
                        ('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)),
                        ('GRID', (0, 0), (-1, 0), 2, (0, 0, 0))])

    table.setStyle(style)
    elements.append(table)

    # elements.append(Paragraph("Dados Selecionados:", styles['Normal']))
    # for entry in selected_data:
    #     elements.append(Paragraph(entry, styles['Normal']))

    elements.append(Spacer(1, 20))
    # Adicione o log de perguntas e respostas do chat
    elements.append(Paragraph("Chat Log:", styles['Heading1']))
    if chat_log is not None:
        for entry in chat_log:
            question, answer = entry
            elements.append(Paragraph(f"Pergunta: {question}", styles['Normal']))
            elements.append(Spacer(1, 10))
            elements.append(Paragraph(f"Resposta: {answer}", styles['Normal']))
            elements.append(Spacer(1, 30))
    else:
        elements.append(Paragraph("Nenhuma pergunta foi feita", styles['Normal']))

    # Construa o PDF
    doc.build(elements)

    # Salve o PDF no arquivo especificado
    with open(filename, 'wb') as f:
        f.write(buffer.getvalue())


#!/usr/bin/python3
"""Module: For defining the Rectangle class.."""

class Rectangle:
    """ Class: For defining a Rectangule object. """
    def __init__(self, width=0, height=0):
        """ Method that initializes the class """
        self.width = width
        self.height = height

    @property
    def width(self):
        """ Private Attribute width Getter """
        return self.__width

    @width.setter
    def width(self, value):
        """ Private Attribute width Setter """
        if type(value) == int:
            if value < 0:
                raise ValueError("width must be >= 0")
            else:
                self.__width = value
        else:
            raise TypeError("width must be an integer")

    @property
    def height(self):
        """ Private Attribute height Getter """
        return self.__height

    @height.setter
    def height(self, value):
        """ Private Attribute height Setter """
        if type(value) == int:
            if value < 0:
                raise ValueError("height must be >= 0")
            else:
                self.__height = value
        else:
            raise TypeError("height must be an integer")


import geopandas as gp
import numpy as np
from shapely import geometry
import networkx as nx
import pyproj as proj
import numexpr as num
import json
import pickle
from workspace import street_name_exists

#bellevue data pickle: bellevue0526
#aus data pickle: sgraphs_aus_bounded.pickle
with open('bellevue0603.pickle', 'rb') as f:
    sgraphs_data = pickle.load(f)

def merge_edges(G):
    starting_nodes = []
    newG = nx.DiGraph()
    # make a list of starting nodes
    # print("SUBGRAPH EDGES \n")
    # print(G.edges(data=True))
    for n in G.nodes():
        if G.degree(nbunch=n) == 2: # in-degree plus out-degree
            starting_nodes.append(n)
        if G.degree(nbunch=n) == 0:
            G.remove_node(n)

    print("starting nodes count: ", len(starting_nodes))
    # iterate through starting nodes to connect sidewalks
    for node in starting_nodes:
        geom_all = []
        first_neigh = next(G.successors(node))
        edge_data_1 = G.get_edge_data(node, first_neigh)
        print(edge_data_1)
        init_geom = edge_data_1['geometry']
        fwd = edge_data_1['forward']
        street = edge_data_1['street']
        geom_all.append(init_geom)
        print("starting node ", node)
        print("first neigh ", first_neigh)
        prev_neigh = node
        while (G.has_node(first_neigh)) and (G.degree(nbunch=first_neigh) != 2): #in-degree plus out-degree. caught in loop here?
            print("start while loop")
            second_neigh = G.successors(first_neigh)  # Returns an iterator over successor nodes of n.
            for neigh in second_neigh:
                if neigh != prev_neigh and neigh != first_neigh: # select node going in correct direction
                    second_neigh = neigh
            edge_data_2 = G.get_edge_data(first_neigh, second_neigh)
            if (edge_data_2 is not None):
                next_geom = edge_data_2['geometry']
                geom_all.append(next_geom)
            prev_neigh = first_neigh
            first_neigh = second_neigh
        dict_info = {
            'forward': fwd,
            'street': street,
            'geometry': geom_all,
        }
        newG.add_edge(node, first_neigh, **dict_info)
    return newG

def main():
    # print(len(sgraphs))
    combined = nx.DiGraph() # giant graph - combination of all subgraphs
    for sg in sgraphs_data:
        # if street_name_exists:
            # sg = merge_edges(sg)
        sg = merge_edges(sg)    # may need to comment out
        sg_edges = sg.edges(data=True)
        combined.add_edges_from(sg_edges)

    # Output as edgelist
    # nx.write_edgelist(combined,'bell_data_edges.edgelist')

    # Output as GeoJSON
    allFeatures = list()
    for e in combined.edges(data=True):
        # get starting node and ending node
        startn = e[0]
        point1 = []
        point2 = []
        edge_geom = []
        endn = e[1]
        # add starting node to coordinates array
        point1.append(startn[0])
        point1.append(startn[1])
        edge_geom.append(point1)

        # get dictionary of data with rest of geom
        ddict = e[2].get("geometry")

        # get forward, street, and visited information
        fwd = e[2].get("forward")
        street = e[2].get("street")
        surface = e[2].get("surface").lower()

        #add next point
        if not isinstance(ddict, list):
            ddict = [ddict]
        nextSeg = ddict[0]
        nextPoint = nextSeg.coords[0]
        point2.append(nextPoint[0])
        point2.append(nextPoint[1])
        edge_geom.append(point2)

        # iterate through linestrings, create and add array of segment with arrays of points
        for linestring in ddict:
            segCoords = linestring.coords
            for point in segCoords:
                newPoint = []
                newPoint.append(point[0])
                newPoint.append(point[1])
                edge_geom.append(newPoint)

        # add second to last point
        ptFinal1 = []
        lastSeg = ddict[len(ddict)-1]
        lastPoint = lastSeg.coords[-1]
        ptFinal1.append(lastPoint[0])
        ptFinal1.append(lastPoint[1])

        # add final point
        ptFinal2 = []
        ptFinal2.append(endn[0])
        ptFinal2.append(endn[1])

        # add last segment of edge
        edge_geom.append(ptFinal1)
        edge_geom.append(ptFinal2)

        info = {"highway": "footway", "surface": surface}
        gmt = {"type": "LineString", "coordinates": edge_geom}

        feat = {"type": "Feature", "geometry": gmt, "properties": info}

        allFeatures.append(feat)

    featCollection = {"type": "FeatureCollection", "features": allFeatures}

    with open('bell_edges_603_v2.json', 'w') as f:  # writing JSON object
        json.dump(featCollection, f)

if __name__ == "__main__":
    main()


from secrets import choice
from flask import Flask, flash, redirect ,render_template, request, jsonify, url_for
from database import db,Links

import datetime
from validator_collection import checkers
import pyperclip

app = Flask(__name__,instance_relative_config = False)
app.config.from_object('config.Config')
token_characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"

def init_db():
    db.init_app(app)
    db.app = app
    db.create_all()
init_db()

@app.route('/',methods=['GET','POST'])
@app.route('/home',methods=['GET','POST'])
def home():
    return render_template("home.html")

@app.route('/long',methods=['GET','POST'])
def encode():
    if request.method == 'POST':
        longurl = request.form['long-url']
        if "http" not in longurl:
            longurl = "http://"+longurl
        print(longurl)
        if not checkers.is_url(longurl):
            flash("Enter a Valid URL for eg: www.google.com or google.com","warning")
            return render_template('home.html')

        if request.form['custom-url'] != "":
            token = request.form['custom-url']
        else:
            token = "".join(choice(token_characters) for i in range(7))
        try:
            info = Links(longURL = longurl, shortURL = token)
            db.session.add(info)
            db.session.commit()
            print("Links Recieved")
            flash("Copied to Clipboard","success")
            pyperclip.copy("127.0.0.1:5000/"+token)
        except Exception as e:
            flash("Custom URL already exists.","danger")
            print(e)

    return render_template('home.html',token = token)

@app.route('/<short>',methods = ['GET','POST'])
def toLong(short):
    if request.method == 'GET':
        long = Links.hasShortURL(short)
        print(long)
        if long != None:
            return redirect(long)
    return redirect('/')

if __name__ == '__main__':
    app.run()


# coding:utf-8
import time
import config as cfg
import requests
from lxml import etree
import pymysql as mdb
import datetime
from selenium import webdriver

class IPFactory:
    """
    代理ip抓取/评估/存储一体化。
    """
    def __init__(self):
        self.page_num = cfg.page_num
        self.round = cfg.examine_round
        self.timeout = cfg.timeout
        self.all_ip = set()
        results = self.get_proxies( )
        self.all_ip.update(results)

    def craw_proxy(self):
        #  创建数据库
        self.create_db()

        # # 抓取全部ip
        current_ips = self.get_all_ip()
        # # 获取有效ip
        valid_ip = self.get_the_best(current_ips, self.timeout, self.round)
        print( valid_ip)
        self.save_to_db( valid_ip)

    def create_db(self):
        """
        创建数据库用于保存有效ip
        """
        # 创建数据库/表语句
        # 创建数据库
        drop_db_str = 'drop database if exists ' + cfg.DB_NAME + ' ;'
        create_db_str = 'create database if not exists ' + cfg.DB_NAME  + ' ;'
        # 选择该数据库
        use_db_str = 'use ' + cfg.DB_NAME + ' ;'
        # 创建表格
        create_table_str = "CREATE TABLE if not exists " + cfg.TABLE_NAME + """(
          `content` varchar(30) NOT NULL,
          `test_times` int(5) NOT NULL DEFAULT '0',
          `failure_times` int(5) NOT NULL DEFAULT '0',
          `success_rate` float(5,2) NOT NULL DEFAULT '0.00',
          `avg_response_time` float NOT NULL DEFAULT '0',
          `score` float(5,2) NOT NULL DEFAULT '0.00'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""

        # 连接数据库
        conn = mdb.connect(cfg.host, cfg.user, cfg.passwd)
        cursor = conn.cursor()
        try:
            cursor.execute(use_db_str)
            cursor.execute('truncate table ' + cfg.TABLE_NAME )
            cursor.execute(create_db_str)
            cursor.execute(create_table_str)
            conn.commit()
        except OSError:
            print ("无法创建数据库！")
        finally:
            cursor.close()
            conn.close()
    def decode_text(self,html):
        myencoding = ""
        if  html.encoding == 'ISO-8859-1':
            encodings = requests.utils.get_encodings_from_content(html.text)
            if encodings:
                myencoding = encodings[0]
            else:
                myencoding = html.apparent_encoding
        html_text = html.text.encode('ISO-8859-1').decode(myencoding, 'replace')
        return   html_text

    def get_proxy_list(self,url,url_xpath):
        '''
        返回抓取到代理的列表
        整个爬虫的关键
        '''
        options = webdriver.ChromeOptions()

        options.add_argument("--headless")
        browser = webdriver.Chrome(chrome_options = options,executable_path='D:\\chromedriver.exe')
        browser.implicitly_wait(30)
        browser.maximize_window()
        proxy_list = []

        browser.get(url)
        browser.implicitly_wait(3)
        # 找到代理table的位置
        elements = browser.find_elements_by_xpath(url_xpath)
        for element in elements:
            ip = element.find_element_by_xpath('./td[1]').text
            port = element.find_element_by_xpath('./td[2]').text
            ip_addr=ip+':' +port
            print( ip_addr)
            proxy_list.append( ip_addr)

        browser.quit()
        return proxy_list

    def get_proxy_list2(self,url,url_xpath):
        '''
        返回抓取到代理的列表
        整个爬虫的关键
        '''
        options = webdriver.ChromeOptions()

        options.add_argument("--headless")
        browser = webdriver.Chrome(chrome_options = options,executable_path='D:\\chromedriver.exe')
        browser.implicitly_wait(30)
        browser.maximize_window()
        proxy_list = []

        browser.get(url)
        browser.implicitly_wait(3)
        # 找到代理table的位置
        elements = browser.find_elements_by_xpath(url_xpath)
        for element in elements:
            ip = element.find_element_by_xpath('./td[1]').text
            port = element.find_element_by_xpath('./td[2]').text
            ip_addr=ip+':' +port
            print( ip_addr)
            proxy_list.append( ip_addr)

        browser.quit()
        return proxy_list

    def get_content(self, url, url_xpath, port_xpath):
        """
        使用xpath解析网页内容,并返回ip列表。
        """
        # 返回列表
        ip_list = []

        try:
            # 设置请求头信息
            headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'}

            # 获取页面数据
            results = requests.get(url, headers=headers, timeout=4)
           # html_text =self.decode_text(results)
            tree = etree.HTML(results.text)

            # 提取ip:port
            url_results = tree.xpath(url_xpath)
            port_results = tree.xpath(port_xpath)
            urls = [line.strip() for line in url_results]
            ports = [line.strip() for line in port_results]

            if len(urls) == len(ports):
                for i in range(len(urls)):
                    # 匹配ip:port对
                    full_ip = urls[i]+":"+ports[i]
                    # 此处利用all_ip对过往爬取的ip做了记录，下次再爬时如果发现
                    # 已经爬过，就不再加入ip列表。
                    if full_ip in self.all_ip:
                        continue
                    # 存储
                    ip_list.append(full_ip)
        except Exception as e:
            print ('get proxies error: ', e)

        return ip_list

    def get_all_ip(self):
        """
        各大网站抓取的ip聚合。
        """
        # 有2个概念：all_ip和current_all_ip。前者保存了历次抓取的ip，后者只保存本次的抓取。
        current_all_ip = set()

        ##################################
        # 66ip网
        ###################################
        print(" crawl http://www.66ip.cn/ " )
        url_xpath_66 = '//*[@id="main"]/div/div[1]/table/tbody/tr[position()>1]'
        for i in range(2,self.page_num+1):
            url_66 = 'http://www.66ip.cn/' + str(i+1) + '.html'
            results = self.get_proxy_list(url_66, url_xpath_66)
            self.all_ip.update(results)
            current_all_ip.update(results)
            # 停0.5s再抓取
            time.sleep(0.5)
        url_xpath_66 = '//*[@id="footer"]/div/table/tbody/tr[position()>1]'

        for m in range(1, 35):
            url_66 ='http://www.66ip.cn/areaindex_%s/1.html' % (m)
            results = self.get_proxy_list(url_66, url_xpath_66)
            self.all_ip.update(results)
            current_all_ip.update(results)
            # 停0.5s再抓取
            time.sleep(0.5)
        ##################################
        print(" crawl http://www.kuaidaili.com/free/inha " )
        url_xpath_kuaidaili = '//*[@id="list"]/table/tbody/tr[position()>1]'

        for m in range(1, 3):
            url_kuaidaili ='http://www.kuaidaili.com/free/inha/%s' % (m)
            results = self.get_proxy_list(url_kuaidaili, url_xpath_kuaidaili)
            self.all_ip.update(results)
            current_all_ip.update(results)
            # 停0.5s再抓取
            time.sleep(0.5)
        ##################################
        # xici代理
        ###################################
        print(" crawl http://www.xicidaili.com/nn/ " )
        url_xpath_xici = '//*[@id="footer"]/div/table/tbody/tr[position()>1]'

        for i in range(1,9):
            url_xici = 'http://www.xicidaili.com/nn/' + str(i+1)
            results = self.get_proxy_list2(url_xici, url_xpath_xici)
            self.all_ip.update(results)
            current_all_ip.update(results)
            time.sleep(0.5)

        ##################################
        # mimiip网
        ###################################
# =============================================================================
#         print(" crawl http://www.mimiip.com/gngao/ " )
#         url_xpath_mimi = '//*[@id="middle_wrapper"]/div/table/tbody/tr[position()>1]'
#
#         for i in range(1,2):
#             url_mimi = 'http://www.mimiip.com/gngao/' + str(i+1)
#             results = self.get_proxy_list(url_mimi, url_xpath_mimi)
#             self.all_ip.update(results)
#             current_all_ip.update(results)
#             time.sleep(0.5)
#
# =============================================================================

        return current_all_ip

    def get_valid_ip(self, ip_set, timeout):
        """
        代理ip可用性测试
        """
        # 设置请求地址
        url = 'http://quotes.money.163.com/stock'

        # 可用代理结果
        results = set()

        # 挨个检查代理是否可用
        for p in ip_set:
            proxy = {'http': 'http://'+p}
            try:
                # 请求开始时间
                start = time.time()
                r = requests.get(url, proxies=proxy, timeout=timeout)
                # 请求结束时间
                end = time.time()
                # 判断是否可用
                if r.text is not None:
                    print( 'succeed: ' + p + '\t' + " in " + format(end-start, '0.2f') + 's')
                    # 追加代理ip到返回的set中
                    results.add(p)
            except OSError:
                print ('timeout:', p)

        return results

    def get_the_best(self, valid_ip, timeout, round):
        """
        N轮检测ip列表，避免"辉煌的15分钟"
        """
        # 循环检查次数
        for i in range(round):
            print ("\n>>>>>>>\tRound\t"+str(i+1)+"\t<<<<<<<<<<")
            # 检查代理是否可用
            valid_ip = self.get_valid_ip(valid_ip, timeout)
            # 停一下
            if i < round-1:
                time.sleep(30)

        # 返回可用数据
        return valid_ip

    def save_to_db(self, valid_ips):
        """
        将可用的ip存储进mysql数据库
        """
        if len(valid_ips) == 0:
            print( "本次没有抓到可用ip。")
            return
        # 连接数据库
        print ("\n>>>>>>>>>>>>>>>>>>>> 代理数据入库处理 Start  <<<<<<<<<<<<<<<<<<<<<<\n")
        conn = mdb.connect(cfg.host, cfg.user, cfg.passwd, cfg.DB_NAME)
        cursor = conn.cursor()
        try:
            for item in valid_ips:
                # 检查表中是否存在数据
                item_exist = cursor.execute('SELECT * FROM %s WHERE content="%s"' %(cfg.TABLE_NAME, item))

                # 新增代理数据入库
                if item_exist == 0:
                    # 插入数据
                    n = cursor.execute('INSERT INTO %s VALUES("%s", 1, 0, 0, 1.0, 2.5)' %(cfg.TABLE_NAME, item))
                    conn.commit()

                    # 输出入库状态
                    if n:
                        print (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+" "+item+" 插入成功。\n")
                    else:
                        print (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+" "+item+" 插入失败。\n")

                else:
                    print (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+" "+ item +" 已存在。\n")
        except Exception as e:
            print ("入库失败：" + str(e))
        finally:
            cursor.close()
            conn.close()
        print( "\n>>>>>>>>>>>>>>>>>>>> 代理数据入库处理 End  <<<<<<<<<<<<<<<<<<<<<<\n")

    def get_proxies(self):
        ip_list = []

        # 连接数据库
        conn = mdb.connect(cfg.host, cfg.user, cfg.passwd, cfg.DB_NAME)
        cursor = conn.cursor()

        # 检查数据表中是否有数据
        try:
            cursor.execute('SELECT * FROM %s ' % cfg.TABLE_NAME)

            # 提取数据
            result = cursor.fetchall()

            # 若表里有数据　直接返回，没有则抓取再返回
            if len(result):
                for item in result:
                    ip_list.append(item[0])
            else:
                # 获取代理数据
                current_ips = self.get_all_ip()
                valid_ips = self.get_the_best(current_ips, self.timeout, self.round)
                self.save_to_db(valid_ips)
                ip_list.extend(valid_ips)
        except Exception as e:
            print ("从数据库获取ip失败！")
        finally:
            cursor.close()
            conn.close()

        return ip_list

def main():
    # 抓取搜索关键词
    ip_factory = IPFactory()

    # 抓取数据
    ip_factory. craw_proxy()

if __name__ == '__main__':
    main()


import pickle

import numpy as np
from keras.callbacks import ModelCheckpoint
from keras.layers import Dense, Flatten, Conv2D
from keras.layers import MaxPooling2D, Dropout
from keras.models import Sequential
from keras.utils import np_utils
from keras.utils import print_summary
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle

def loadFromPickle():
    with open("features_numbers_letters", "rb") as f:
        features = np.array(pickle.load(f))
    with open("labels_numbers_letters", "rb") as f:
        labels = np.array(pickle.load(f))

    return features, labels

def keras_model(image_x, image_y):
    num_of_classes = 33
    model = Sequential()
    model.add(Conv2D(32, (5, 5), input_shape=(image_x, image_y, 1), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))
    model.add(Conv2D(64, (5, 5), activation='relu'))
    model.add(MaxPooling2D(pool_size=(5, 5), strides=(5, 5), padding='same'))
    model.add(Flatten())
    model.add(Dense(1024, activation='relu'))
    model.add(Dropout(0.6))
    model.add(Dense(num_of_classes, activation='softmax'))

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    filepath = "ISL.h5"
    checkpoint1 = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
    callbacks_list = [checkpoint1]

    return model, callbacks_list

def main():
    features, labels = loadFromPickle()
    # loadFromPicklefeatures, labels = augmentData(features, labels)
    features = features / 127.5 - 1.
    features, labels = shuffle(features, labels)
    train_x, test_x, train_y, test_y = train_test_split(features, labels, random_state=0,
                                                        test_size=0.1)
    train_y = np_utils.to_categorical(train_y)
    test_y = np_utils.to_categorical(test_y)
    # train_y = train_y.reshape(train_y.shape[1], train_y.shape[2])

    # test_y = test_y.reshape(test_y.shape[1], test_y.shape[2])
    train_x = train_x.reshape(train_x.shape[0], 50, 50, 1)
    test_x = test_x.reshape(test_x.shape[0], 50, 50, 1)
    model, callbacks_list = keras_model(50,50)
    print_summary(model)
    model.fit(train_x, train_y, validation_data=(test_x, test_y), epochs=1, batch_size=64,
              callbacks=callbacks_list)
    model.save('ISL.h5')

main()


## Initialisation
import boilerBot.lib as lib
import nextcord

from  nextcord.ext import commands, tasks
from common import Player

## Define command cog
class skip(commands.Cog):
    ## Initialise with help info
    def __init__(self,bot):
        self.bot = bot
        self.category = lib.getCategory(self.__module__)
        self.description = "Skip the current track"
        self.usage = f"""
        {self.bot.command_prefix}skip
        """
        self.hidden = False

    @nextcord.slash_command()
    async def skip(self, ctx):
        """Skip the current track.

        Parameters
        ----------
            ctx: Interaction
                The interaction object
        """
        guildVars = lib.retrieve(ctx.guild.id, self.bot)
        if not guildVars["player"]:
            embed = lib.embed(
                title="Not playing anything",
                color = lib.errorColour
            )
            guildVars["previous"] = await lib.send(ctx,embed,guildVars["previous"])
            lib.set(ctx.guild.id,self.bot,guildVars)
            return
        title = guildVars["player"].queue[0].title
        guildVars["player"].voiceclient.stop()
        lib.set(ctx.guild.id, self.bot, guildVars)
        embed=lib.embed(
            title=f"Skipped {title}"
        )
        guildVars["previous"] = await lib.send(ctx,embed,guildVars["previous"])
        lib.set(ctx.guild.id,self.bot,guildVars)
        return

def setup(bot):
    bot.add_cog(skip(bot))


import torch
import numpy as np
from collections import OrderedDict
from tqdm import tqdm
from sklearn import metrics
import os
from .postdataset import PostDataset

from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.dataloader import default_collate

from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold

TRAIN_BATCH_SIZE = 16
VALID_BATCH_SIZE = 4

class KFoldSplit():
    def __init__(self, p_data, k_folds = 5):
        self.k_folds = k_folds
        self.data = np.load(p_data, allow_pickle=True)
        self.kfold = KFold(n_splits=k_folds, shuffle=False)
        self.folds = [f[1] for f in self.split()]
        self.cur_test_fold = 0

        # print(folds)

    def split(self):
        return self.kfold.split(self.data)

    def get_split(self, train_ratio = -1, save_test = True): # one out of four
        # train_ratio == 1: testset for early-stopping  -1: one fold for early-stopping
        i_test = self.folds[self.cur_test_fold]
        x_test = self.data[i_test]
        mask = np.ones(len(self.data), bool)
        mask[i_test] = False
        x_train_val = self.data[mask]
        self.cur_test_fold = self.cur_test_fold+1
        assert (self.cur_test_fold<=self.k_folds), 'Out of boundary.'

        if train_ratio == 1:
            x_train = x_train_val
            x_val= x_test
        else:
            if train_ratio == -1:
                train_ratio = (self.k_folds-2) / (self.k_folds-1)
            x_train, x_val = train_test_split(x_train_val, test_size=1-train_ratio, random_state=0)
        # print(len(x_train), len(x_val), len(x_test))

        if save_test == True:
            output_folder_path = './output/'
            if not os.path.exists(output_folder_path):
                os.makedirs(output_folder_path)
            np.save(os.path.join(output_folder_path, str(self.cur_test_fold-1) + '_testset.npy'), x_test, allow_pickle=True)
        return x_train, x_val, x_test

class DataPreprocessor():
    def __init__(self, x_train, x_val, x_test, tokenizer, max_len, fea_config, device):
        self.x_train, self.x_val, self.x_test = x_train, x_val, x_test
        self.tokenizer = tokenizer
        self.training_set = PostDataset(self.x_train, tokenizer, max_len, fea_config, device)
        self.validation_set = PostDataset(self.x_val, tokenizer, max_len, fea_config, device)
        self.testing_set = PostDataset(self.x_test, tokenizer, max_len, fea_config, device)

    def get_train_dataloader(self):
        params = {'batch_size': TRAIN_BATCH_SIZE,
                        'shuffle': False,
                        'num_workers': 0
                        }
        return DataLoader(self.training_set, **params)

    def get_val_dataloader(self):
        params = {'batch_size': VALID_BATCH_SIZE,
                        'shuffle': False,
                        'num_workers': 0
                        }
        return DataLoader(self.validation_set, **params)

    def get_test_dataloader(self):
        params = {'batch_size': VALID_BATCH_SIZE,
                        'shuffle': False,
                        'num_workers': 0
                        }
        return DataLoader(self.testing_set, **params)

if __name__ == "__main__":
    print("data processor.")
    p_data = '../dataset/all_annotated_post_784.npy'
    k_fold_obj = KFoldSplit(p_data, 5)
    # folds = k_fold_obj.split()
    x_train, x_val, x_test = k_fold_obj.get_split()
    print(x_test[0])
#     from transformers import *
#     from torch import cuda

#     fea_config = {
#         'code_fea' : False,
#         'word_cnt' : False,
#         'readability' : False,
#         'sentiment' : False
#     }
#     device = 'cuda' if cuda.is_available() else 'cpu'
#     tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
#     dp = DataPreprocessor(x_train, x_val, x_test, tokenizer, 128, fea_config, device)

#     vdl = dp.get_val_dataloader()


import argparse
import sys

class Parser(argparse.ArgumentParser):
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)

def parse_args(args=None):
    parser = Parser(prog='git resolutions',
                    usage='%(prog)s --prepare | --pull | --push | <commit-ish>',
                    description='publish merge resolutions')
    parser.set_defaults(action='merge')
    parser.add_argument('-i', '--install', dest='action', action='store_const',
                        const='install', help='install git resolutions')
    parser.add_argument('-l', '--pull', dest='action', action='store_const',
                        const='fetch', help='pull resolutions from origin')
    parser.add_argument('-p', '--push', dest='action', action='store_const',
                        const='publish', help='push resolutions to origin')
    parser.add_argument('-f', '--force', dest='force', action='store_true',
                        help='force command, even on mixmatch')
    parser.add_argument('--directory')
    parser.add_argument('ref',
                        help=('commit-ish object names to merge'),
                        metavar='commit-ish', nargs='?')
    args = parser.parse_args(args)
    return args, parser


import numpy as np
import pickle
from numpy.linalg import  svd
import scipy.linalg as la
from tensorly.cp_tensor import cp_to_tensor
from tensorly import kr
from tensorly.decomposition import parafac
import tensorly as tl
import math

def algo2(R, X, Y, task_function, r, d3, A):

    N, d1 = X.shape

    #get an estimate of A1
    M = np.zeros((d1,d1))
    for i in range(N):
        M += R[i]*R[i] * (X[i] @ X[i].T)
    M = 1/float(N) * M
    B, D, B1  = svd(M, full_matrices=False)
    A1 = B[:, :r]

    #get an estimate of A2
    _, d2 = Y.shape
    M = np.zeros((d2, d2))
    for i in range(N):
        M += R[i]*R[i] * (Y[task_function[i]] @ Y[task_function[i]].T)
    M = 1/float(N) * M
    B, D, B1 = svd(M, full_matrices=False)
    A2 = B[:, :r]

    #use estimates A1 and A2 to get an estimate of A3
    M = np.zeros((r, r))
    #print(A2.shape)
    #print(A1.shape)
    krprod = kr((A2, A1))
    for i in range(N):
        P = np.kron(Y[task_function[i]], X[i]) @ krprod
        M += R[i]*R[i] * (P @ P.T)
    #print(M.shape)
    B, D, B1 = svd(M, full_matrices=False)
    C3 = B[:, :r]
    C3 = np.concatenate((C3, np.zeros((r, d3-r))), axis=1)
    A3 = C3.T
    #print(A3.shape)
    weights = np.ones(r)

    est_A = cp_to_tensor((weights, [A1, A2, A3]))
    #print(est_A.shape)
    weights, factors = parafac(A,r)
    #theta1 = math.acos(np.linalg.norm(factors[0].T @ A1, ord=2))
    print(np.linalg.norm(factors[0].T @ A1, ord=2))
    print(np.linalg.norm(factors[1].T @ A2, ord=2))
    #print(math.sin(theta1))
    #theta2 = math.acos(np.linalg.norm(factors[1].T @ A2, ord=2))
    #print(math.sin(theta2))
    #print(tl.norm(factors[2]-A3)/ tl.norm(A3))
    return A1, A2


import random

def main():

    #creating lists of different emoji features
    eyes = [':',';','X','8']
    noses = ['*','-','>','o','']
    mouths = ['D','P',')','(','/','[']

    print('Here are 5 emojis:\n')

    #creating REPL for 5 emoji outputs
    counter = 1
    while counter < 6:
        randoEyes = random.choice(eyes)
        randoNose = random.choice(noses)
        randoMouth = random.choice(mouths)

        print(randoEyes + randoNose + randoMouth + '\n')
        counter += 1

main()


import os
from pathlib import Path
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import numpy as np
from io import BytesIO
from PIL import Image
import tensorflow as tf

app = FastAPI()

origins = [
    "http://192.168.0.108:8080"
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

img = open("./healthy.jpg")

MODEL = tf.keras.models.load_model("./model")

CLASS_NAMES = ["Early Blight", "Late Blight", "Healthy"]

@app.get("/test")
async def test():
    return "Local server is started"

def read_file_as_image(data) -> np.ndarray:
    image = np.array(Image.open(BytesIO(data)))
    return image

@app.post("/predict")
async def predict(
    file: UploadFile = File(...)
):
    image = read_file_as_image(await file.read())
    img_batch = np.expand_dims(image, 0)

    predictions = MODEL.predict(img_batch)

    predicted_index = int(np.argmax(predictions[0]))
    predicted_class = CLASS_NAMES[predicted_index]
    confidence = np.max(predictions[0])
    return {
        'class': predicted_class,
        'confidence': float(confidence),
    }

if __name__ == "__main__":
    uvicorn.run(app, host='localhost', port=8000)


import json
import os
import pickle
import re

import numpy as np
import pandas as pd
import torch
import torchaudio
from sklearn.feature_extraction.text import CountVectorizer
from torch.utils.data import DataLoader, Dataset
from torchsummary import summary
from tqdm.auto import tqdm

device = 'cuda' if torch.cuda.is_available() else 'cpu'

sr = 16000

def loading_fairseq_model(model_file):
    import fairseq

    from torchaudio.models.wav2vec2.utils import import_fairseq_model
    model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task([model_file])
    original = model[0]
    imported = import_fairseq_model(original)
    return imported

def loading_huggingface_model(hf_model):
    from torchaudio.models.wav2vec2.utils import import_huggingface_model
    model = import_huggingface_model(hf_model)
    return model

def walk_librispeech_dirs(librispeech_root, libri_split):
    libri_split_path = os.path.join(librispeech_root,libri_split)
    filelist = []
    for root, dir, file in os.walk(libri_split_path):
        filelist.append(file)
    import itertools
    flatlist_raw = list(itertools.chain(*filelist))
    fileid_pattern = re.compile(r'\d+\-\d+-\d+')
    flatlist = [s for s in flatlist_raw if fileid_pattern.match(s)]
    txtlist = [os.path.join(*[re.split(r'\.|-', x)[0],re.split(r'\.|-', x)[1],x]) for x in flatlist if 'txt' in x]
    flaclist = [os.path.join(*[re.split(r'\.|-', x)[0],re.split(r'\.|-', x)[1],x]) for x in flatlist if 'flac' in x]
    df = pd.DataFrame(flaclist)
    df['fileid'] = df[0].apply(lambda x : os.path.split(x)[1])
    df['fileid'] = df['fileid'].str.replace('.flac', '', regex=True)
    df = df.rename({0:'fullpath'},axis=1)
    txt_out = []
    for txt_file in tqdm(txtlist):
        with open(os.path.join(libri_split_path, txt_file)) as f:
            txt_dict = {}

            sent = f.readline()
            file_id = os.path.split(txt_file)[-1]
            txt_dict['sent'] = sent
            txt_dict['fileid'] = file_id
            txt_out.append(txt_dict)
    df_txt = pd.DataFrame(txt_out)
    df_txt['fileid'] = df_txt['fileid'].str.replace('.txt', '', regex=True)
    merge_df = pd.merge(df,df_txt, on = 'fileid')
    merge_df = merge_df.drop(columns=['fileid'])
    return merge_df

def make_bow(doc):

    doc = list(map(str.lower, doc))
    unique_words = set(' '.join(doc).split())
    print(f'there are {len(unique_words)} unique words')
    index_dict = {}
    for ind, i in enumerate(sorted(unique_words)):
        index_dict[i] = ind
    cv = CountVectorizer(token_pattern=r"(?u)\b\w+\b")
    count_occurrences = cv.fit_transform(doc)
    return count_occurrences.toarray()

def read_json_save_csv(json_path):
    '''Reading the SpokenCOCO json file and extracting the text and wav file pairs'''
    with open(json_path) as json_file:
        data = json.load(json_file)
    text = []
    wav = []
    for image in data['data']:
        for caption in image['captions']:
            text.append(caption['text'])
            wav.append(caption['wav'])

    '''
    Using pandas to combine the two lists extracted in the cells above and
    save the resulting dataframe into a csv file
    '''
    dict_spokencoco = dict(zip(text,wav))
    spokencoco_val = pd.Series(dict_spokencoco, name = 'wav')
    spokencoco_val.index.name = 'text'
    spokencoco_val = spokencoco_val.reset_index()
    column_titles = ['wav', 'text']
    spokencoco_val = spokencoco_val.reindex(columns = column_titles)
    return spokencoco_val

def get_weird_sents(corpus_csv, root_dir):
    from custom_classes import Corpus
    corpus_ = Corpus(corpus_csv, root_dir)
    weird_sents = [x for x in [corpus_.get_depth(i) for i in range(len(corpus_))] if x[1] > len(str.split(x[0]))+2]
    print(f'there are total {len(weird_sents)} sentences')
    print(weird_sents)

def generate_tree(dataset, num_entries = None):
    import stanza
    nlp = stanza.Pipeline(lang='en', processors='tokenize,pos,constituency')
    from nltk.tree import Tree

    text = [x[-2] for x in dataset[:num_entries]]

    tree_list = [str(nlp(sent).sentences[0].constituency) for sent in text]
    nltk_tree_list = [Tree.fromstring(x) for x in tree_list]

    return list(zip((nltk_tree_list,text)))

def recover_from_triu(matrices):

    size_X = matrices[-1]
    X = np.zeros((size_X,size_X))
    full_matrices = []
    for v in matrices[:-1]:
        X[np.triu_indices(X.shape[0], k = 1)] = v
        X = X + X.T
        full_matrices.append(X)
    return full_matrices


# SPDX-License-Identifier: GPL-2.0-only
"""
A module with utilities for storing information related to a specific user.
"""

import time
import collections
import logging
import itertools
import os
import pwd
import usage
import cinfo
import statuses
from cfgparser import cfg, shared

def get_whitelist(status_group):
    """
    Returns the whitelist for the status group plus the global whitelist as a
    set.
    """
    status_group_prop = statuses.lookup_status_prop(status_group)
    whlist = set(cfg.processes.whitelist)
    whlist.update(status_group_prop.whitelist)

    if cfg.processes.whitelist_other_processes:
        whlist.add(shared.other_processes_label)

    whlist_files = [
        cfg.processes.whitelist_file, status_group_prop.whitelist_file
    ]
    for wfile in whlist_files:
        if wfile and os.path.isfile(wfile):
            with open(wfile, "r") as f:
                whlist.update(item.strip() for item in f.readlines())
    return whlist

proc_owner_whitelist = set(cfg.processes.proc_owner_whitelist)
whitelist = {}
for status_group in cfg.status.order + cfg.status.penalty.order:
    whitelist[status_group] = get_whitelist(status_group)

class User:
    """
    Contains information related to an user.

    Properties:
    uid: int
        The user's uid.
    gids: [int, ]
        A list of gids that the user belongs to.
    cgroup: cinfo.UserSlice()
        A cgroup obj representing the user.
    history: collections.deque(dict, )
        A list of history events ordered chronologically (i.e. most recent is
        first). History events are formatted as:
            {"time": float,
             "mem": float,
             "cpu": float,
             "pids": {int (pid): pidinfo.StaticProcess()}}
    badness_history: collections.deque(dict, )
        A list of badness history events ordered chronologically (i.e. most
        recent is first). Badness events are formatted as:
            {"timestamp": int,
             "delta_badness": {"mem": float, "cpu": float},
             "badness": {"mem": float, "cpu": float}}
    badness_timestamp: int
        A epoch timestamp for when the user's badness score goes above zero.
        This is reset after the user's badness score goes to 0.
    status: statuses.Status()
        The status of the user. See statuses.get_status() for format.
    cpu_usage: float
        The average cpu usage of the user over the arbiter interval (as a
        percent of a single core), averaged from collector events during the
        arbiter interval.
    mem_usage: float
        The average mem usage of the user over the arbiter interval (as a
        percentage of the entire machine), averaged from collector events
        during the arbiter interval.
    cpu_quota: float
        The user's cpu quota (as a percent of a single core) based on their
        current status.
    mem_quota: float
        The user's memory quota (as a percentage of the entire machine) based
        on their current status.
    """
    __slots__ = ["uid", "gids", "cgroup", "username", "uid_name", "history",
                 "badness_history", "badness_timestamp", "status",
                 "cpu_usage", "mem_usage", "cpu_quota", "mem_quota"]

    def __init__(self, uid):
        """
        Initializes a user.

        uid: int
            The user's uid
        """
        self.uid = uid
        self.gids = statuses.query_gids(self.uid)
        self.cgroup = cinfo.UserSlice(self.uid)
        self.username = "?"
        try:
            self.username = pwd.getpwuid(uid).pw_name
        except KeyError:
            pass
        self.uid_name = "{} ({})".format(self.uid, self.username)
        self.status = statuses.get_status(uid)
        self.history = collections.deque(maxlen=cfg.badness.max_history_kept)
        self.badness_history = collections.deque(maxlen=cfg.badness.max_history_kept)
        self.badness_timestamp = 0  # epoch when badness started increasing
        self.set_badness({"cpu": 0.0, "mem": 0.0}, int(time.time()))

    def set_badness(self, badness, record_time):
        """
        Sets and clears the badness history with the given badness.

        badness: dict
            The new first badness.
        record_time: float, int
            Time in epoch that the badness was calculated.
        """
        self.badness_history.clear()
        self.badness_history.appendleft({
            "timestamp": record_time,
            "delta_badness": {"cpu": 0.0, "mem": 0.0},
            "badness": badness
        })
        if sum(badness.values()) == 0:
            self.badness_timestamp = record_time

    def add_badness(self, badness, delta_badness, record_time):
        """
        Imports new badness and prepends the new badness into the
        self.badness_history accordingly.

        badness: dict
            A new badness dictionary.
        delta_badness: dict
            The change in badness dictionary.
        record_time: float, int
            Time in epoch that the badness was calculated.
        """
        self.badness_history.appendleft({
            "timestamp": record_time,
            "delta_badness": delta_badness,
            "badness": badness
        })

        # Set badness_timestamp when user starts gaining badness or loses it
        if not self.badness_timestamp and sum(badness.values()) != 0:
            self.badness_timestamp = record_time
        elif self.badness_timestamp and sum(badness.values()) == 0:
            self.badness_timestamp = 0

    def update_properties(self):
        """
        Sets properties of the user.
        """
        self.status = statuses.get_status(self.uid)
        avg_cpu, avg_mem = self.avg_gen_usage()
        self.cpu_usage = avg_cpu
        self.mem_usage = avg_mem
        cpu_quota, mem_quota = statuses.lookup_quotas(self.uid, self.status.current)
        self.cpu_quota = cpu_quota
        self.mem_quota = mem_quota
        self.gids = statuses.query_gids(self.uid)

    def whitelisted_processes(self, processes):
        """
        Filters the given processes and into list of whitelisted processes.

        processes: iter
            A iterable of processes.
        """
        return [
            proc for proc in processes
            if proc.name.rstrip("*") in whitelist[self.status.current] or
               proc.owner in proc_owner_whitelist
        ]

    def mark_whitelisted_processes(self, processes):
        """
        Marks the given StaticProcess()s with a asterisk at the end of their
        name if the process is whitelisted either by the global whitelist,
        status whitelist or pid owner whitelist.
        """
        whitelisted_procs = self.whitelisted_processes(processes)
        for proc in whitelisted_procs:
            proc.name += "*"

    def avg_gen_usage(self):
        """
        Returns the current average cgroup usage between the arbiter
        intervals.
        """
        updates = cfg.general.history_per_refresh
        cpu_usages = [
            event["cpu"]
            for event in itertools.islice(self.history, 0, updates)
        ]
        mem_usages = [
            event["mem"]
            for event in itertools.islice(self.history, 0, updates)
        ]
        return (
            sum(cpu_usages) / len(cpu_usages) if cpu_usages else 0.0,
            sum(mem_usages) / len(mem_usages) if mem_usages else 0.0
        )

    def avg_proc_usage(self, whitelisted=False):
        """
        Returns the current average total process usage between the arbiter
        intervals.

        whitelisted: bool
            Whether to only count whitelisted processes.
        """
        updates = cfg.general.history_per_refresh
        total_procs = []
        for event in itertools.islice(self.history, 0, updates):
            if whitelisted:
                procs = self.whitelisted_processes(event["pids"].values())
            else:
                procs = list(event["pids"].values())
            total_procs.append(sum(procs))

        if not total_procs:
            return 0.0, 0.0

        avg_proc = usage.average(*total_procs)
        return avg_proc.usage["cpu"], avg_proc.usage["mem"]

    def new(self):
        """
        Returns whether the user is new (as in the obj created).
        """
        return len(self.badness_history) <= 1


import unittest
import time

from selenium.common.exceptions import (
    InvalidArgumentException,
)

from src.Scraper import Scraper
from src import models as m

URL = "https://www.mtgtop8.com/format?f=ST"

class TestDriver(unittest.TestCase):

    def test_get_mtgtop8(self):
        with Scraper(URL) as scraper:
            page_title = scraper.get_title().lower()
            self.assertIn("mtg", page_title)
            self.assertEqual(scraper.get_url(), URL)

    def test_stable_should_be_in_page_one_body(self):
        with Scraper(URL) as scraper:
            page_source = repr(scraper)
            self.assertIn("Stable", page_source)
            self.assertNotIn("Stttbl", page_source)

    def test_should_return_a_string_for_page_source(self):
        with Scraper(URL) as scraper:
            page_source = repr(scraper)
            self.assertIsInstance(page_source, str)

    def test_is_page_one_with_no_previous_button(self):
        page = 2
        with Scraper(URL) as scraper:
            page_source = repr(scraper)
            stable = scraper.get_by("css", "table.Stable")
        self.assertIn("Nav_PN_no", page_source)
        self.assertIn(f"PageSubmit({page})", page_source)
        self.assertIsNotNone(stable)

    def test_get_button_to_go_to_page_two(self):
        with Scraper(URL) as scraper:
            scraper.execute("PageSubmit", 2)
            stable = scraper.get_by("css", "table.Stable")
        self.assertNotIn("Nav_PN_no", stable)

    @unittest.skip("Out of Date")
    def test_first_page_should_have_this_event_title(self):
        event_title = "FNM @ Deckmaster Games"
        with Scraper(URL) as scraper:
            page_source = repr(scraper)
        self.assertIn(event_title, page_source)

# Skipping because it is gumming up the webdriver access...
@unittest.SkipTest
class TestDriverWithBadInputsDefaultExceptions(unittest.TestCase):

    def test_should_return_with_empty_page(self):
        with self.assertRaises(InvalidArgumentException):
            scraper = Scraper("adfa")
            scraper.quit()

    def test_should_get_mad_if_no_keys_in_selector(self):
        with Scraper(URL) as scraper:
            result = scraper.get_by("css", "table.NotATable")
        self.assertFalse(result)

@unittest.skip("Out of Date")
class TestGettingSpecificElements(unittest.TestCase):

    def test_should_give_all_tables_with_class_Stable(self):
        with Scraper(URL) as scraper:
            table_elements = scraper.get_all_by(
                "css", "table.Stable")
        self.assertTrue(len(table_elements) > 1)
        self.assertIsInstance(table_elements, list)

    def test_should_give_first_table_with_class_stable(self):
        with Scraper(URL) as scraper:
            table_element = scraper.get_by("css", "table.Stable")
        self.assertEqual(len(table_element), 1)

    def test_finding_one_thing_by_name(self):
        with Scraper(URL) as scraper:
            result = scraper.get_by("name", "meta")
        self.assertEqual(len(result), 1)
        self.assertIsInstance(result, list)

    def test_finding_one_thing_by_id(self):
        with Scraper(URL) as scraper:
            result = scraper.get_by("id", "other_tooltip")
        self.assertEqual(len(result), 1)
        self.assertIsInstance(result, list)

    def test_finding_one_thing_by_class_not_css(self):
        with Scraper(URL) as scraper:
            result = scraper.get_by("class", "S14")
            self.assertEqual(len(result), 1)
            self.assertIsInstance(result, list)
            self.assertIn("Players Tour Online", result[0].text)

    def test_finding_all_things_by_class_not_css(self):
        with Scraper(URL) as scraper:
            result = scraper.get_all_by("class", "S14")
            self.assertGreaterEqual(len(result), 2)
            self.assertIn("decks", result[1].text)

    def test_find_one_row_of_stable_with_xpath(self):
        with Scraper(URL) as scraper:
            result = scraper.get_by(
                "xpath", "//table[@class='Stable'][2]//tr[@class='hover_tr']//a")
            self.assertEqual(len(result), 1)
            # self.assertEqual("Japan Championship 2020 Autumn - Last Chance Trial @ BIG Magic", result[0].text)
            # self.assertIn("event?e=27876&f=ST", result[0].get_attribute("href"))

    def test_find_all_rows_in_stable_with_xpath(self):
        with Scraper(URL) as scraper:
            results = scraper.get_all_by(
                "xpath", "//table[@class='Stable'][2]//tr[@class='hover_tr']//a"
            )
            self.assertEqual(len(results), 10)
            # events = [item.text for item in results]
            # links = [item.get_attribute("href") for item in results]
            # self.assertIn("FNM @ Deckmaster Games", events)
            # self.assertIn("https://www.mtgtop8.com/event?e=27847&f=ST", links)

    def test_xpath_finds_things_on_other_pages(self):
        with Scraper(URL) as scraper:
            scraper.execute("PageSubmit", 9)
            time.sleep(2)
            results = scraper.get_all_by(
                "xpath", "//table[@class='Stable'][2]//tr[@class='hover_tr']//a"
            )
            self.assertEqual(len(results), 10)
            # events = [item.text for item in results]
            # links = [item.get_attribute("href") for item in results]
            # self.assertIn("Monday Night Magic 2 @ Plague League", events)
            # self.assertIn("https://www.mtgtop8.com/event?e=27623&f=ST", links)

    def test_xpath_finds_dates(self):
        with Scraper(URL) as scraper:
            result = scraper.get_by(
                "xpath", "//table[@class='Stable'][2]//tr[@class='hover_tr']//td[@class='S10']")
            self.assertEqual(result[0].text, '30/10/20')

class TestRepr(unittest.TestCase):

    def test_should_print_page_source(self):
        with Scraper(URL) as scraper:
            print(scraper)

if __name__ == "__main__":
    unittest.main()


# %%
"""
Transport distributions using dense solvers
===========================================

In this example, we sample 2 toy distributions and compute
a dense fugw alignment between them.
Dense alignments are typically used when both aligned distributions
have less than 10k points.
"""

# sphinx_gallery_thumbnail_number = 4
import matplotlib.pyplot as plt
import numpy as np
import torch

from fugw.mappings import FUGW
from fugw.utils import _init_mock_distribution
from matplotlib.collections import LineCollection

# %%
torch.manual_seed(0)

n_points_source = 50
n_points_target = 40
n_features_train = 2
n_features_test = 2

# %%
# Let us generate random training data for the source and target distributions
_, source_features_train, source_geometry, source_embeddings = (
    _init_mock_distribution(n_features_train, n_points_source)
)
_, target_features_train, target_geometry, target_embeddings = (
    _init_mock_distribution(n_features_train, n_points_target)
)
source_features_train.shape

# %%
# We can visualize the generated features:
fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot()
ax.set_title("Source and target features")
ax.set_aspect("equal", "datalim")
ax.scatter(source_features_train[0], source_features_train[1], label="Source")
ax.scatter(target_features_train[0], target_features_train[1], label="Target")
ax.legend()
plt.show()

# %%
# And embeddings:
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.set_title("Source and target embeddings (ie geometries)")
ax.scatter(
    source_embeddings[:, 0],
    source_embeddings[:, 1],
    source_embeddings[:, 2],
    s=15,
    label="Source",
)
ax.scatter(
    target_embeddings[:, 0],
    target_embeddings[:, 1],
    target_embeddings[:, 2],
    s=15,
    label="Target",
)
ax.legend()
plt.show()

# %%
# Features and geometries should be normalized before calling the solver
source_features_train_normalized = source_features_train / torch.linalg.norm(
    source_features_train, dim=1
).reshape(-1, 1)
target_features_train_normalized = target_features_train / torch.linalg.norm(
    target_features_train, dim=1
).reshape(-1, 1)

source_geometry_normalized = source_geometry / source_geometry.max()
target_geometry_normalized = target_geometry / target_geometry.max()

# %%
# Let us define the optimization problem to solve
alpha = 0.5
rho = 1000
eps = 1e-4
mapping = FUGW(alpha=alpha, rho=rho, eps=eps)

# %%
# Now, we fit a transport plan between source and target distributions
# using a sinkhorn solver
_ = mapping.fit(
    source_features_train_normalized,
    target_features_train_normalized,
    source_geometry=source_geometry_normalized,
    target_geometry=target_geometry_normalized,
    solver="sinkhorn",
    verbose=True,
)

# %%
# The transport plan can be accessed after the model has been fitted
pi = mapping.pi
print(f"Transport plan's total mass: {pi.sum():.5f}")

# %%
# Here is the evolution of the FUGW loss during training,
# as well as the contribution of each loss term:

fig, ax = plt.subplots(figsize=(10, 4))
ax.set_title("Mapping training loss")
ax.set_ylabel("Loss")
ax.set_xlabel("BCD step")
ax.stackplot(
    mapping.loss_steps,
    [
        (1 - alpha) * np.array(mapping.loss["wasserstein"]),
        alpha * np.array(mapping.loss["gromov_wasserstein"]),
        rho * np.array(mapping.loss["marginal_constraint_dim1"]),
        rho * np.array(mapping.loss["marginal_constraint_dim2"]),
        eps * np.array(mapping.loss["regularization"]),
    ],
    labels=[
        "wasserstein",
        "gromov_wasserstein",
        "marginal_constraint_dim1",
        "marginal_constraint_dim2",
        "regularization",
    ],
    alpha=0.8,
)
ax.legend()
plt.show()

# %%
# Using the computed mapping
# --------------------------
# The computed mapping is stored in ``mapping.pi`` as a ``torch.Tensor``.
# In this example, the transport plan is small enough that we can display
# it altogether.

fig, ax = plt.subplots(figsize=(4, 4))
ax.set_title("Transport plan")
ax.set_xlabel("target vertices")
ax.set_ylabel("source vertices")
im = plt.imshow(pi, cmap="viridis")
plt.colorbar(im, ax=ax, shrink=0.8)
plt.show()

# %%
# The previous figure of the transport plan tells us it is very sparse
# and not very regularized.
# Another informative way to look at the plan consists in checking
# which points of the source and target distributions
# were matched together in the feature space.

fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot()
ax.set_aspect("equal", "datalim")
ax.set_title("Mapping\ndisplayed in feature space")

# Draw lines between matched points
indices = torch.cartesian_prod(
    torch.arange(n_points_source), torch.arange(n_points_target)
)
segments = torch.stack(
    [
        source_features_train[:, indices[:, 0]],
        target_features_train[:, indices[:, 1]],
    ]
).permute(2, 0, 1)
pi_normalized = pi / pi.sum(dim=1).reshape(-1, 1)
line_segments = LineCollection(
    segments, alpha=pi_normalized.flatten(), colors="black", lw=1, zorder=1
)
ax.add_collection(line_segments)

# Draw distributions
ax.scatter(source_features_train[0], source_features_train[1], label="Source")
ax.scatter(target_features_train[0], target_features_train[1], label="Target")

ax.legend()
plt.show()

# %%
# Finally, the fitted model can transport unseen data
# between source and target
source_features_test = torch.rand(n_features_test, n_points_source)
target_features_test = torch.rand(n_features_test, n_points_target)
transformed_data = mapping.transform(source_features_test)
transformed_data.shape

# %%
assert transformed_data.shape == target_features_test.shape

# %%


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import yolov5
import odmetrics

###############################################################################
# PARAMETERS
###############################################################################

# Path to the folder containing the test images and labels (ground truth)
PATH_TEST_IMAGES='../../../DATA/BURROWS/DATASET/images/test/'
PATH_TEST_LABELS='../../../DATA/BURROWS/DATASET/labels/test/'

# Path to the trained model
PATH_MODEL='MODELS/BSMALL.pt'

# Image size (required to convert YOLOv5 (xywhn) to ABSLUTE (xyxy))
IMG_WIDTH=640
IMG_HEIGHT=480

# IoU thresholds to use when computing metrics.
IOU_THRESHOLDS=np.round(np.arange(0.1,0.95,0.05),2)

# Classes to evaluate. Must be an iterable.
CLASSES_TO_EVALUATE=[0]

###############################################################################
# MAIN CODE
###############################################################################

# =============================================================================
# OBJECT DETECTION
# =============================================================================

# Install YOLOv5
pathYOLOv5=yolov5.install()

# Perform object detection
theNames,predTimes,predLabels=yolov5.detect_with_torch(pathYOLOv5,PATH_MODEL,PATH_TEST_IMAGES)

# =============================================================================
# STATS NOT REQUIRING ODMETRICS
# =============================================================================

# Let's show some results (not requiring odmetrics)
print('[INFO] AVERAGE PREDICTION TIME PER IMAGE: %.3f ms'%(np.mean(predTimes)))

# Remove outliers from time consumption (usually the first ones are the largest
# due -probably- to startup, caching and stuff)
theMedian=np.median(predTimes)
theStd=np.std(predTimes)
filteredTimes=[[i,t] for i,t in enumerate(predTimes) if abs(t-theMedian)<=3*theStd]

# Get the largest prediction time within the filtered ones
iLargest=np.argmax([x[1] for x in filteredTimes])
iLargest=filteredTimes[iLargest][0]

# Print some related info
print('[INFO] THE MOST TIME CONSUMING IMAGE WAS %s, WHICH REQUIRED %.3f ms TO DETECT %d OBJECTS.'%(theNames[iLargest],predTimes[iLargest],len(predLabels[iLargest])))

# Get the smallest prediction time within the filtered ones
iSmallest=np.argmin([x[1] for x in filteredTimes])
iSmallest=filteredTimes[iSmallest][0]

# Print some related info
print('[INFO] THE LEAST TIME CONSUMING IMAGE WAS %s, WHICH REQUIRED %.3f ms TO DETECT %d OBJECTS.'%(theNames[iSmallest],predTimes[iSmallest],len(predLabels[iSmallest])))

# =============================================================================
# USING ODMETRICS.COMPUTE_METRICS AND RELATED UTILITIES
# =============================================================================

# Load the ground truth labels. Note that "theNames" is necessary to load them
# in the same order than the predLabels.
gtLabels=odmetrics.load_all_yolo_labels(PATH_TEST_LABELS,theNames,IMG_WIDTH,IMG_HEIGHT)

# Compute the main metrics
allResults=odmetrics.compute_metrics(predLabels,gtLabels,IOU_THRESHOLDS,CLASSES_TO_EVALUATE)

# Plot some Recall-Precision curves
odmetrics.plot_rp_curves(allResults, [0.1,0.3,0.5,0.7,0.9])

# Get mAP0.5 and mAP0.5:0.05:0.95, both for class 0.
mAP05=odmetrics.compute_mAP(allResults,[0.5],[0])
mAP05_005_095=odmetrics.compute_mAP(allResults,np.round(np.arange(0.5,0.95,0.05),2),[0])

# Print the results
print('[INFO] HERE ARE SOME STATS FOR YOUR ENJOYMENT:')
print('* mAP@0.5=%.3f'%mAP05)
print('* mAP@0.5:0.05:0.95=%.3f'%mAP05_005_095)

# =============================================================================
# USING ODMETRICS.EXPLORE_PARAMETERS AND RELATED UTILITIES
# =============================================================================

# Let's explore the threshold space
theExploration=odmetrics.explore_parameters(predLabels,gtLabels,np.round(np.arange(0.1,0.9,0.1),2), np.round(np.arange(0.1,0.9,0.1),2), [0])

# Plot the F1-Score for all the explored space
odmetrics.plot_exploration(theExploration,metricToShow=5)

# Search the best threshold combination for class 0 according to the different
# explored metrics.
bestTPConfig=odmetrics.get_best_configuration(theExploration,0)
bestFPConfig=odmetrics.get_best_configuration(theExploration,1)
bestFNConfig=odmetrics.get_best_configuration(theExploration,2)
bestRecallConfig=odmetrics.get_best_configuration(theExploration,3)
bestPrecisionConfig=odmetrics.get_best_configuration(theExploration,4)
bestF1Config=odmetrics.get_best_configuration(theExploration,5)

# Print the configurations
print('[INFO] CONFIGURATION MAXIMIZING TRUE POSITIVES')
odmetrics.print_explored_configuration(bestTPConfig)
print('\n[INFO] CONFIGURATION MAXIMIZING FALSE POSITIVES')
odmetrics.print_explored_configuration(bestFPConfig)
print('\n[INFO] CONFIGURATION MAXIMIZING FALSE NEGATIVES')
odmetrics.print_explored_configuration(bestFNConfig)
print('\n[INFO] CONFIGURATION MAXIMIZING RECALL')
odmetrics.print_explored_configuration(bestRecallConfig)
print('\n[INFO] CONFIGURATION MAXIMIZING PRECISION')
odmetrics.print_explored_configuration(bestPrecisionConfig)
print('\n[INFO] CONFIGURATION MAXIMIZING F1-SCORE')
odmetrics.print_explored_configuration(bestF1Config)


a = input()
cpr= "432765-4321"
sumVal = 0
for i in range(len(a)):
    if a[i] == "-":
        continue
    else:
        sumVal += int(a[i]) * int(cpr[i])

if sumVal%11 == 0:
    print(1)
else:
    print(0)


bool = True
if bool:
	print("bool is true")

otherbool = False
if otherbool:
	print("true")
else:
	print("false")

value = int(input("enter a number: "))
if value < 5:
	print("small number")
elif value < 20:
	#n.b. you can have as many elif clauses as you like in an if statement
	print("medium size number")
else:
	print("big number")


"""
selection sort, per ogni elemento della lista scambia quello in prima posizione con il minimo
"""

def selection_sort(lista):

    ## deve scambiare l'elemento in prima posizione con il minimo
    ## e poi via via con i successivi minimi

    for i in range(len(lista)):
        current = lista[i]

        # m è il minimo ?
        m = i

        for j in range(i+1, len(lista)):
            if lista[j] < lista[m]:
                m = j

        # uscito dal ciclo lista[j] è il minimo
        tmp = lista[i]
        lista[i] = lista[m]
        lista[m] = tmp

    return lista

if __name__ == "__main__":

    print(selection_sort([4, 7, 1, 2, 9, 12, 5, 99, 65]))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('musico', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='album',
            name='foto',
            field=models.ImageField(upload_to='', blank='True'),
        ),
    ]


from flask import Flask, request
import time
import json

app = Flask(__name__)

feedbackArr:list = []

@app.route("/submit", methods=["POST"])
def submit():
    requestJson = request.get_json()
    feedbackArr.append(
        {
            "Feedback":requestJson["feedback"],
            "Time":time.time(),
            "Username":requestJson["username"]
        }
    )
    return "Feedback Submitted Successfully"

@app.route("/get", methods=["GET"])
def get_feedback():
    #the amount of days back the feedback goes
    daysback = request.args.get("daysback")

    if daysback:
        newFeedback = []

        secondsback = int(daysback) * 24 * 60 * 60
        for i in reversed(feedbackArr):
            if time.time()- i["Time"] < secondsback:
                newFeedback.append(i)
            else:
                break
        return json.dumps(newFeedback)

    return json.dumps(feedbackArr)

@app.route("/" , methods=["GET", "POST"])
def index():
    return "null"

if __name__=="__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)