# 258. Add Digits
# Easy

class Solution:
    def addDigits(self, num: int) -> int:

        def helper(num):
            num = list(str(num))
            temp = 0
            if len(num) == 1:
                return num[0]
            else:
                for i in num:
                    temp += int(i)
                num = temp
                helper(num)

        return helper(num)
s = Solution()
print(s.addDigits(38))
# why this returns none?

# Larry
class Solution:
    def addDigits(self, num: int) -> int:
        """
        # Larry, https://www.youtube.com/watch?v=FRWUcc1cX9A
        """
        if num == 0:
            return num
        digit = num % 9
        if digit == 0:
            digit = 9
        return digit


import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = None

def pytest_addoption(parser):  # from https://docs.pytest.org/en/latest/example/simple.html
    parser.addoption(
        "--browser_name", action="store", default="chrome", help="my option: chrome, firefox or ie"
    )

@pytest.fixture(scope="class")
def setup(request):
    global driver
    browser_name = request.config.getoption("--browser_name")  # from https://docs.pytest.org/en/latest/example/simple.html
    if browser_name == "chrome":
        driver = webdriver.Chrome()
    elif browser_name == "firefox":
        driver = webdriver.Firefox()
    elif browser_name == "ie":
        driver = webdriver.Ie()
    driver.get("https://rahulshettyacademy.com/angularpractice/")
    driver.maximize_window()
    request.cls.driver = driver  # it will be passed as driver to the class where this fixture is used
    yield
    driver.close()

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
        Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
        :param item:
        """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            _capture_screenshot(file_name)
            if file_name:
                html = '

' % file_name
                extra.append(pytest_html.extras.html(html))
        report.extra = extra

def _capture_screenshot(name):
    driver.get_screenshot_as_file(name)


from pulp import *
from tabulate import tabulate

class Solver():
    def __init__(self, numberOfProducts, numberOfTruckTypes, prob, productVolumes,
                 productDemandQuantity, truckTypeCapacities, numberOfTrucksPerType):
        self.prob = prob
        self.numberOfProducts = numberOfProducts
        self.numberOfTruckTypes = numberOfTruckTypes
        self.productVolumes = productVolumes
        self.productDemandQuantity = productDemandQuantity
        self.truckTypeCapacities = truckTypeCapacities
        self.numberOfTrucksPerType = numberOfTrucksPerType

    def getProductNames(self):
        productNames = []
        for i in range(self.numberOfProducts):
            productName = f"Product_{str(i + 1)}"
            productNames.append(productName)

        return productNames

    def getTruckTypeNames(self):
        truckTypeNames = []
        for i in range(self.numberOfTruckTypes):
            truckTypeName = f"Truck_{str(i + 1)}"
            truckTypeNames.append(truckTypeName)

        return truckTypeNames

    def getTrucksPerTypeNames(self):
        trucksPerTypeNames = []
        for i in range(self.numberOfTruckTypes):
            for j in range(self.numberOfTrucksPerType[i]):
                truckPerTypeName = f"Truck_{str(i + 1)}_{str(j + 1)}"
                trucksPerTypeNames.append(truckPerTypeName)

        return trucksPerTypeNames

    def getSolution(self):
        x, y = self.setDecisionVariables()
        self.prob += (lpSum([y[truckPerType] for truckPerType in self.getTrucksPerTypeNames()]), "number_of_trucks_used")
        self.setConstraints(x=x, y=y)
        self.prob.solve()

        status = LpStatus[self.prob.status]
        canShowTable = status == 'Optimal'

        return self.prepareSolution(x=x) if canShowTable else None

    def setDecisionVariables(self):
        x = LpVariable.dicts("X", (self.getProductNames(), self.getTrucksPerTypeNames()), 0, None, LpInteger)
        y = LpVariable.dicts("Y", self.getTrucksPerTypeNames(), 0, 1, LpBinary)

        return x, y

    def setConstraints(self, x, y):
        for truckPerType in self.getTrucksPerTypeNames():
            truckTypeName = truckPerType.split("_")[0] + "_" + truckPerType.split("_")[1]
            self.prob += (
                lpSum(self.getTruckLoad(x, truckPerType)) <= self.getTruckCapacityIfUsed(y, truckTypeName, truckPerType),
                f"Capacity_of_{truckPerType}"
            )

        for (productIndex, product) in enumerate(self.getProductNames()):
            self.prob += (
                lpSum(self.getProductQuantity(x, product)) == self.productDemandQuantity[productIndex],
                f"sum_of_trucks_for_{product}"
            )

    def getTruckLoad(self, x, truckPerType):
        return [(x[product][truckPerType] * self.productVolumes[productIndex]) for (productIndex, product) in enumerate(self.getProductNames())]

    def getTruckCapacityIfUsed(self, y, truckTypeName, truckPerType):
        return self.truckTypeCapacities[self.getTruckTypeIndex(truckTypeName)] * y[truckPerType]

    def getTruckTypeIndex(self, truckTypeName):
        return self.getTruckTypeNames().index(truckTypeName)

    def getProductQuantity(self, x, product):
        return [x[product][truckPerType] for truckPerType in self.getTrucksPerTypeNames()]

    def prepareSolution(self, x):
        table = []
        for truck in self.getTrucksPerTypeNames():
            truckInventory = [truck]
            transportedVolume = 0

            for (productIndex, product) in enumerate(self.getProductNames()):
                truckInventory.append(value(x[product][truck]))
                transportedVolume += value(x[product][truck]) * self.productVolumes[productIndex]

            truckTypeName = truck.split("_")[0] + "_" + truck.split("_")[1]
            truckLoad = transportedVolume / self.truckTypeCapacities[self.getTruckTypeIndex(truckTypeName)]
            truckInventory.append(round(truckLoad * 100, 2))
            table.append(truckInventory)

        table = sorted(table, key=lambda x: x[-1], reverse=True)
        return {row[0]: row[1:] for row in table}

    def pretifySolution(self, solution):
        pretifiedSolution = []
        for truck, values in solution.items():
            values.insert(0, truck)
            pretifiedSolution.append(values)

        headers = ['Truck']
        headers.extend(iter(self.getProductNames()))
        headers.append('Capacity %')

        return tabulate(pretifiedSolution, headers=headers, floatfmt=".2f")


def solve(dp, M, P, x, S, U):
    if x == P:
        if U == 0:
            return 1
        else:
            return 0
    if dp[x][S][U] != -1:
        return dp[x][S][U]

    res = [0]*2

    # 아직 선택 안한 곡을 선택
    if U > 0:
        res[0] = solve(dp, M, P, x+1, S+1, U-1) * U

    # 선택했던 곡을 재선택
    if S > M:
        res[1] = solve(dp, M, P, x+1, S, U) * (S - M)

    dp[x][S][U] = sum(res)
    return dp[x][S][U]

if __name__ == "__main__":
    N, M, P = map(int, input().strip().split())

    dp = [[[-1]* 101 for i in range(101)] for j in range(101)]
    # dp[x][S][N]: 현재까지 선택된 곡 S 갯수 선택 안된곡 N

    print(solve(dp, M, P, 0, 0, N)%1000000007)


import pandas as pd
import numpy as np
import re
import itertools
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import MinMaxScaler
import warnings
warnings.filterwarnings("ignore")
from flask import Flask
###  FOR CSV SETTINGS ###
### RUNS ONCE ###
app = Flask(__name__,template_folder='templates')

scope = 'user-library-read'

#simple function to create OHE features
def oneHotEncode(df, column, new_name):
    #take the categorical variables and convert it to dummy variable!
    tfDF = pd.get_dummies(df[column])
    feature_names = tfDF.columns
    tfDF.columns = [new_name + "|" + str(i) for i in feature_names]
    tfDF.reset_index(drop = True, inplace = True)
    return tfDF

#function to build entire feature set
def create_feature_set(df, floatCols):
    #tfdf genre lists
    tfidf = TfidfVectorizer()
    tfidf_matrix =  tfidf.fit_transform(df['consolidates_genre_lists'].apply(lambda x: " ".join(x)))
    #genre
    genre_df = pd.DataFrame(tfidf_matrix.toarray())
    genre_df.columns = ['genre' + "|" + i for i in tfidf.get_feature_names()]
    genre_df.reset_index(drop = True, inplace=True)
    #year
    year_ohe = oneHotEncode(df, 'year','year') * 0.5
    #popularity
    popularity_ohe = oneHotEncode(df, 'popularity_red','pop') * 0.15

    #scale float columns
    floats = df[floatCols].reset_index(drop = True)
    scaler = MinMaxScaler()
    floats_scaled = pd.DataFrame(scaler.fit_transform(floats), columns = floats.columns) * 0.2

    #concanenate all features
    final = pd.concat([genre_df, floats_scaled, popularity_ohe, year_ohe], axis = 1)

    #add song id
    final['id']=df['id'].values

    return final

#preprocessing the dataset
#concat all unecessary chars from the strings(genres, artists etc.)
def preprocess_dataset():
        #these csv's comes from KAGGLE DATASET
        #KAGGLE links are in the PROJECT REPORT!!!!
        spotifyDf = pd.read_csv('data/data.csv')
        data_w_genre = pd.read_csv('data/data_w_genres.csv')
        data_w_genre['genres_upd'] = data_w_genre['genres'].apply(lambda x: [re.sub(' ','_',i) for i in re.findall(r"'([^']*)'", x)])
        spotifyDf['artists_upd_v1'] = spotifyDf['artists'].apply(lambda x: re.findall(r"'([^']*)'", x))
        spotifyDf[spotifyDf['artists_upd_v1'].apply(lambda x: not x)].head(5)

        spotifyDf['artists_upd_v2'] = spotifyDf['artists'].apply(lambda x: re.findall('\"(.*?)\"',x))
        spotifyDf['artists_upd'] = np.where(spotifyDf['artists_upd_v1'].apply(lambda x: not x), spotifyDf['artists_upd_v2'], spotifyDf['artists_upd_v1'] )

        spotifyDf['artists_song'] = spotifyDf.apply(lambda row: row['artists_upd'][0]+row['name'],axis = 1)
        spotifyDf.sort_values(['artists_song','release_date'], ascending = False, inplace = True)

        spotifyDf.drop_duplicates('artists_song',inplace = True)
        artists_exploded = spotifyDf[['artists_upd','id']].explode('artists_upd')

        artists_exploded_enriched = artists_exploded.merge(data_w_genre, how = 'left', left_on = 'artists_upd',right_on = 'artists')
        artists_exploded_enriched_nonnull = artists_exploded_enriched[~artists_exploded_enriched.genres_upd.isnull()]

        artists_genres_consolidated = artists_exploded_enriched_nonnull.groupby('id')['genres_upd'].apply(list).reset_index()
        artists_genres_consolidated['consolidates_genre_lists'] = artists_genres_consolidated['genres_upd'].apply(lambda x: list(set(list(itertools.chain.from_iterable(x)))))

        spotifyDf = spotifyDf.merge(artists_genres_consolidated[['id','consolidates_genre_lists']], on = 'id',how = 'left')

        #Feature Engineering
        spotifyDf['year'] = spotifyDf['release_date'].apply(lambda x: x.split('-')[0])
        # create 5 point buckets for popularity
        spotifyDf['popularity_red'] = spotifyDf['popularity'].apply(lambda x: int(x/5))
        # tfidf can't handle nulls so fill any null values with an empty list
        spotifyDf['consolidates_genre_lists'] = spotifyDf['consolidates_genre_lists'].apply(lambda d: d if isinstance(d, list) else [])
        # assign it to a csv to use it app.py!!
        spotifyDf.to_csv("spotify_last.csv")
        return spotifyDf

def main():

    spotifyDf=preprocess_dataset()
    floatCols = spotifyDf.dtypes[spotifyDf.dtypes == 'float64'].index.values
    complete_feature_set = create_feature_set(spotifyDf, floatCols=floatCols)#.mean(axis = 0)
    #######################FINAL CSV (used in app.py)
    complete_feature_set.to_csv("final.csv")

if __name__ == "__main__":
    main()


import numpy as np

# See https://github.com/keras-rl/keras-rl/blob/master/rl/memory.py
def zeros_like(a, dtype='float32'):
    """Return an array of zeros with same shape as given array.

    Args:
        a (array_like, iterable): An object with shape attribute or an iterable.

    Returns:
        (array_like, list): Array of zeros with the same shape as a.
    """
    if hasattr(a, 'shape'):
        if hasattr(a, 'dtype'):
            dtype = a.dtype
        return np.zeros(a.shape, dtype=dtype)
    if hasattr(a, '__iter__'):
        return [zeros_like(b, dtype=dtype) for b in a]
    return 0.

def check_shape(a, b):
    """Check if the shapes of given values match.

    Args:
        a (array_like, tuple): An object with shape attribute or a tuple representing shape.
        b (array_like, tuple): An object with shape attribute or a tuple representing shape.

    Raises:
        Exception: When shapes don't match.
    """
    if hasattr(a, 'shape'):
        a = a.shape
    if hasattr(b, 'shape'):
        b = b.shape
    assert a == b, f"Shapes {a} and {b} don't match"

def unique(a):
    res = {id(v): v for v in a}
    return list(res.values())


from tkinter import Tk, Label, Frame
from PIL import Image, ImageTk, ImageOps
import webbrowser
class Splash:
    def __init__(self):
        splash = Tk()
        splash.geometry("400x400")
        width = splash.winfo_screenwidth()
        height = splash.winfo_screenheight()
        x = (width/2) - (400/2)
        y = (height/2) - (400/2)
        splash.geometry("+%d+%d" % (x, y))
        splash.configure(bg="white")
        splash.overrideredirect(True)

        logo_img = ImageTk.PhotoImage(ImageOps.contain(Image.open("./img/Layers.png"), (300, 100)))
        logo_img_label = Label(splash, image=logo_img, bg="white")
        logo_img_label.place(relx=0.5, rely=0.5, anchor="center")

        info_frame = Frame(splash, bg="white", width=400, height=100)
        info_frame.place(relx=0.5, rely=0.8, anchor="center")

        info_text = "Layers, Image Editing tool"
        info_label = Label(info_frame, text=info_text, bg="white", fg="#77cbff", font=("Arial Rounded MT Bold", 20))
        info_label.place(relx=0.5, rely=0.5, anchor="center")

        dev_label = Label(info_frame, text="Developed by: Meet Makwana", bg="white", fg="#77cbff", font=("Arial Rounded MT Bold", 12), cursor="hand2")
        dev_label.place(relx=0.65, rely=0.8, anchor="center")
        dev_label.bind("<Button-1>", lambda e: webbrowser.open("https://github.com/meetxvii"))

        splash.after(3000, lambda: splash.destroy())
        splash.mainloop()

if __name__ == "__main__":
    Splash()


import os
import sys
import pandas as pd
import warnings
import re

warnings.simplefilter(action='ignore', category=FutureWarning)

os.chdir(os.path.dirname(sys.argv[0]))

def gather():
    # Load the data
    df = pd.read_csv('saves/mhr_slot.csv')
    df.set_index('Name', inplace=True)

    # Create dataframes
    df2 = pd.DataFrame(data={'ID':0,'Name':0,'Quantity':0,'Category':0,'Subcategory':0},index=(0,1))
    df3 = pd.DataFrame(data={'Index':0,'Type ID':0,'Name':0,'Level':0,'Quantity':0,'Type':0,'Subcategory':0},index=(0,1))
    df4 = pd.DataFrame(data={'Index':0,'Name':0,'Level':0,'Quantity':0},index=(0,1))
    df5 = pd.DataFrame(data={'ID':0,'Skill I ID':0,'Skill II ID':0,'Name':0,'Quantity':0,'Skill I':0,'Skill II':0,'Subcategory':0},index=(0,1))

    # Locate items, weapons, armor and talismans
    index_item = df.index.get_loc('struct item i[1999]')
    df_item = df.iloc[index_item:index_item+5998]
    df_weapons = df.iloc[index_item+5998:index_item+17199]
    df_armor = df.iloc[index_item+17199:index_item+26800]
    df_talisman = df.iloc[index_item+26800:index_item+29801]
    df_item.reset_index(inplace=True)
    df_weapons.reset_index(inplace=True)
    df_armor.reset_index(inplace=True)
    df_talisman.reset_index(inplace=True)

    # Gather items
    for i in range(0,5998):
            if 'Item ID' in df_item.iloc[i,0]:
                id = df_item.iloc[i,1]
            if 'Amount' in df_item.iloc[i,0]:
                amount = df_item.iloc[i,1]
                s = {'ID':id,'Name':0,'Quantity':amount,'Category':0,'Subcategory':0}
                df2 = df2.append(s,ignore_index=True)

    # Gather weapons
    for i in range(0,4200):
            if 'Weapon Type' in df_weapons.iloc[i,0]:
                type = df_weapons.iloc[i,1]
                type_id = re.sub('[^0-9]','',type)
            if 'Weapon index' in df_weapons.iloc[i,0]:
                index = df_weapons.iloc[i,1]
            if 'Weapon Level' in df_weapons.iloc[i,0]:
                level = df_weapons.iloc[i,1]
                s = {'Index':index,'Type ID':type_id,'Name':0,'Level':level,'Quantity':1,'Type':type,'Subcategory':0}
                df3 = df3.append(s,ignore_index=True)

    # Gather armor
    for i in range(0,9600):
            if 'Armor Index' in df_armor.iloc[i,0]:
                index = df_armor.iloc[i,1]
            if 'Armor Level' in df_armor.iloc[i,0]:
                level = df_armor.iloc[i,1]
                s = {'Index':index,'Name':0,'Level':level,'Quantity':1}
                df4 = df4.append(s,ignore_index=True)

    # Gather talismans
    for i in range(0,3001):
            if 'Talisman Base ID' in df_talisman.iloc[i,0]:
                id = df_talisman.iloc[i,1]
            if 'Skill ID 1' in df_talisman.iloc[i,0]:
                skill_1 = df_talisman.iloc[i,1]
                skill_1_id = re.sub('[^0-9]','',skill_1)
            if 'Skill ID 2' in df_talisman.iloc[i,0]:
                skill_2 = df_talisman.iloc[i,1]
                skill_2_id = re.sub('[^0-9]','',skill_2)
                s = {'ID':id,'Skill I ID':skill_1_id,'Skill II ID':skill_2_id,'Name':0,'Quantity':1,'Skill I':skill_1,'Skill II':skill_2,'Subcategory':0}
                df5 = df5.append(s,ignore_index=True)

    # Cleaning dataframes
    df2 = df2[df2['ID'] != 0]

    # Adding dictionaries
    df_dict_items = pd.read_csv('dictionaries/MHS2_dictionary_items.csv')
    df_dict_items.set_index('ID', inplace=True)
    df_dict_armor = pd.read_csv('dictionaries/MHS2_dictionary_armor.csv')
    df_dict_armor.set_index('Index', inplace=True)
    df_dict_weapons = pd.read_csv('dictionaries/MHS2_dictionary_weapons.csv')
    df_dict_talismans = pd.read_csv('dictionaries/MHS2_dictionary_talismans.csv')

    # Adding item information
    for i in range(len(df2)):
        id = df2.iloc[i,0]
        try:
            s = {'ID':id,'Name':df_dict_items.loc[int(float(id)),'Name'],'Quantity':0,'Category':df_dict_items.loc[int(float(id)),'Category'],'Subcategory':df_dict_items.loc[int(float(id)),'Subcategory']}
            df2 = df2.append(s,ignore_index=True)
        except KeyError:
            continue

    # Adding weapons information
    for i in range(len(df3)):
            index = df3.iloc[i,0]
            type_id = df3.iloc[i,1]
            df_temp = df_dict_weapons[(df_dict_weapons['Index'] == int(float(index))) & (df_dict_weapons['Type ID'] == int(float(type_id)))]
            try:
                df_temp.reset_index(inplace=True)
                s = {'Index':index,'Type ID':type_id,'Name':df_temp.loc[0,'Name'],'Level':0,'Quantity':0,'Type':0,'Subcategory':df_temp.loc[0,'Subcategory']}
                df3 = df3.append(s,ignore_index=True)
            except KeyError:
                continue

    # Adding armor information
    for i in range(len(df4)):
        index = df4.iloc[i,0]
        try:
            s = {'Index':index,'Name':df_dict_armor.loc[int(float(index)),'Name'],'Level':0,'Quantity':0}
            df4 = df4.append(s,ignore_index=True)
        except KeyError:
            continue

    # Adding talismans information
    for i in range(len(df5)):
            skill_1_id = df5.iloc[i,1]
            skill_2_id = df5.iloc[i,2]
            df_temp = df_dict_talismans[(df_dict_talismans['Skill I ID'] == int(float(skill_1_id))) & (df_dict_talismans['Skill II ID'] == int(float(skill_2_id)))]
            try:
                df_temp.reset_index(inplace=True)
                s = {'ID':0,'Skill I ID':skill_1_id,'Skill II ID':skill_2_id,'Name':df_temp.loc[0,'Name'],'Quantity':0,'Skill I':0,'Skill II':0,'Subcategory':df_temp.loc[0,'Subcategory']}
                df5 = df5.append(s,ignore_index=True)
            except KeyError:
                continue

    # Cleaning
    df2 = df2.groupby(df2['ID'],sort=False).aggregate({'Name':'last','Quantity':'first','Category':'last','Subcategory':'last'})
    df3 = df3.groupby([df3['Index'],df3['Type ID']],sort=False).aggregate({'Name':'last','Level':'first','Quantity':'sum','Type':'first','Subcategory':'last'})
    df4 = df4.groupby(df4['Index'],sort=False).aggregate({'Name':'last','Level':'first','Quantity':'sum'})
    df5 = df5.groupby([df5['Skill I ID'],df5['Skill II ID']],sort=False).aggregate({'ID':'first','Name':'last','Quantity':'sum','Skill I':'first','Skill II':'first','Subcategory':'last'})

    # Outputting dataframes
    df2.to_csv(r'outputs/MHS2_output_items.csv',encoding='utf-8')
    df3.to_csv(r'outputs/MHS2_output_weapons.csv',encoding='utf-8')
    df4.to_csv(r'outputs/MHS2_output_armor.csv',encoding='utf-8')
    df5.to_csv(r'outputs/MHS2_output_talismans.csv',encoding='utf-8')


"""
output : 트리의 지름 출력
1. 아이디어
    - 양방향 그래프
    - 루트에서 가장 먼 노드찾기
    - 루트에서 가장 먼 노드에서 가장 먼 노드까지의 길이 구하기
2. 시간복잡도
N = 1e4 O(N*2)
"""
import sys; input = sys.stdin.readline
from collections import defaultdict
sys.setrecursionlimit(10**6)

def dfs(start, total):
    global answer, node
    if answer < total:
        answer = total
        node = start
    for nxt, weight in tree[start]:
        if not visited[nxt]:
            visited[nxt] = True
            dfs(nxt,total+weight)
            visited[nxt] = False

n = int(input())
tree = defaultdict(list)

for _ in range(n-1):
    p, c, w = map(int,input().split())
    tree[p].append((c,w))
    tree[c].append((p,w))

answer, node = -1, 0
visited = [False] * (n+1)
visited[1] = True
dfs(1,0)

visited = [False] * (n+1)
visited[node] = True
dfs(node,0)
print(answer)


from .Index_new_user_data import index_data
from .FbIndexManager import FbIndexManager
from .FbUser import FbUser
from django.shortcuts import render
from allauth.socialaccount.models import SocialToken
import pysolr
import threading

solr_string = 'https://solr.socialsearch.blog/solr/demo3/'
solr = pysolr.Solr(solr_string)

def results_list(request):
    if request.user.is_anonymous:
        return render(request, 'app/results_list.html', {'profpic': 0})

    if not request.session.get('search_done'):
        initialize_context(request)

    context = request.session['context']
    return render(request, 'app/results_list.html', context)

def initialize_context(request):
    token = SocialToken.objects.filter(account__user=request.user, account__provider='facebook').first()

    # inizializza i dati dell'utente loggato
    user = FbUser(token)
    user.initialize()

    index_manager = FbIndexManager(user, solr)
    thread = threading.Thread(target=index_data, args=(user, solr, index_manager))
    thread.start()

    score_list = solr.search(q='doc_type:score AND users:{}'.format(user.id),
                             fl='users, similarity',
                             sort='similarity desc',
                             rows=200, wt='json').docs

    # session variables to use in other view/template
    context = {'profpic': user.profPic, 'user_id': user.id, 'user_name': user.name,
               'score_list': score_list, 'solr': solr_string}

    request.session['context'] = context
    request.session['search_done'] = True
    request.session['similarity_done'] = False


class LightGrid:

    def processInstruction(line, matrix):
        instruction = LightGrid.parseInstruction(line)
        # assume an n x n matrix
        n = len(matrix[0])
        for i in range(instruction['xStart'], instruction['xEnd']+1):
            for j in range(instruction['yStart'], instruction['yEnd']+1):
                matrix[i][j] = LightGrid.applySwitch(instruction['operation'], matrix[i][j])

        return matrix

    def parseInstruction(line):
        # example input:
        #turn on 606,361 through 892,600
        #turn off 448,208 through 645,684
        #toggle 50,472 through 452,788
        input = line.split(' ')
        if (len(input) == 4) :
            start = input[1].split(',')
            end = input[3].split(',')
            return { 'operation' : input[0], 'xStart' : int(start[0]), 'yStart' : int(start[1]), 'xEnd' : int(end[0]), 'yEnd' : int(end[1]) }
        else:
            start = input[2].split(',')
            end = input[4].split(',')
            return { 'operation' : input[0] + " " + input[1], 'xStart' : int(start[0]), 'yStart' : int(start[1]), 'xEnd' : int(end[0]), 'yEnd' : int(end[1]) }

    def applySwitch(operation, existingValue):
        if operation == "turn on":
            return 1
        elif operation == "turn off":
            return 0
        else:
            if existingValue == 0:
                return 1
        return 0

    def countOnLights(matrix):
        count = 0
        # assume an n x n matrix
        n = len(matrix[0])
        for i in range(0, n):
            for j in range(0, n):
                count += matrix[i][j]
        return count


import sys
if '/opt/ros/kinetic/lib/python2.7/dist-packages' in sys.path:
    sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
sys.path.append("..")
import argparse
from config.config import cfg
from src.train import train
from src.Global_Localization_Interface import Global_Localization_Interface
from src.post_process_logs import post_process_logs

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    """
        Arguments for selecting operation modes among training, testing for the network, testing for MCL and data generation.
    """
    parser.add_argument("--operation", help="Select operation among train, test_MCL, post_process_logs", default='train')

    """
        Arguments for universal parameters.
    """
    parser.add_argument("--dataset", help="Select dataset among Simulation, Bicocca and UPO", default='Bicocca')
    parser.add_argument("--subdataset", help="Select sub-dataset among 1,2,...", default='1')
    parser.add_argument("--load_model", help="model path to load", default=None)
    parser.add_argument("--device", help="device used", default=cfg.DSOM_device)

    """
        Arguments for parameters required in training.
    """
    parser.add_argument("--num_epochs", help="the number of epochs to train", default=cfg.DSOM_num_epoch)
    parser.add_argument("--batchsize", help="the number of epochs to train", default=cfg.DSOM_batchsize)
    parser.add_argument("--num_iters_per_epoch_train", help="the number of iteration in each epoch when training", default=cfg.DSOM_training_iters)
    parser.add_argument("--num_iters_per_epoch_val", help="the number of iteration in validation", default=cfg.DSOM_validation_iters)
    parser.add_argument("--save_per_x_epoch", help="save model per x epoch", default=2)
    parser.add_argument("--decay_per_x_step", help="decay per x global steps", default=40000)
    parser.add_argument("--decay_rate", help="decay rate", default=0.999)
    parser.add_argument("--val_per_x_iters", help="validate per x iterations", default=3600)

    """
        Arguments for parameters required in testing for the network.
    """
    parser.add_argument("--num_iters_per_epoch_testing", help="the number of iteration in testing", default=cfg.DSOM_validation_iters)

    """
        Arguments for parameters required in testing for the MCL.
    """
    parser.add_argument("--particle_num", help="The number of particles used in the filter", default=1000)
    parser.add_argument("--update_mode", help="The mode used in the filter", default='DL_Aided_Particle_Filter')
    parser.add_argument("--random_sampling", help="Random sample or not", default=True)
    parser.add_argument("--random_sample_rate", help="Random sample rate", default=0.2)
    parser.add_argument("--w_cut", help="parameter for cutting weight", default=0.6)
    parser.add_argument("--rc_lamda_short", help="lamda for short model", default=1)
    parser.add_argument("--rc_w_hit", help="Weight for hit model", default=0.95)
    parser.add_argument("--rc_w_short", help="Weight for short model", default=1)
    parser.add_argument("--rc_w_max", help="Weight for max model", default=1)
    parser.add_argument("--rc_w_rand", help="Weight for random model", default=0.05)
    parser.add_argument("--p_mcl", help="probability to execute MCL in Mixture MCL", default=0.95)
    args = parser.parse_args()

    if args.dataset == "simulation":
        cfg.DSOM_X = 129
        cfg.DSOM_Y = 129
        cfg.DSOM_batchsize = 32
        args.batchsize = 32
    else:
        cfg.DSOM_X = 320
        cfg.DSOM_Y = 320
        cfg.DSOM_batchsize = 16
        args.batchsize = 16

    if args.operation == "train":
        train_model = train(args.dataset,args.subdataset,int(args.batchsize), int(args.num_iters_per_epoch_train), args.num_iters_per_epoch_val, args.num_epochs, args.device, args.load_model, args.save_per_x_epoch, int(args.decay_per_x_step), args.decay_rate, args.val_per_x_iters)
        train_model.train()

    elif args.operation == "test_MCL":
        cfg.DSOM_batchsize = 1
        args.batchsize = 1
        cfg.DSOM_model_path = args.load_model
        if args.dataset == 'simulation':
            paras = {'Random_Produce': args.random_sampling, 'scan_res': cfg.simulation_Dataset_angle_step,
                     'scan_angle_st': cfg.simulation_Dataset_st_angle,
                     'max_scan_range': cfg.simulation_Dataset_max_range,
                     'var_rc_weighting_model': 5,
                     'laser_portions': cfg.simulation_Dataset_scan_steps, 'Random_sample_var_x': 0.1, 'Random_sample_var_y': 0.1,
                     'Random_sample_var_theta': 0.1, 'w_cut': float(args.w_cut),
                     'rc_lamda_short': float(args.rc_lamda_short),
                     'rc_w_hit': float(args.rc_w_hit), 'rc_w_short': float(args.rc_w_short),
                     'rc_w_max': float(args.rc_w_max), 'rc_w_rand': float(args.rc_w_rand),
                     'device': 'cpu', 'laser_steps': 5, 'random_sample_rate': args.random_sample_rate,'P_MCL': float(args.p_mcl),
                     'resolution':cfg.simulation_Dataset_resolution,
                     }
        elif args.dataset == 'Bicocca':
            paras = {'Random_Produce': args.random_sampling, 'scan_res': cfg.Bicocca_angle_step,
                     'scan_angle_st': cfg.Bicocca_st_angle,
                     'max_scan_range': cfg.Bicocca_laser_max_range,
                     'var_rc_weighting_model': 5,
                     'laser_portions': cfg.Bicocca_scan_steps, 'Random_sample_var_x': 0.1,
                     'Random_sample_var_y': 0.1,
                     'Random_sample_var_theta': 0.1, 'w_cut': float(args.w_cut),
                     'rc_lamda_short': float(args.rc_lamda_short),
                     'rc_w_hit': float(args.rc_w_hit), 'rc_w_short': float(args.rc_w_short),
                     'rc_w_max': float(args.rc_w_max), 'rc_w_rand': float(args.rc_w_rand),
                     'device': 'cpu', 'laser_steps': 5, 'random_sample_rate': args.random_sample_rate,
                     'P_MCL': float(args.p_mcl),
                     'resolution': cfg.Bicocca_resolution,
                     }

        elif args.dataset == 'UPO':
            paras = {'Random_Produce': args.random_sampling, 'scan_res': cfg.UPO_Dataset_angle_increment,
                     'scan_angle_st': cfg.UPO_Dataset_angle_min,
                     'max_scan_range': cfg.UPO_Dataset_range_max,
                     'var_rc_weighting_model': 5,
                     'laser_portions': cfg.UPO_Dataset_angle_portions, 'Random_sample_var_x': 0.1,
                     'Random_sample_var_y': 0.1,
                     'Random_sample_var_theta': 0.1, 'w_cut': float(args.w_cut),
                     'rc_lamda_short': float(args.rc_lamda_short),
                     'rc_w_hit': float(args.rc_w_hit), 'rc_w_short': float(args.rc_w_short),
                     'rc_w_max': float(args.rc_w_max), 'rc_w_rand': float(args.rc_w_rand),
                     'device': 'cpu', 'laser_steps': 5, 'random_sample_rate': args.random_sample_rate,
                     'P_MCL': float(args.p_mcl),
                     'resolution': cfg.UPO_Dataset_resolution,
                     }
        for exp in range(100):
            Interface = Global_Localization_Interface(args.dataset,args.subdataset,args.update_mode,args.particle_num,paras)

            Interface.update_pf()
    elif args.operation == "post_process_logs":
        post_process_logs('./logs/',1,10 * 3.14159 / 180,10)
    else:
        assert ('No operation selected!')


import pickle
import random
from time import time
from typing import Union

import numpy as np
import torch
from torch import nn, optim
from torch.nn import functional as F
from torch.nn.functional import mse_loss, l1_loss, binary_cross_entropy, cross_entropy
from torch.optim import Optimizer

class NBeatsNet(nn.Module):
    SEASONALITY_BLOCK = "seasonality"
    TREND_BLOCK = "trend"
    GENERIC_BLOCK = "generic"

    def __init__(
        self,
        device=torch.device("cpu"),
        stack_types=(TREND_BLOCK, SEASONALITY_BLOCK),
        nb_blocks_per_stack=3,
        forecast_length=5,
        backcast_length=10,
        thetas_dim=(4, 8),
        share_weights_in_stack=False,
        hidden_layer_units=256,
        final_layer_units=512,
        nb_harmonics=None,
    ):
        super(NBeatsNet, self).__init__()
        self.forecast_length = forecast_length
        self.backcast_length = backcast_length
        self.hidden_layer_units = hidden_layer_units
        self.nb_blocks_per_stack = nb_blocks_per_stack
        self.share_weights_in_stack = share_weights_in_stack
        self.nb_harmonics = nb_harmonics
        self.stack_types = stack_types
        self.stacks = []
        self.thetas_dim = thetas_dim
        self.parameters = []
        self.final_layer_units = final_layer_units
        self.device = device
        print("| N-Beats")
        for stack_id in range(len(self.stack_types)):
            self.stacks.append(self.create_stack(stack_id))
        self.parameters = nn.ParameterList(self.parameters)
        self.final_layer = nn.Sequential(
            nn.Linear(self.hidden_layer_units, self.final_layer_units),
            nn.ReLU(),
            nn.Linear(self.final_layer_units, 2),
            nn.Softmax(dim=1),
        )

        self.to(self.device)
        self._loss = None
        self._opt = None

    def create_stack(self, stack_id):
        stack_type = self.stack_types[stack_id]
        print(
            f"| --  Stack {stack_type.title()} (#{stack_id}) (share_weights_in_stack={self.share_weights_in_stack})"
        )
        blocks = []
        for block_id in range(self.nb_blocks_per_stack):
            block_init = NBeatsNet.select_block(stack_type)
            if self.share_weights_in_stack and block_id != 0:
                block = blocks[-1]  # pick up the last one when we share weights.
            else:
                block = block_init(
                    self.hidden_layer_units,
                    self.thetas_dim[stack_id],
                    self.device,
                    self.backcast_length,
                    self.forecast_length,
                    self.nb_harmonics,
                )
                self.parameters.extend(block.parameters())
            print(f"     | -- {block}")
            blocks.append(block)
        return blocks

    def save(self, filename: str):
        torch.save(self, filename)

    @staticmethod
    def load(f, map_location=None, pickle_module=pickle, **pickle_load_args):
        return torch.load(f, map_location, pickle_module, **pickle_load_args)

    @staticmethod
    def select_block(block_type):
        if block_type == NBeatsNet.SEASONALITY_BLOCK:
            return SeasonalityBlock
        elif block_type == NBeatsNet.TREND_BLOCK:
            return TrendBlock
        else:
            return GenericBlock

    def forward(self, backcast):
        backcast = squeeze_last_dim(backcast)
        # forecast = torch.zeros(size=(backcast.size()[0], self.forecast_length,))  # maybe batch size here.
        for stack_id in range(len(self.stacks)):
            for block_id in range(len(self.stacks[stack_id])):
                # get the hidden unit feature representation of the block.
                block = self.stacks[stack_id][block_id]
                backcast = block(backcast)

        # apply the final linear layer for binary classification
        forecast = self.final_layer(backcast)
        return forecast

        # b, f = self.stacks[stack_id][block_id](backcast)
        # backcast = backcast.to(self.device) - b
        # forecast = forecast.to(self.device) + f
        # return backcast, forecast

def squeeze_last_dim(tensor):
    if len(tensor.shape) == 3 and tensor.shape[-1] == 1:  # (128, 10, 1) => (128, 10).
        return tensor[..., 0]
    return tensor

def seasonality_model(thetas, t, device):
    p = thetas.size()[-1]
    assert p <= thetas.shape[1], "thetas_dim is too big."
    p1, p2 = (p // 2, p // 2) if p % 2 == 0 else (p // 2, p // 2 + 1)
    s1 = torch.tensor([np.cos(2 * np.pi * i * t) for i in range(p1)]).float()  # H/2-1
    s2 = torch.tensor([np.sin(2 * np.pi * i * t) for i in range(p2)]).float()
    S = torch.cat([s1, s2])
    return thetas.mm(S.to(device))

def trend_model(thetas, t, device):
    p = thetas.size()[-1]
    assert p <= 4, "thetas_dim is too big."
    T = torch.tensor([t**i for i in range(p)]).float()
    return thetas.mm(T.to(device))

def linear_space(backcast_length, forecast_length, is_forecast=True):
    horizon = forecast_length if is_forecast else backcast_length
    return np.arange(0, horizon) / horizon

class Block(nn.Module):
    def __init__(
        self,
        units,
        thetas_dim,
        device,
        backcast_length=10,
        forecast_length=5,
        share_thetas=False,
        nb_harmonics=None,
    ):
        super(Block, self).__init__()
        self.units = units
        self.thetas_dim = thetas_dim
        self.backcast_length = backcast_length
        self.forecast_length = forecast_length
        self.share_thetas = share_thetas
        self.fc1 = nn.Linear(backcast_length, units)
        self.fc2 = nn.Linear(units, units)
        self.fc3 = nn.Linear(units, units)
        self.fc4 = nn.Linear(units, units)
        self.device = device
        self.backcast_linspace = linear_space(
            backcast_length, forecast_length, is_forecast=False
        )
        self.forecast_linspace = linear_space(
            backcast_length, forecast_length, is_forecast=True
        )
        if share_thetas:
            self.theta_f_fc = self.theta_b_fc = nn.Linear(units, thetas_dim, bias=False)
        else:
            self.theta_b_fc = nn.Linear(units, thetas_dim, bias=False)
            self.theta_f_fc = nn.Linear(units, thetas_dim, bias=False)

    def forward(self, x):
        x = squeeze_last_dim(x)
        x = F.relu(self.fc1(x.to(self.device)))
        x = F.relu(self.fc2(x))
        x = F.relu(self.fc3(x))
        x = F.relu(self.fc4(x))
        return x

    def __str__(self):
        block_type = type(self).__name__
        return (
            f"{block_type}(units={self.units}, thetas_dim={self.thetas_dim}, "
            f"backcast_length={self.backcast_length}, forecast_length={self.forecast_length}, "
            f"share_thetas={self.share_thetas}) at @{id(self)}"
        )

class SeasonalityBlock(Block):
    def __init__(
        self,
        units,
        thetas_dim,
        device,
        backcast_length=10,
        forecast_length=5,
        nb_harmonics=None,
    ):
        if nb_harmonics:
            super(SeasonalityBlock, self).__init__(
                units,
                nb_harmonics,
                device,
                backcast_length,
                forecast_length,
                share_thetas=True,
            )
        else:
            super(SeasonalityBlock, self).__init__(
                units,
                forecast_length,
                device,
                backcast_length,
                forecast_length,
                share_thetas=True,
            )

    def forward(self, x):
        x = super(SeasonalityBlock, self).forward(x)
        backcast = seasonality_model(
            self.theta_b_fc(x), self.backcast_linspace, self.device
        )
        forecast = seasonality_model(
            self.theta_f_fc(x), self.forecast_linspace, self.device
        )
        return backcast, forecast

class TrendBlock(Block):
    def __init__(
        self,
        units,
        thetas_dim,
        device,
        backcast_length=10,
        forecast_length=5,
        nb_harmonics=None,
    ):
        super(TrendBlock, self).__init__(
            units,
            thetas_dim,
            device,
            backcast_length,
            forecast_length,
            share_thetas=True,
        )

    def forward(self, x):
        x = super(TrendBlock, self).forward(x)
        backcast = trend_model(self.theta_b_fc(x), self.backcast_linspace, self.device)
        forecast = trend_model(self.theta_f_fc(x), self.forecast_linspace, self.device)
        return backcast, forecast

class GenericBlock(Block):
    def __init__(
        self,
        units,
        thetas_dim,
        device,
        backcast_length=10,
        forecast_length=5,
        nb_harmonics=None,
    ):
        super(GenericBlock, self).__init__(
            units, thetas_dim, device, backcast_length, forecast_length
        )

        self.backcast_fc = nn.Linear(thetas_dim, backcast_length)
        self.forecast_fc = nn.Linear(thetas_dim, forecast_length)

    def forward(self, x):
        # no constraint for generic arch.
        x = super(GenericBlock, self).forward(x)

        # theta_b = self.theta_b_fc(x)
        # theta_f = self.theta_f_fc(x)

        # backcast = self.backcast_fc(theta_b)  # generic. 3.3.
        # forecast = self.forecast_fc(theta_f)  # generic. 3.3.

        # return backcast, forecast

        return x


from calc import *

menu()

funkcje = {'1': dodawanie, '2': odejmowanie, '3': mnozenie, '4': dzielenie, '5': dzieleniecal, '6': potegowanie,
           '7': autor, '8': zakoncz}
nazwyFunkcji = {'1': 'dodawanie', '2': 'odejmowanie', '3': 'mnożenie', '4': 'dzielenie', '5': 'dzielenie całkowite',
                '6': 'potęgowanie', '7': 'autor', '8': 'zakończ'}

operacja = input("Co wybierasz?")
while operacja != "8":
    wybranaFkcja = funkcje.get(operacja, blad)
    nazwaWybranejFkcji = nazwyFunkcji.get(operacja, blad)
    print(nazwaWybranejFkcji)
    print(wybranaFkcja())
    operacja = input("Co wybierasz? ")
print("Koniec")


import random
from typing import List, Union

import pytest

from pysegmenttree import PySegmentTree, QueryFunction, stree
from pysegmenttree._abc import T
from pysegmenttree.c_extensions import FloatSegmentTree, IntSegmentTree
from pysegmenttree.test_utils import VerifySegmentTree

CLASSES = [PySegmentTree, IntSegmentTree, FloatSegmentTree]
SUPPORTED_FUNCTIONS = [f for f in QueryFunction]

def construct_tree(
    kls: Union[PySegmentTree, IntSegmentTree, FloatSegmentTree],
    source: List[T],
    func: QueryFunction,
):
    if kls is PySegmentTree:
        return kls(source=source, func=func)
    elif kls in (IntSegmentTree, FloatSegmentTree):
        return kls(source=source, func=func.value)
    else:
        raise RuntimeError(f"Unexpected tree class {kls}")

@pytest.mark.parametrize("cls", CLASSES)
@pytest.mark.parametrize("func", SUPPORTED_FUNCTIONS)
def test_len(cls: type, func: QueryFunction):
    tree = construct_tree(cls, [18, 17, 13, 19], func)
    assert len(tree) == 4

@pytest.mark.parametrize("cls", CLASSES)
def test_query(cls: type):
    source = [18, 17, 13, 19, 15, 11, 20, 12, 33, 25]

    tree = construct_tree(cls, source, func=QueryFunction.SUM)
    v_tree = VerifySegmentTree(source, func=QueryFunction.SUM)

    queries = [[0, 3], [2, 7], [6, 7], [0, len(source)]]
    expected = [48, 78, 20, 183]

    for (start, end), expected in zip(queries, expected):
        assert tree.query(start, end) == expected

@pytest.mark.parametrize("cls", CLASSES)
def test_update(cls: type):
    source = [18, 17, 13, 19, 15, 11, 20, 12, 33, 25]
    tree = construct_tree(cls, source, func=QueryFunction.SUM)

    tree.update(0, 20)
    tree.update(3, 14)
    assert tree.query(0, 3) == 50
    assert tree.query(2, 7) == 73
    tree.update(7, -10)

    assert tree.query(5, 9) == 54
    assert tree.query(0, len(source)) == 158

@pytest.mark.parametrize("cls", CLASSES)
@pytest.mark.parametrize("func", SUPPORTED_FUNCTIONS)
def test_query_random(cls: type, func: QueryFunction):
    random.seed(42)

    size = 500
    rng = 100000
    queries = 1000

    source = [random.randint(-rng, rng) for _ in range(size)]
    tree = construct_tree(cls, source, func=func)
    verify_tree = VerifySegmentTree(
        source=source,
        func=func,
    )

    for _ in range(queries):
        left, right = sorted((random.randint(0, size - 1), random.randint(0, size - 1)))
        assert tree.query(left, right) == verify_tree.query(left, right)

@pytest.mark.parametrize("cls", CLASSES)
@pytest.mark.parametrize("func", SUPPORTED_FUNCTIONS)
def test_query_n_update_random(cls: type, func: QueryFunction):
    random.seed(-42)

    size = 500
    rng = 100000
    queries = 1000

    source = [random.randint(-rng, rng) for _ in range(size)]
    tree = construct_tree(cls, source, func=func)
    verify_tree = VerifySegmentTree(source=source, func=func)

    for _ in range(queries):
        indx = random.randint(0, size - 1)
        value = random.randint(-rng, rng)

        tree.update(indx, value)
        verify_tree.update(indx, value)

        left, right = sorted((random.randint(0, size - 1), random.randint(0, size - 1)))
        assert tree.query(left, right) == verify_tree.query(left, right)


import cv2

#Capture video from webcam
vid_capture = cv2.VideoCapture(0)
size = (int(vid_capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),
        int(vid_capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.cv.FOURCC('8', 'B', 'P', 'S')     #works, large
out = cv2.VideoWriter("output.avi", fourcc, 20.0, size, True)
while(True):
     # Capture each frame of webcam video
     ret,frame = vid_capture.read()
     cv2.imshow("My cam video", frame)
     frame = cv2.flip(frame,0)
     out.write(frame)
     # Close and break the loop after pressing "x" key
     if cv2.waitKey(1) &0XFF == ord('x'):
         break

# close the already opened camera
vid_capture.release()
# close the already opened file
out.release()
# close the window and de-allocate any associated memory usage
cv2.destroyAllWindows()


from collections import deque

v = int(input())
e = int(input())
graph = [[] for i in range(v+1)]
visited = [False] * (v+1)
count = 0

for i in range(e):
  a, b = map(int, input().split())
  graph[a] += [b]
  graph[b] += [a]

def bfs(node):
  global count
  q = deque()
  q.append(node)
  while q:
    node = q.popleft()
    if visited[node] == False:
      visited[node] = True
      q.extend(graph[node])
      count += 1

bfs(1)
print(count-1)


"""
Matthew Schwartz
One Dimensional Modeling of Plant Growth
Model 2

This program models plant growth in one dimension. It utilizes several different
numerical methods to solve a set of ordinary differential equations describing
plant growth. These methods include:
    - Euler Method
    - Adaptive Euler Method
    - 4th Order Runge-Kutta Method
    - 4th Order Adaptive Runge-Kutta Method

It also solves the one-dimensional diffusion-advection equation, using the
Crank Nicolson Method.

Equations to solve:
    - dL/dt = f(R)    where x = L(t), x is the end of the plant.
    - h*(dR/dt) = g(R)*C - sigma*R
    - g(R) and f(R) are piecewise functions
    - dC/dt = -u*dC/dx + d*d^2C/dx^2, the diffusion-advection equation

Inputs:
    - Method:     ODE solver (suggestion: 3)
    - Tau:        Time step (suggestion: 0.0001)
    - nstep:      Number of steps (suggestion: 10000)
    - N:          Number of grid points (suggestion: 100)

Outputs:
    - Graph: Growth Factor Concentration vs. Time
    - Graph: Plant Length vs. Time
    - Graph: Metabolite concentration at end-point vs. time

"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.sparse import diags

#%% Construct f(R) and g(R)

def f(R):
    """ f is a piecewise linear function """

    if 0 <= R <= Rf:
        f = 0
    elif R > Rf:
        f = f0
    else:
        print('Error: R must be greater than 0')

    return f

def g(R):
    """ g is a piecewise linear function """

    if 0 <= R <= Rg1:
        g = .015*sigma*R
    elif Rg1 < R <= Rg2:
        g = 0.06*Rg1
    elif R > Rg2:
        g = 0
    else:
        print('Error: R must be greater than 0')

    return g

#%% Parameters and Initial Conditions

# User Inputs
method = int(input("Choose a number for a numerical method: \n\
 1-Euler\n 2-Adaptive Euler\n 3-4th Order Runge-Kutta\n 4-Adaptive R-K: "))
tau = float(input('Enter time step: '))
nstep = int(input('Enter number of steps: '))
N = int(input('Enter initial number of grid points: '))
anim = int(input('Animate? (1)Yes (2)No: '))

# Parameters
sigma = 0.009           # Growth factor decay coefficient
w = 0.001               # Width of meristem
d = 0.001               # Diffusion coefficient (of metabolites in xylem fluid)
Rf = 0.005              # Critical values of R and G functions
Rg1 = 0.01                          # " "
Rg2 = 0.05                          # " "
f0 = 1                              # " "

err = 1.e-3             # Used by adaptive routines
total_time = 100.;

# Initial Conditions
Rplot = [Rf / 2.0]       # Growth factor starts below critical value
Lplot = [0.01]           # Plant length is 0 at t = 0
Cplot = [0]
tplot = [0]

# Initiate a grid (for concentration of metabolites)
h = Lplot[0]/(N-1)        # Spacing of grid
x = np.arange(0,N)*h      # Initial coordinates of grid points
C = np.zeros(N)           # Initiate C (concentration of metabolites)
C[0] = 1                  # Boundary Condition
b = (tau*d) / (2*(h**2))  # Final parameter (depends on h so must be defined here)

# Construct State Vector
state = np.array([Rplot[0],Lplot[0]])
#%% Numerical Method Functions

def euler(x,C,t,tau,derivsRK):
# %  Euler integrator (1st order)
# % Input arguments -
# %   x = current value of dependent variable
# %   t = independent variable (usually time)
# %   tau = step size (usually timestep)
# %   derivsRK = right hand side of the ODE; derivsRK is the
# %             name of the function which returns dx/dt
# %             Calling format derivsRK(x,t,param).
# %  Output arguments -
# %   xout = new value of x after a step of size tau

    F1 = derivsRK(x,C,t)
    xout = x + tau*F1
    return xout;

def eulera(x,C,t,tau,err,derivsRK):
# % Adaptive Euler routine
# % Inputs
# %   x          Current value of the dependent variable
# %   t          Independent variable (usually time)
# %   tau        Step size (usually time step)
# %   err        Desired fractional local truncation error
# %   derivsRK   Right hand side of the ODE; derivsRK is the
# %              name of the function which returns dx/dt
# %              Calling format derivsRK(x,t,param).
# % Outputs
# %   xSmall     New value of the dependent variable
# %   t          New value of the independent variable
# %   tau        Suggested step size for next call to rka

#* Set initial variables
    tSave = t;  xSave = x;    # Save initial values
    safe1 = 0.9;  safe2 = 4.;  # Safety factors

    #* Loop over maximum number of attempts to satisfy error bound
    maxTry = 500;
    for iTry in range(0,maxTry):

      #* Take the two small time steps
      half_tau = 0.5 * tau;
      xTemp = euler(xSave,C,tSave,half_tau,derivsRK);
      t = tSave + half_tau;
      xSmall = euler(xTemp,C,t,half_tau,derivsRK);

      #* Take the single big time step
      t = tSave + tau;
      xBig = euler(xSave,C,tSave,tau,derivsRK);

      #* Compute the estimated truncation error
      scale = err * (np.abs(xSmall) + np.abs(xBig))/2.;
      xDiff = xSmall - xBig;
      errorRatio = np.max( abs(xDiff)/(scale + np.spacing(1)) );

      #* Estimate new tau value (including safety factors)
      tau_old = tau;
      tau = safe1*tau_old*errorRatio**(-0.5);
      tau = np.max([tau,tau_old/safe2]);
      tau = np.min([tau,safe2*tau_old]);

      #* If error is acceptable, return computed values
      if (errorRatio < 1) :
        xSmall = 2*xSmall - xBig; # higher order correction
        return xSmall, t, tau

    #* Issue error message if error bound never satisfied
    BaseException('ERROR: Adaptive Euler routine failed');

def rk4(x,C,t,tau,derivsRK):
#%  Runge-Kutta integrator (4th order)
#% Input arguments -
#%   x = current value of dependent variable
#%   t = independent variable (usually time)
#%   tau = step size (usually timestep)
#%   derivsRK = right hand side of the ODE; derivsRK is the
#%             name of the function which returns dx/dt
#%             Calling format derivsRK(x,t).
#% Output arguments -
#%   xout = new value of x after a step of size tau
    half_tau = 0.5*tau
    F1 = derivsRK(x,C,t)
    t_half = t + half_tau
    xtemp = x + half_tau*F1
    F2 = derivsRK(xtemp,C,t_half)
    xtemp = x + half_tau*F2
    F3 = derivsRK(xtemp,C,t_half)
    t_full = t + tau
    xtemp = x + tau*F3
    F4 = derivsRK(xtemp,C,t_full)
    xout = x + tau/6.*(F1 + F4 + 2.*(F2+F3))
    return xout

def rka(x,C,t,tau,err,derivsRK):

#% Adaptive Runge-Kutta routine
#% Inputs
#%   x          Current value of the dependent variable
#%   t          Independent variable (usually time)
#%   tau        Step size (usually time step)
#%   err        Desired fractional local truncation error
#%   derivsRK   Right hand side of the ODE; derivsRK is the
#%              name of the function which returns dx/dt
#%              Calling format derivsRK(x,t).
#% Outputs
#%   xSmall     New value of the dependent variable
#%   t          New value of the independent variable
#%   tau        Suggested step size for next call to rka

#%* Set initial variables
    tSave = t;  xSave = x    # Save initial values
    safe1 = .9;  safe2 = 4.  # Safety factors
    eps = np.spacing(1) # smallest value

#%* Loop over maximum number of attempts to satisfy error bound
    maxTry = 100

    for iTry in range(1,maxTry):

#%* Take the two small time steps
        half_tau = 0.5 * tau
        xTemp = rk4(xSave,C,tSave,half_tau,derivsRK)
        t = tSave + half_tau
        xSmall = rk4(xTemp,C,t,half_tau,derivsRK)

  #%* Take the single big time step
        t = tSave + tau
        xBig = rk4(xSave,C,tSave,tau,derivsRK)

  #%* Compute the estimated truncation error
        scale = err * (np.abs(xSmall) + np.abs(xBig))/2.
        xDiff = xSmall - xBig
        errorRatio = np.max( [np.abs(xDiff)/(scale + eps)] )

        #print safe1,tau,errorRatio

  #%* Estimate news tau value (including safety factors)
        tau_old = tau

        tau = safe1*tau_old*errorRatio**(-0.20)
        tau = np.max([tau,tau_old/safe2])
        tau = np.min([tau,safe2*tau_old])

  #%* If error is acceptable, return computed values
        if errorRatio < 1 :
          # xSmall = xSmall #% +  (xDiff)/15
          #   xSmall = (16.*xSmall - xBig)/15. # correction
            return xSmall, t, tau

#%* Issue error message if error bound never satisfied
    print ('ERROR: Adaptive Runge-Kutta routine failed')
    return

def crank(s,C_in):
#%  Returns updated C vector (as part of state vector)
#%  Utilizes Crank-Nicolson method
#%  Inputs
#%    s      State vector [R, L]
#%    C_in   Concentration vector
#%  Output
#%    C_out  Updated concentration vector

    N = len(C_in)
    a = (tau*f(s[0])) / (4*h)

    # Initiate two intermediate matrices used to solve problem
    M1 = diags([-a-b, 1+2*b, a-b], [-1, 0, 1], shape=(N, N)).toarray()
    M2 = diags([b+a, 1-2*b, b-a], [-1, 0, 1], shape=(N, N)).toarray()

    # Final Matrix:
    M = np.linalg.inv(M1).dot(M2)

    C_out = C_in.dot(M)    # written this way because C is a row vector

    return C_out

def plantrk(s,C,t):
#%  Returns right-hand side of Plant ODE; used by Runge-Kutta routines
#%  Inputs
#%    s      State vector [R, L]
#%    C      Metabolite concentration vector
#%    t      Time (not used)
#%  Output
#%    deriv  Derivatives [dR/dt(1) dLdt(1)]

    drdt = ((C[-1])*g(s[0]) - sigma*s[0]) / w
    dldt = f(s[0])

#%* Return derivatives
    derivs = np.array([drdt, dldt])
    return derivs

#%% Solve ODE for R
time = 0.  # Initialize time
for istep in range(0,nstep):    ###  MAIN LOOP  ###

    # Record length before update
    L0 = np.copy(state[1])

    # Methods to solve for L(t)

    if ( method == 1 ):       # Euler Method
        state = euler(state,C,time,tau,plantrk)
        time = time + tau

    if ( method == 2 ):       # Adaptive Euler Method
        if time > total_time:
            print('time completed in istep=',istep)
            break
        [state, time, tau] = eulera(state,C,time,tau,err,plantrk)

    if ( method == 3 ):       # 4th Order Runge-Kutta
        state = rk4(state,C,time,tau,plantrk)
        time = time + tau

    if ( method == 4 ):       # Adaptive 4th Order Runge-Kutta
        if time > total_time:
            print('time completed in istep=',istep)
            break
        [state, time, tau] = rka(state,C,time,tau,err,plantrk)

    ## Solve for and update concentration C ##
    C = crank(state,C)

    # Lengthen C vector by change in L and use boundary conditions
    dL = state[1] - L0               # Change in L
    dN = np.int(np.round(dL / h))    # Number of new grid points

    # Apply BCs to fill in new grid points.
    C[0] = 1
    Ci = (1-(g(state[0])*(h/d)))*C[-1]
    if dL > 0:
        C = np.append(C,dN*[Ci])
    else:
        C[-1] = Ci

    # Print statement to denote step
    if ( istep % 1000 ) == 0:
        print('Number of iterations completed:',istep)

    # Append to plot vectors
    Rplot.append(state[0])
    Lplot.append(state[1])
    Cplot.append(C[-1])
    tplot.append(time)

#%% Plotting

# Non-animated plots of L(t) and R(t)
plt.figure()
plt.plot(tplot,Lplot)
plt.title('Length of Plant vs Time'); plt.xlabel('Time'); plt.ylabel('Length');
plt.grid()

plt.figure()
plt.plot(tplot,Rplot)
plt.title('Growth Factor Concentration vs. Time'); plt.xlabel('Time'); plt.ylabel('Concentration')
plt.grid()

plt.figure()
plt.plot(tplot,Cplot)
plt.title('Metabolite Concentration vs. Time'); plt.xlabel('Time'); plt.ylabel('Concentration')
plt.grid()


def main():
    N,M=map(int,input().split())
    edges=[[float("inf") for _ in range(N+1)]for _ in range(N+1)]
    for n in range(1,N+1):
        edges[n][n]=0
    for _ in range(M):
        u,v=map(int,input().split())
        edges[u][v]=1
        edges[v][u]=1
    K=int(input())
    dists=warshall(N,edges)
    colors=[0 for _ in range(N+1)]
    for _ in range(K):
        p,min_d=map(int,input().split())
        d=dists[p]

def warshall(N:int,d:list)->list:
    for k in range(1,N+1):
        for i in range(1,N+1):
            for j in range(1,N+1):
                d[i][j]=min(d[i][j],d[i][k]+d[k][j])
    return d

if __name__=="__main__":
    main()


from random import *
def arvud_loendis():
    print("Данные:")
    n=abs(int(input("Сколько целых чисел генерируем в список? => ")))
    mini=int(input("Введите минимальное число диапазона => "))
    maxi=int(input("Введите максимальное число диапазона => "))
    if mini>maxi:
        mini,maxi=vahetus(mini,maxi)
    s=[]
    generaator(n,s,mini,maxi)
    print()
    print("Результаты:")
    print("Полученный список от",mini,"до",maxi,s)
    s.sort()
    print("Отсортированный список",s)
    pos=[]
    neg=[]
    null=[]
    jagamine(s,pos,neg,null)
    print("Список положительных элементов",pos)
    print("Список отрицательных элементов",neg)
    print("Список нулевых элементов",null)
    kesk=keskmine(pos)
    lisamine(s,kesk)
    print("Среднее положительных:",kesk)
    kesk=keskmine(neg)
    lisamine(s,kesk)
    print("Среднее отрицательных:",kesk)
    print("Добавляем средние в изначалный массив:")
    s.sort()
    print(s)

def vahetus(a:int,b:int):
    """
    Меняет местами mini и maxi если mini больше maxi
    :param a :вводимое пользавателем неправельное минимальное число диапазона
    :param b :вводимое пользавателем неправельное максимальное число диапазона
    """
    abi=a
    a=b
    b=abi
    return a,b

def generaator(n:int,loend:list,a:int,b:int):
    """
    Выдает n случайных чисел от а до b
    :param int n : сколко раз нужно повторить цкал
    :param int a : какое минимальное число диапазона будет выведен
    :param int b : какое максимальное число диапазона будет выведен
    :param list loend : хранит даные выведенных чисел
    """
    for i in range (n):
        loend.append(randint(a,b))

def jagamine(loend:list,p:int,n:int,nol:int):
    """
    Проверяет и запоменает в списки pos, neg, null
    из списка loend сколько позитивных,негативных и нулей
    :param int p :
    :param int n :
    :param int nol :
    :list loend : хранит даные проверенных чисел
    """
    for el in loend:
        if el>0:
            p.append(el)
        elif el<0:
            n.append(el)
        else:
            nol.append(el)

def keskmine(loend):
    """
    """
    n=len(loend)
    if n==0:
        kesk=0
    else:
        sum=0
        for i in loend:
            sum+=i
        kesk=round(sum/n,2)
    return kesk

def lisamine(loend,el):
    loend.append(el)
    loend.sort()


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

#2次元遅れ系
from scipy import signal
import matplotlib.pyplot as plt

jita=float(input("減衰係数"))
omega_n=float(input("共振角周波数"))

# 伝達関数の定義
num = [omega_n] # 分子の係数
den = [1,2*jita*omega_n ,omega_n**2] # 分母の係数
G = signal.lti(num, den)

# ボード線図の計算
w, mag, phase = signal.bode(G)

# ゲイン線図の描画
plt.subplot(2, 1, 1)
plt.semilogx(w, mag)
plt.ylabel("Gain[dB]")
plt.grid()

# 位相線図の描画
plt.subplot(2, 1, 2)
plt.semilogx(w, phase)
plt.xlabel("w[rad/sec]")
plt.ylabel("Phase[deg]")
plt.grid()
plt.show()


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

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import torch
import torch.nn as nn
import torch.nn.functional as F
import os

folder = 'Test_ANN_incidence_NPI_prova/'#5000 neuroni hidden layer

os.mkdir(folder)

class Net(nn.Module):
    def __init__(self, I0, training_size, dt, gamma):
      super(Net, self).__init__()
      self.neurons = 50
      self.dimTimes = 100
      self.init_shape = 100 # Timesteps X params_type, in this case 100 X 1 (only NPIs, no temperature nor other QOIs)
      self.fc0 = nn.Linear(self.init_shape, self.neurons)
      self.fc1 = nn.Linear(self.neurons,self.neurons)
      self.fc2 = nn.Linear(self.neurons,self.dimTimes-1)
      self.training_size = training_size
      self.dt = dt
      self.I0 = I0
      self.gamma = gamma
      self.I = torch.from_numpy(self.I0*np.ones((self.training_size,self.dimTimes)))
      self.tol = 0.0001#1e-5
      self.nmax = 100#1e2
      print('Number of neurons per layer', self.neurons)

    def forward(self, x):
      x1 = self.fc0(x).clone()
      x2 = F.relu(x1, inplace = False).clone()
      x3 = self.fc1(x2).clone()
      x4 = F.relu(x3, inplace = False).clone()
      x5 = self.fc2(x4).clone()
      output = x5.clone()
      self.I = torch.from_numpy(self.I0[0] * np.ones((self.training_size, self.dimTimes))).squeeze()

      for k in range(1,self.dimTimes):
          self.I[:,k] = self.I[:,k-1].clone() + self.dt * (output[:,k-1].clone() * self.I[:, k-1].clone() * (1 - self.I[:,k-1].clone()) - self.gamma * self.I[:,k-1].clone())
      return self.I.type(torch.double)

# Function modelling the fictious dependency of the transmission rate on the parameters
# For instance: temperature, variant prevelances, variant infctiousness, NPIs, percentage of vaccinations

def beta_fun_dep(t, params, training_size):
    NPIs = params
    aux = 0.5* NPIs
    return aux

#SOLVER SIS
def solution_SIS_vec(I0, fun, dt, gamma):

  I = I0 * np.ones(int(1/dt))
  for i in range(1, int(1/dt)):
    I[i] = I[i-1] + dt * (fun[i-1] * (1 - I[i-1]) * I[i-1] - gamma * I[i-1])

  return I

# Converter for NPIs
def convert(a):
    l = list()
    for i in range(len(a)):
        if a[i] == 1:
            l.append('White')
        elif a[i] == 4:
            l.append('Red')
        elif a[i] == 3:
            l.append('Orange')
        elif a[i] == 2:
            l.append('Yellow')
        elif a[i] == 5:
            l.append('Black')
        else:
            raise Exception("Error in NPI colors.")
    return l

# Solver parameters
I0 = 0.12
dt = 1/100
gamma = 1/20
t_points_len = 100
time_range = np.linspace(0,1,100)

# Hyperparameters
training_size = 30
learning_rate = 1e-3
batch_size = training_size #complete batch
epochs =100#1000
loss_list = []

torch.autograd.set_detect_anomaly(True)

# Net initialization
NN = Net(I0*np.ones(t_points_len), training_size, dt, gamma)

# Optimizer
optimizer = torch.optim.Adam(NN.parameters(), lr=learning_rate)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min')

# Training input (Non-Pharmaceutical Interventions)
np.random.seed(1)
NPIs_vec = np.zeros((t_points_len, training_size))

for i in range(training_size):
    NPIs_vec[:,i] = np.clip(np.random.rand() * np.sin(4 * np.pi * time_range) + np.random.rand(), 0, 1)
    #if i % 5 ==0:
    #    plt.plot(NPIs_vec[:,i])
    #    plt.show()

# Converting NPIs into piecewise constant functions
NPIs_vec[NPIs_vec <= 0.1] = 0.1
NPIs_vec[(NPIs_vec>0.1)*(NPIs_vec<=0.3)] = 0.3
NPIs_vec[(NPIs_vec>0.3)*(NPIs_vec<=0.6)] = 0.6
NPIs_vec[(NPIs_vec>0.6)*(NPIs_vec<=0.9)] = 0.9
NPIs_vec[(NPIs_vec>0.9)*(NPIs_vec<=1)] = 1

# Loss function
loss_fn = nn.MSELoss()

# Training set
y_train = np.zeros((t_points_len, training_size))
params = NPIs_vec
betas = beta_fun_dep(time_range, params, training_size)
X_train_list = list()

for i in range(training_size):
    y_train[:,i] = solution_SIS_vec(I0,betas[:,i],dt,gamma)
    X_train_list.append(NPIs_vec.T[i])

X_train = np.array(X_train_list).astype(np.float32)

from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset

y_train = (y_train.T).astype(np.float32)
train_ds = TensorDataset(torch.Tensor(X_train), torch.Tensor(y_train).type(torch.double))
train_dataloader =DataLoader(train_ds, batch_size = batch_size)

from re import I

# Train loop definition
def train_loop(dataloader, model, loss_fn, optimizer,scheduler):
    size = len(dataloader.dataset)
    loss_list = []
    for batch, (X, y) in enumerate(dataloader):

        # Compute prediction and loss
        pred = model(X)
        loss = loss_fn(pred, y)

        # Backpropagation
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch % 100 == 0:

            loss, current = loss.item(), batch * len(X)
            loss_list.append(loss)#torch.Tensor.detach(loss).numpy())
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")
    return loss_list[-1]

for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    l = train_loop(train_dataloader, NN, loss_fn, optimizer,scheduler)
    loss_list.append(l)
    scheduler.step(t)
print("Done!")

with open(folder + "loss.txt", "w") as output:
    output.write(str(loss_list))

for batch, (X, y) in enumerate(train_dataloader):

    pred = NN(X)
    #Plot
    for i in range(batch_size):
    # Compute prediction and loss
        plt.plot(pred[i].detach().numpy())
        plt.plot(y[i].detach().numpy(), '--')
        plt.savefig(folder + 'train_'+str(i)+'.png')
        plt.close()
        #plt.show()

torch.save(NN.state_dict(), folder+'NNstateTest.pth')

#model_scripted = torch.jit.script(NN) # Export to TorchScript
#model_scripted.save(folder+'model_scripted_Test'+str(k)+'.pt')


import cv2
img=cv2.imread('loose.jpg')
print(img)
cv2.imshow('loose',img)
k=cv2.waitKey(0)&0xFF
if k==27:
    cv2.destroyAllWindows()
elif k==ord('s'):
    cv2.imwrite('loose_copy.jpg',img)
    cv2.destroyAllWindows()


# The iCal feed URL for the events that should be synced to the Google Calendar.
# Note that the syncing is one-way only.
ICAL_FEED = '<ICAL FEED URL>'

# the ID of the calendar to use for iCal events, should be of the form
# 'ID@group.calendar.google.com', check the calendar settings page to find it.
# (can also be 'primary' to use the default calendar)
CALENDAR_ID = '<GOOGLE CALENDAR ID>'

# must use the OAuth scope that allows write access
SCOPES = 'https://www.googleapis.com/auth/calendar'

# API secret stored in this file
CLIENT_SECRET_FILE = 'ical_to_gcal_sync_client_secret.json'

# Location to store API credentials
CREDENTIAL_PATH = 'ical_to_gcal_sync.json'

# Application name for the Google Calendar API
APPLICATION_NAME = 'ical_to_gcal_sync'

# File to use for logging output
LOGFILE = 'ical_to_gcal_sync_log.txt'

# Time to pause between successive API calls that may trigger rate-limiting protection
API_SLEEP_TIME = 0.05


from src.pipeline import Pipeline
from src.logger import Logger

def main():
    logger = Logger().get_logger()

    try:
        logger.info('starting pipeline')

        pipeline = Pipeline(logger=logger, csv_path='app/test/SegaGames.csv')
        pipeline.run()

        logger.info('finishing pipeline')
    except Exception as e:
        logger.error(f'An error ocurred: {e}')

main()


# 推荐使用else的情况 即没有任何异常的情况下执行的语句
# 无论在任何情况下都会执行的清理行为

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else:
        print("result is", result)
    finally:
        print("executing finally clause")

def divide_2(x, y):
    try:
        result = x / y
        print("result is", result)
    except ZeroDivisionError:
        print("division by zero!")
    finally:
        print("executing finally clause")

divide_2(2, 1)

divide_2(2, 0)

# 关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法:
with open("test2.txt") as f:
    for line in f:
        print(line, end="")

# 当执行完毕后，文件会保持打开状态，并没有被关闭
for line in open("test2.txt"):
    print(line, end="")

print("\n");
# 定义函数
# 处理带有参数的异常的方法如下

def temp_convert(var):
    try:
        return int(var)
    except (ValueError) as Argument:
        print("参数没有包含数字\n", Argument)

# 调用函数
temp_convert("xyz");


"""
Простой пример созданий пустого окна с использование pygame.
В дальнейшем этот пример будет развиваться для использваония OpenGL

Необходимо поставить модули pyopengl pygame
Для wibdwos можно брать отсюда http://www.lfd.uci.edu/~gohlke/pythonlibs/
"""

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

class Controller(object):
    """Основной класс для создания окна и запуска цикла рендеринга"""

    def __init__(self, w=800, h=600, name="Lab", frame_rate=60):
        """Конструктор нашего класса

        Принимает параметры размера окна, название окна и ограничение количества кадров всекунду
        """
        self.w = w
        self.h = h
        self.name = name
        self.frame_rate = frame_rate
        self.screen = None  # ссылка на созданное коно
        self.clock = None  # вспомогательный объект для контроля FPS

    def init(self):
        """Создание окна, инициализация"""
        self.screen = pygame.display.set_mode((self.w, self.h), HWSURFACE | OPENGL | DOUBLEBUF | RESIZABLE)
        pygame.display.set_caption(self.name)
        glEnable(GL_DEPTH_TEST)
        self.clock = pygame.time.Clock()

    def loop_step(self):
        """Обратока цикла рендеринга pygame"""
        # задаем максимальное количество кадров в секунду
        self.clock.tick(self.frame_rate)
        # считываем все произошедшие событие
        for event in pygame.event.get():
            # обробатываем выход из приложения
            if event.type == QUIT:
                self.quit()
                return
            if event.type == KEYUP and event.key == K_ESCAPE:
                self.quit()
                return
            # обрабатываем изменение размера окна
            if event.type == VIDEORESIZE:
                self.reshape(*event.size)
            # обработка события
            self.event(event)
        # что-то рисуем
        self.render()
        # показываем в залоговке окна FPS
        self.fps()
        # смена кадров, т.к. мы используем DOUBLEBUF ражим
        pygame.display.flip()

    def quit(self):
        """Выход из приложения, закрытие окна"""
        pygame.quit()
        quit()

    def loop(self):
        """Запускает бесконечный цикл рендеринга"""
        while True:
            self.loop_step()

    def reshape(self, width, height):
        """Обрабатываем изменение размера окна"""
        self.w = width
        self.h = height

    def event(self, e):
        """Обрабатываем события"""
        pass

    def fps(self):
        """Рисуем текущий FPS"""
        pygame.display.set_caption("%s FPS: %s" % (self.name, self.clock.get_fps()))

    def run(self):
        """Запуск приложения"""
        self.init()
        self.loop()

    def render(self):
        """Рисуем"""
        pass

if __name__ == '__main__':
    main = Controller()
    main.run()


from math import copysign
import pygame as pg

from data.config import UPGRADE_MENU_ANIMATION_TIME
from data.paths import UPGRADE_CAPTION_RUS, UPGRADE_CAPTION_ENG

class UpgradeCaption:
    def __init__(self):
        self.x = 48
        self.y = -128
        self.Y0 = -128
        self.Y1 = 16
        self.vel_y = (self.Y1 - self.Y0) / UPGRADE_MENU_ANIMATION_TIME
        self.vel_y_sign = copysign(1, self.vel_y)
        self.caption = None

    def set_language(self, language):
        img = UPGRADE_CAPTION_ENG if language == "English" else UPGRADE_CAPTION_RUS
        self.caption = pg.image.load(img).convert_alpha()

    def reset_velocity(self):
        self.vel_y = abs(self.vel_y)

    def update_pos(self, dt):
        self.y += self.vel_y * dt
        if self.vel_y_sign * self.y > self.vel_y_sign * self.Y1:
            self.y = self.Y1
        elif self.vel_y_sign * self.y < self.vel_y_sign * self.Y0:
            self.y = self.Y0

    def draw(self, surface):
        surface.blit(self.caption, (self.x, self.y))


from apps.inventario.models import *
from django import forms

from django.forms import widgets
from django.forms import fields, CheckboxInput

class productoForm(forms.ModelForm):
	fkcate = forms.ModelChoiceField(queryset=CategoriaIncidencia.objects.all())
	comentario = forms.CharField(required=False, max_length=150)
	class Meta:
		model=Producto
		fields=[
			'nombre',
			'descripcion',
			'precioventa',
			'preciocompra',
			'existencia',
			'promocion',
			'fkcategoria',
			'fkproveedor',
			]
		labels={

			'nombre':'Nombre',
			'descripcion':'Descripcion:',
			'precioventa':'Precio de Venta:',
			'preciocompra':'Precio de Compra:',
			'existencia':'Existencias:',
			'promocion':'Promocion:',
			'fkcategoria':'Categoria',
			'fkproveedor':'Proveedor',
		}
		widgets={
			'nombre': forms.TextInput(),
			'descripcion': forms.TextInput(),
			'precioventa': forms.NumberInput(),
			'preciocompra': forms.NumberInput(),
			'existencia': forms.TextInput(),
			'promocion': forms.CheckboxInput(),
			'fkproveedor': forms.Select(),
			'fkcategoria': forms.Select(),
		}

class elimiarForm(forms.Form):
	confirmar = forms.CheckboxInput()


# Iterators - Exercise 4 🐍

# iterate each elements of `list1`,`tuple1`,`set1` and print them out

# for the `dict1` iterate all elements but only print the ones who are living on land
# in the form of `x lives in y`

list1 = ["lion", "monkey", "dog","fish"]

for x in list1:
  print(x)

tuple1 = ("lion", "monkey", "dog","fish")

for a in tuple1:
  print(a)

set1 = {"lion", "monkey", "dog","fish"}

for b in set1:
  print(b)

dict1 = {"lion":"land", "monkey":"land", "dog":"land","fish":"water"}

for key, value in dict1.items():
    if str(value).startswith("la"):
        print(key)


#
# Tests for the 'osbuild.util.fscache' module.
#

# pylint: disable=protected-access

import contextlib
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import time

import pytest

from osbuild.util import fscache

@pytest.fixture(name="tmpdir")
def tmpdir_fixture():
    with tempfile.TemporaryDirectory(dir="/var/tmp") as tmp:
        yield tmp

def sleep_for_fs():
    """Sleep a tiny amount of time for atime/mtime updates to show up in fs"""
    time.sleep(0.05)

def has_precise_fs_timestamps():
    with tempfile.TemporaryDirectory(dir="/var/tmp") as tmpdir:
        stamp_path = pathlib.Path(tmpdir) / "stamp"
        stamp_path.write_bytes(b"m1")
        mtime1 = stamp_path.stat().st_mtime
        sleep_for_fs()
        stamp_path.write_bytes(b"m2")
        mtime2 = stamp_path.stat().st_mtime
        return mtime2 > mtime1

def test_calculate_space(tmpdir):
    #
    # Test the `_calculate_space()` helper and verify it only includes file
    # content in its calculation.
    #
    def du(path_target):
        env = os.environ.copy()
        env["POSIXLY_CORRECT"] = "1"
        output = subprocess.check_output(["du", "-s", path_target], env=env, encoding="utf8")
        return int(output.split()[0].strip())*512

    test_dir = os.path.join(tmpdir, "dir")
    os.mkdir(test_dir)
    assert fscache.FsCache._calculate_space(test_dir) == du(test_dir)

    with open(os.path.join(tmpdir, "dir", "file"), "x", encoding="utf8") as f:
        pass
    assert fscache.FsCache._calculate_space(test_dir) == du(test_dir)

    with open(os.path.join(tmpdir, "dir", "file"), "w", encoding="utf8") as f:
        f.write("foobar")
    assert fscache.FsCache._calculate_space(test_dir) == du(test_dir)

    os.makedirs(os.path.join(test_dir, "dir"))
    assert fscache.FsCache._calculate_space(test_dir) == du(test_dir)

    with open(os.path.join(test_dir, "sparse-file"), "w") as f:
        f.truncate(10*1024*1024)
        f.write("I'm not an empty file")
    assert fscache.FsCache._calculate_space(test_dir) == du(test_dir)

def test_pathlike(tmpdir):
    #
    # Verify behavior of `__fspath__()`.
    #

    class Wrapper:
        def __init__(self, path: str):
            self._path = path

        def __fspath__(self) -> str:
            return self._path

    # Test with a plain string as argument
    dir_str: str = os.fspath(tmpdir)
    cache1 = fscache.FsCache("osbuild-test-appid", dir_str)
    assert os.fspath(cache1) == tmpdir
    assert os.path.join(cache1, "foobar") == os.path.join(tmpdir, "foobar")

    # Test with a wrapper-type as argument
    dir_pathlike: Wrapper = Wrapper(os.fspath(tmpdir))
    cache2 = fscache.FsCache("osbuild-test-appid", dir_pathlike)
    assert os.fspath(cache2) == tmpdir
    assert os.path.join(cache2, "foobar") == os.path.join(tmpdir, "foobar")

def test_path(tmpdir):
    #
    # Verify behavior of `_path()`.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)
    with cache:
        assert cache._path() == cache._path_cache
        assert cache._path("dir") == os.path.join(cache._path_cache, "dir")
        assert cache._path("dir", "file") == os.path.join(cache._path_cache, "dir", "file")

def test_atomic_open(tmpdir):
    #
    # Verify the `_atomic_open()` helper correctly opens existing files and
    # takes a lock.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)
    with cache:
        # Must never create files.
        with pytest.raises(OSError):
            with cache._atomic_open("file", write=False, wait=False) as f:
                pass

        # Create the file with "foo" as content.
        with open(os.path.join(tmpdir, "file"), "x", encoding="utf8") as f:
            f.write("foo")

        # Open and acquire a write-lock. Then verify a read-lock fails.
        with cache._atomic_open("file", write=True, wait=False):
            with pytest.raises(BlockingIOError):
                with cache._atomic_open("file", write=False, wait=False):
                    pass

def test_atomic_file(tmpdir):
    #
    # Verify behavior of `_atomic_file()` as replacement for `O_TMPFILE`.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)
    with cache:
        rpath_store = cache._dirname_objects
        path_store = os.path.join(cache._path_cache, rpath_store)

        # Initially the store is empty.
        assert len(list(os.scandir(path_store))) == 0

        # Create a file and verify there is almost exactly 1 file in the store.
        with cache._atomic_file(os.path.join(rpath_store, "file"), rpath_store) as f:
            assert len(list(os.scandir(path_store))) == 1
            f.write("foo")
        assert len(list(os.scandir(path_store))) == 1

        # Verify `ignore_exist=False` works as expected.
        with pytest.raises(OSError):
            with cache._atomic_file(os.path.join(rpath_store, "file"), rpath_store) as f:
                # Temporarily, there will be 2 files.
                assert len(list(os.scandir(path_store))) == 2
                f.write("bar")
        assert len(list(os.scandir(path_store))) == 1
        with open(os.path.join(path_store, "file"), "r", encoding="utf8") as f:
            assert f.read() == "foo"

        # Verify `ignore_exist=True` works as expected.
        with cache._atomic_file(os.path.join(rpath_store, "file"), rpath_store, ignore_exist=True) as f:
            f.write("bar")
        assert len(list(os.scandir(path_store))) == 1
        with open(os.path.join(path_store, "file"), "r", encoding="utf8") as f:
            assert f.read() == "foo"

        # Verify `replace=True`.
        with cache._atomic_file(os.path.join(rpath_store, "file"), rpath_store, replace=True) as f:
            f.write("bar")
        assert len(list(os.scandir(path_store))) == 1
        with open(os.path.join(path_store, "file"), "r", encoding="utf8") as f:
            assert f.read() == "bar"

        # Combining `replace` and `ignore_exist` is not allowed.
        with pytest.raises(AssertionError):
            with cache._atomic_file(
                    os.path.join(rpath_store, "file"),
                    rpath_store,
                    replace=True,
                    ignore_exist=True,
            ) as f:
                pass

def test_atomic_dir(tmpdir):
    #
    # Verify the `_atomic_dir()` helper correctly creates anonymous files
    # and yields the name and lock-file.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)
    with cache:
        # The relative-path must exist, so expect an error if it does not.
        with pytest.raises(OSError):
            cache._atomic_dir("dir")

        assert len(list(os.scandir(os.path.join(tmpdir, cache._dirname_objects)))) == 0

        (name, lockfd) = cache._atomic_dir(cache._dirname_objects)
        assert name.startswith("uuid-")
        assert len(name) == 37
        assert lockfd >= 0
        os.close(lockfd)

        assert len(list(os.scandir(os.path.join(tmpdir, cache._dirname_objects)))) == 1

def test_scaffolding(tmpdir):
    #
    # Verify that the cache creates scaffolding when entered.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)

    assert len(list(os.scandir(tmpdir))) == 0

    with cache:
        pass

    assert len(list(os.scandir(tmpdir))) == 6
    assert len(list(os.scandir(os.path.join(tmpdir, cache._dirname_objects)))) == 0
    assert len(list(os.scandir(os.path.join(tmpdir, cache._dirname_stage)))) == 0

    with open(os.path.join(tmpdir, cache._filename_cache_tag), "r", encoding="utf8") as f:
        assert len(f.read()) > 0
    with open(os.path.join(tmpdir, cache._filename_cache_info), "r", encoding="utf8") as f:
        assert json.load(f) == {"version": 1}
    with open(os.path.join(tmpdir, cache._filename_cache_lock), "r", encoding="utf8") as f:
        assert f.read() == ""
    with open(os.path.join(tmpdir, cache._filename_cache_size), "r", encoding="utf8") as f:
        assert f.read() == "0"

def test_cachedir_tag(tmpdir):
    #
    # Verify compatibility to the cachedir-tag specification.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)

    with cache:
        pass

    with open(os.path.join(tmpdir, "CACHEDIR.TAG"), "r", encoding="utf8") as f:
        assert f.read(43) == "Signature: 8a477f597d28d172789f06886806bc55"

def test_cache_info(tmpdir):
    #
    # Verify that the cache reads and augments cache information. Also verify
    # the default values.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)

    with cache:
        assert cache._info == fscache.FsCacheInfo(version=1)
        assert cache.info == cache._info

        assert cache.info.maximum_size is None
        assert cache.info.creation_boot_id is None
        cache.info = fscache.FsCacheInfo(maximum_size=1024)
        assert cache.info.maximum_size == 1024
        assert cache.info.creation_boot_id is None
        cache.info = fscache.FsCacheInfo(creation_boot_id="0" * 32)
        assert cache.info.maximum_size == 1024
        assert cache.info.creation_boot_id == "0" * 32
        cache.info = fscache.FsCacheInfo(maximum_size=2048, creation_boot_id="1" * 32)
        assert cache.info.maximum_size == 2048
        assert cache.info.creation_boot_id == "1" * 32

    assert not fscache.FsCacheInfo().to_json()
    assert fscache.FsCacheInfo(creation_boot_id="0" * 32).to_json() == {
        "creation-boot-id": "0" * 32,
    }
    assert fscache.FsCacheInfo(creation_boot_id="0" * 32, maximum_size=1024).to_json() == {
        "creation-boot-id": "0" * 32,
        "maximum-size": 1024,
    }

    assert fscache.FsCacheInfo.from_json({}) == fscache.FsCacheInfo()
    assert fscache.FsCacheInfo.from_json(None) == fscache.FsCacheInfo()
    assert fscache.FsCacheInfo.from_json("foobar") == fscache.FsCacheInfo()
    assert fscache.FsCacheInfo.from_json({
        "creation-boot-id": "0" * 32,
    }) == fscache.FsCacheInfo(creation_boot_id="0" * 32)
    assert fscache.FsCacheInfo.from_json({
        "creation-boot-id": "0" * 32,
        "maximum-size": 1024,
    }) == fscache.FsCacheInfo(creation_boot_id="0" * 32, maximum_size=1024)
    assert fscache.FsCacheInfo.from_json({
        "creation-boot-id": "0" * 32,
        "maximum-size": 1024,
    }) == fscache.FsCacheInfo(creation_boot_id="0" * 32, maximum_size=1024)
    assert fscache.FsCacheInfo.from_json({
        "creation-boot-id": "0" * 32,
        "unknown0": "foobar",
        "unknown1": ["foo", "bar"],
    }) == fscache.FsCacheInfo(creation_boot_id="0" * 32)

def test_store(tmpdir):
    #
    # API tests for the `store()` method.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)

    with pytest.raises(AssertionError):
        with cache.store("foobar"):
            pass

    with cache:
        with pytest.raises(ValueError):
            with cache.store(""):
                pass

def test_load(tmpdir):
    #
    # API tests for the `load()` method.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)

    with pytest.raises(AssertionError):
        with cache.load("foobar"):
            pass

    with cache:
        with pytest.raises(ValueError):
            with cache.load(""):
                pass

def test_store_tree(tmpdir):
    #
    # API tests for the `store_tree()` method.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)

    with pytest.raises(AssertionError):
        cache.store_tree("foobar", "invalid/dir")

    with cache:
        cache.info = cache.info._replace(maximum_size=1024 * 1024 * 1024)

        with pytest.raises(ValueError):
            cache.store_tree("", "invalid/dir")
        with pytest.raises(RuntimeError):
            cache.store_tree("key", "invalid/dir")

        with tempfile.TemporaryDirectory(dir="/var/tmp") as tmp:
            with open(os.path.join(tmp, "outside"), "x", encoding="utf8") as f:
                f.write("foo")
            os.mkdir(os.path.join(tmp, "tree"))
            with open(os.path.join(tmp, "tree", "inside"), "x", encoding="utf8") as f:
                f.write("bar")
            with open(os.path.join(tmp, "tree", "more-inside"), "x", encoding="utf8") as f:
                f.write("foobar")

            cache.store_tree("key", os.path.join(tmp, "tree"))

            with cache.load("key") as rpath:
                assert len(list(os.scandir(os.path.join(cache, rpath)))) == 1
                assert len(list(os.scandir(os.path.join(cache, rpath, "tree")))) == 2
                with open(os.path.join(cache, rpath, "tree", "inside"), "r", encoding="utf8") as f:
                    assert f.read() == "bar"
                with open(os.path.join(cache, rpath, "tree", "more-inside"), "r", encoding="utf8") as f:
                    assert f.read() == "foobar"

def test_basic(tmpdir):
    #
    # A basic cache store+load test.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)
    with cache:
        cache.info = cache.info._replace(maximum_size=1024*1024)

        with cache.stage() as rpath:
            with open(os.path.join(tmpdir, rpath, "bar"), "x", encoding="utf8") as f:
                f.write("foobar")

        with pytest.raises(fscache.FsCache.MissError):
            with cache.load("foo") as rpath:
                pass

        with cache.store("foo") as rpath:
            with open(os.path.join(tmpdir, rpath, "bar"), "x", encoding="utf8") as f:
                f.write("foobar")

        with cache.load("foo") as rpath:
            with open(os.path.join(tmpdir, rpath, "bar"), "r", encoding="utf8") as f:
                assert f.read() == "foobar"

def test_size_discard(tmpdir):
    #
    # Verify that a cache with no maximum-size configured can never store any
    # entries, but discards them immediately.
    #

    cache = fscache.FsCache("osbuild-test-appid", tmpdir)
    with cache:
        with cache.store("foo") as rpath:
            with open(os.path.join(tmpdir, rpath, "bar"), "x", encoding="utf8") as f:
                f.write("foobar")

        with pytest.raises(fscache.FsCache.MissError):
            with cache.load("foo") as rpath:
                pass

def test_cache_last_used_noent(tmpdir):
    cache = fscache.FsCache("osbuild-test-appid", tmpdir)
    with pytest.raises(fscache.FsCache.MissError):
        cache._last_used("non-existant-entry")

@pytest.mark.skipif(not has_precise_fs_timestamps(), reason="need precise fs timestamps")
def test_cache_load_updates_last_used(tmpdir):
    cache = fscache.FsCache("osbuild-test-appid", tmpdir)
    with cache:
        cache.info = cache.info._replace(maximum_size=1024*1024)
        with cache.store("foo") as rpath:
            pass
        with cache.load("foo") as rpath:
            pass
        load_time1 = cache._last_used("foo")
        # would be nice to have a helper for this in cache
        obj_lock_path = os.path.join(
            cache._dirname_objects, "foo", cache._filename_object_lock)
        mtime1 = os.stat(cache._path(obj_lock_path)).st_mtime
        assert load_time1 > 0
        sleep_for_fs()
        with cache.load("foo") as rpath:
            pass
        # load time is updated
        load_time2 = cache._last_used("foo")
        assert load_time2 > load_time1
        # mtime is unchanged
        mtime2 = os.stat(cache._path(obj_lock_path)).st_mtime
        assert mtime1 == mtime2

@pytest.mark.skipif(os.getuid() != 0, reason="needs root")
def test_cache_load_updates_last_used_on_noatime(tmp_path):
    mnt_path = tmp_path / "mnt"
    mnt_path.mkdir()
    with contextlib.ExitStack() as cm:
        subprocess.check_call(
            ["mount", "-t", "tmpfs", "-o", "noatime", "none", os.fspath(mnt_path)],
            stdout=sys.stdout,
            stderr=sys.stderr,
        )
        cm.callback(subprocess.check_call, ["umount", os.fspath(mnt_path)], stdout=sys.stdout, stderr=sys.stderr)
        test_cache_load_updates_last_used(mnt_path)

def test_cache_full_behavior(tmp_path):
    cache = fscache.FsCache("osbuild-cache-evict", tmp_path)
    with cache:
        # use big sizes to mask the effect of dirs using 4k of space too
        cache.info = cache.info._replace(maximum_size=192 * 1024)
        # add one object to the store, we are below the limit
        with cache.store("o1") as rpath:
            rpath_f1 = os.path.join(tmp_path, rpath, "f1")
            with open(rpath_f1, "wb") as fp:
                fp.write(b'a'*64*1024)
        assert cache._calculate_space(tmp_path) > 64 * 1024
        assert cache._calculate_space(tmp_path) < 128 * 1024
        with cache.load("o1") as o:
            assert o != ""
        # and one more
        with cache.store("o2") as rpath:
            rpath_f2 = os.path.join(tmp_path, rpath, "f2")
            with open(rpath_f2, "wb") as fp:
                fp.write(b'b'*64*1024)
        assert cache._calculate_space(tmp_path) > 128 * 1024
        assert cache._calculate_space(tmp_path) < 192 * 1024
        with cache.load("o2") as o:
            assert o != ""
        # adding a third one will (silently) fail because the cache is full
        with cache.store("o3") as rpath:
            rpath_f3 = os.path.join(tmp_path, rpath, "f3")
            with open(rpath_f3, "wb") as fp:
                fp.write(b'b'*128*1024)
        assert cache._calculate_space(tmp_path) > 128 * 1024
        assert cache._calculate_space(tmp_path) < 192 * 1024
        with pytest.raises(fscache.FsCache.MissError):
            with cache.load("o3") as o:
                pass


import pandas as pd
import jieba
# jieba.enable_paddle()# 启动paddle模式。 0.40版之后开始支持，早期版本不支持

# 创建停用词列表
def stopwordslist():
	stopwords = [line.strip('\n') for line in open('stopwords.txt',encoding='UTF-8').readlines()]
	return stopwords

# 分词+去停用词
def textProcess(text,stopwords):
	split_text = list(jieba.cut(text.strip(),use_paddle=True))
	# print(split_text)
	# 创建一个停用词列表
	# stopwords = stopwordslist()
	# 输出结果为outstr
	outstr = ''
	# 去停用词
	for word in split_text:
		word=word.strip()
		if word not in stopwords and len(word) < 10:
			outstr += word
			outstr += " "
	# print(outstr)
	return outstr

def generateoneline(content, comments, label, stopwords):
	content = textProcess(content, stopwords)
	oneline = content+"######"
	for idx in range(0,2):
		comment = textProcess(comments[idx], stopwords)
		oneline = oneline+comment+"\t"
	comment = textProcess(comments[2], stopwords)
	oneline = oneline+comment+"######"+label+"\n"
	return oneline

if __name__ == '__main__':
	# rmrdata_pt="covid-rumor/rumor.csv"
	rmrdata_pt="covid-rumor/rumor.xlsx"
	# nonrmrdata_pt="covid-rumor/nonrumor.csv"
	# nonrmrdata_pt="covid-rumor/nonrumor-random.csv"
	covid_pt="covid.txt"
	keywords=["肺炎","新冠","病毒","武汉","湖北","封城","确诊","疑似","疫情","钟南山","防控","口罩","感染","疫","肺","染"]

	rmrdf = pd.read_excel(rmrdata_pt)
	# rmrdf = pd.read_csv(rmrdata_pt)
	# nonrmrdf = pd.read_csv(nonrmrdata_pt)

	stopwords = stopwordslist()
	# print(rmrdf)

	with open(covid_pt, mode="w", encoding="utf-8") as covid_file:
		count = 0
		lineidxs = rmrdf.index.values
		# print(lineidxs)
		for idx in lineidxs:
			try:
				# 微博正文
				content = rmrdf.iloc[idx,2].split(":")[1].split("                                  ")[0].split("                      ")[0].split("              ")[0].split("             ")[0]
				# print(content)
				# 关键词筛选
				filter_bool = False
				for keyword in keywords:
					filter_bool = filter_bool or (keyword in content)
				if filter_bool:
					# 获取评论
					comments = rmrdf.iloc[idx,9].split(";")
					oneline = generateoneline(content, comments, "rumor", stopwords)
					# print(oneline)
					covid_file.write(oneline)

					count += 1
			except:
				print("===skip===")
		print("The number of Filtered COVID-19 Rumors ："+str(count))