# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 09:10:52 2019

@author: Acer
"""
#%%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

data=pd.read_csv(r"D:\projects\zomato.csv")

data.describe()
data.columns

# Transforming rate column

data['rate_new'] = data['rate'].astype(str)
data['rate_new'] = data['rate_new'].apply(lambda x: x.split('/')[0])# Dealing with instanced with 'NEW'
data['rate_new'] = data['rate_new'].apply(lambda x: x.replace('NEW', str(np.nan)))
data['rate_new'] = data['rate_new'].apply(lambda x: x.replace('-', str(np.nan)))
# Changing data type
data['rate_new'] = data['rate_new'].astype(float)

data.drop(['rate'], axis=1, inplace=True)
print(f'{type(data["rate_new"][0])}')

data['approx_cost(for two people)'] = data['approx_cost(for two people)'].str.replace(',','').apply(lambda x:float(x))

#%%
#Dropping unnecessary data
data.drop(['url', 'address', 'dish_liked', 'phone', 'reviews_list', 'menu_item','location'], axis=1, inplace=True)

# Looking for null data
data.isnull().sum()
data = data.dropna(subset=['rate_new', 'approx_cost(for two people)'])
data = data.fillna('Not defined')
data.isnull().sum()

data.reset_index(drop=True)
data.describe()
data
#===========================EDA===========================
#%%
#1.Restaurant Rate Distribution
data['rate_new'].describe()

sns.set(style='darkgrid',palette='muted',color_codes=True)
fig, ax=plt.subplots(figsize=(12,5))
sns.distplot(data['rate_new'],bins=30,color='blue')
ax.set_title('Restaurant Rate Distribution',size=13)
ax.set_xlabel('Rate')
plt.show()
#%%
#2. Approx. cost of 2 people

data['approx_cost(for two people)']
sns.set(style='darkgrid',palette='muted',color_codes=True)
fig, ax=plt.subplots(figsize=(12,5))
sns.distplot(data['approx_cost(for two people)'],bins=10,color='blue')
ax.set_title('Approx cost for two people')
ax.set_xlabel('cost')
plt.show()
#%%
#3.Finding Outliers
#Online_Order
fig, ax=plt.subplots(figsize=(12,7))
sns.boxplot(x='online_order',y='rate_new',data=data)

#BookTable
fig, ax=plt.subplots(figsize=(12,7))
sns.boxplot(x='book_table',y='rate_new',data=data)

#%%
#4.Correlation between rating and cost
fig, ax = plt.subplots(figsize=(10 , 10))
sns.scatterplot(x='rate_new', y='approx_cost(for two people)', data=data, ax=ax)
ax.set_title('Correlation Between Rate and Approx Cost', size=14)
plt.show()

#%%
#5.Correlation between rating and Online Order or Booking Tables
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(10, 10))
sns.scatterplot(x='rate_new', y='approx_cost(for two people)', hue='online_order',
                data=data, ax=axs[0], palette=['navy', 'crimson'])
sns.scatterplot(x='rate_new', y='approx_cost(for two people)', hue='book_table',
                data=data, ax=axs[1], palette=['navy', 'crimson'])
axs[0].set_title('Cost and Rate Distribution by Online Order', size=14)
axs[1].set_title('Cost and Rate Distribution by Book Table', size=14)
plt.show()
#%%
data.groupby(by='online_order').mean()
#%%
data.groupby(by='book_table').mean()
#%%
#6.Top Rated Restaurant
grouped_rate = data.groupby(by='name', as_index=False).mean()
top_rating = grouped_rate.sort_values(by='rate_new', ascending=False).iloc[:10, np.r_[0, -1]]
top_rating

top_rating.iloc[1, 0] = 'Santa Spa Cuisine'

# Plotting
fig, ax = plt.subplots(figsize=(13, 5))
ax = sns.barplot(y='name', x='rate_new', data=top_rating, palette='Blues_d')
ax.set_xlim([4.7, 4.95])
ax.set_xlabel('Mean Rate')
ax.set_ylabel('')
for p in ax.patches:
    width = p.get_width()
    ax.text(width+0.007, p.get_y() + p.get_height() / 2. + 0.2, '{:1.2f}'.format(width),
            ha="center", color='grey')

ax.set_title('Top 10 Restaurants in Bengaluru by Rate', size=14)
plt.show()
#%%
#Label Encoding

from sklearn.preprocessing import LabelEncoder

lb_en=LabelEncoder()
data['online_order']=lb_en.fit_transform(data['online_order'])
data['online_order'].unique()
data['online_order']
#%%
data['book_table']=lb_en.fit_transform(data['book_table'])
data['book_table'].unique()
data['book_table']
#%%
data['listed_in(type)']=lb_en.fit_transform(data['listed_in(type)'])
data['listed_in(type)']
#%%
data['listed_in(city)'].unique()
data['listed_in(city)']=lb_en.fit_transform(data['listed_in(city)'])
data['listed_in(city)']
#%%
data=pd.read_excel(r"D:\projects\zomato2.xlsx")
data['rest_type'].unique()
data['rest_type']=lb_en.fit_transform(data['rest_type'])
data['rest_type'].unique()
data['rest_type']

data.drop(['cuisines'], axis=1, inplace=True)
data.columns
#data['rate_new'].unique()
data['listed_in(type)'].unique()
#%%
corr = data.corr(method='kendall')
plt.figure(figsize=(15,8))
sns.heatmap(corr, annot=True)

#%%
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score, StratifiedKFold

data.columns
x=data.iloc[:,1:8]
y=data['rate_new']

sc=StandardScaler()
sc.fit(x)
x=sc.transform(x)

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.10,random_state=20)
#kfold=StratifiedKFold(n_splits=10,random_state=48)
#%%
#LASSO
from sklearn.linear_model import Lasso
from sklearn.metrics import  mean_squared_error
from sklearn.metrics import r2_score
alpha=0.1
lasso=Lasso(alpha=alpha)
lasso.fit(x_train,y_train)
y_train_pred=lasso.predict(x_train)
y_test_pred=lasso.predict(x_test)
print(lasso.coef_)
print('MSE train: %.3f,test: %.3f' % (mean_squared_error(y_train,y_train_pred),mean_squared_error(y_test,y_test_pred)))
print('R^2 train: %.3f,test: %.3f' % (r2_score(y_train,y_train_pred),r2_score(y_test,y_test_pred)))

r2_score_lasso=r2_score(y_test,y_test_pred)
print(lasso)
print("r^2 on test data: %f" % r2_score_lasso)

predictors=data.columns.values[1:8]
coef=pd.Series(lasso.coef_,predictors).sort_values()
coef.plot(kind='bar', title='Modal Coefficients')
#%%
#RandomForest

from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_selection import SelectFromModel
sel = SelectFromModel(RandomForestRegressor(n_estimators = 100))
sel.fit(x_train, y_train)
sel.get_support()
selected_feat= x_train.columns[(sel.get_support())]
print(selected_feat)

#%%
from xgboost import XGBRegressor
from numpy import sort

model = XGBRegressor()
model.fit(x_train, y_train)
# make predictions for test data and evaluate
y_pred = model.predict(x_test)
predictions = [round(value) for value in y_pred]
r2 = r2_score(y_test,y_test_pred)
print("R2: %.2f%%" % (r2 * 100.0))
mse=mean_squared_error(y_test,y_test_pred)
print("MSE: %.2f%%" % (mse * 100.0))
# Fit model using each importance as a threshold
thresholds = sort(model.feature_importances_)
for thresh in thresholds:
	# select features using threshold
	selection = SelectFromModel(model, threshold=thresh, prefit=True)
	select_X_train = selection.transform(x_train)
	# train model
	selection_model = XGBRegressor()
	selection_model.fit(select_X_train, y_train)
	# eval model
	select_X_test = selection.transform(x_test)
	y_pred = selection_model.predict(select_X_test)
	predictions = [round(value) for value in y_pred]
	r2 = r2_score(y_test,y_test_pred)
    #mse=mean_squared_error(y_test,y_test_pred)
	print("Thresh=%.3f, n=%d, r2: %.2f%%" % (thresh, select_X_train.shape[1], r2*100.0))

#%%
#Model Building
#RANDOM FOREST
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression

RForest=RandomForestRegressor(n_estimators=5,random_state=329,min_samples_leaf=.0001)
RForest.fit(x_train,y_train)
y_predict=RForest.predict(x_test)
from sklearn.metrics import r2_score
print("Random forest:", r2_score(y_test,y_predict))
#results=cross_val_score(RForest,x_train,y_train,cv=kfold)
#print("CVS:",results)

#Linear Regression
lm=LinearRegression()
lm.fit(x_train,y_train)
y_pred=lm.predict(x_test)
from sklearn.metrics import r2_score
print("Linear Regression:",r2_score(y_test,y_pred))
#results=cross_val_score(lm,x_train,y_train,cv=kfold)
#print("CVS:",results)

#DecisionTree
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import export_graphviz
from os import  system

DTree=DecisionTreeRegressor(min_samples_leaf=.0001)
DTree.fit(x_train,y_train)
y_predict=DTree.predict(x_test)
from sklearn.metrics import r2_score
print("Decision Tree:",r2_score(y_test,y_predict))

#results=cross_val_score(DTree,x_train,y_train,cv=kfold)
#print("CVS:",results)

#SVM regressor
from sklearn.svm import SVR
regressor = SVR(kernel = 'rbf')
regressor.fit(x_train,y_train)
y_predict=regressor.predict(x_test)
from sklearn.metrics import r2_score
print("SVM regressor:", r2_score(y_test,y_predict))

#XGBoost Regressor
import xgboost

xgb = xgboost.XGBRegressor(n_estimators=500, learning_rate=0.5, gamma=0, subsample=0.75,colsample_bytree=1, max_depth=7)
xgb.fit(x_train,y_train)
predictions = xgb.predict(x_test)
print("XGB:",r2_score(y_test,predictions))

#KNN
from sklearn import neighbors
r2_val = []
for K in range(20):
    K = K+1
    model = neighbors.KNeighborsRegressor(n_neighbors = K)

    model.fit(x_train, y_train)  #fit the model
    pred=model.predict(x_test) #make prediction on test set
    r2 = r2_score(y_test,pred) #calculate rmse
    r2_val.append(r2) #store rmse values
    print('R2 for k= ' , K , 'is:', r2)

Zomato's Restaurant Rating Prediction.py


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        """
        어떤 순회인가는 V(부모노드)가 몇번째로 탐색되느냐
        preorder -> VLR
        inorder -> LVR
        """
        if inorder:
            index = inorder.index(preorder.pop(0))

            node = TreeNode(inorder[index])
            node.left = self.buildTree(preorder, inorder[0:index])
            node.right = self.buildTree(preorder, inorder[index+1:])

            return node


# coding: utf-8

from traitlets import Type, Instance, default
from .baseapp import NbGrader
from ..plugins import ExportPlugin, CsvExportPlugin
from ..api import Gradebook

aliases = {
    'log-level' : 'Application.log_level',
    'db': 'CourseDirectory.db_url',
    'to' : 'ExportPlugin.to',
    'exporter': 'ExportApp.plugin_class',
    'assignment' : 'ExportPlugin.assignment',
    'student': 'ExportPlugin.student',
    'course': 'CourseDirectory.course_id'
}
flags = {}

class ExportApp(NbGrader):

    name = u'nbgrader-export'
    description = u'Export information from the database to another format.'

    aliases = aliases
    flags = flags

    examples = """

        The default is to export to a file called "grades.csv", i.e.:

            nbgrader export

        You can customize the filename with the --to flag:

            nbgrader export --to mygrades.csv

        You can export the grades for a single (or limited set) of students
        or assignments with the --assignment and/or --student flag:

            nbgrader export --assignment [assignmentID]
                            --student [studentID1,studentID2]

        Where the studentIDs and assignmentIDs are a list of IDs and
        assignments. The assignments or studentIDs need to quoted if they
        contain not only numbers. The square brackets are obligatory.

        To change the export type, you will need a class that inherits from
        nbgrader.plugins.ExportPlugin. If your exporter is named
        `MyCustomExporter` and is saved in the file `myexporter.py`, then:

            nbgrader export --exporter=myexporter.MyCustomExporter

        """

    plugin_class = Type(
        CsvExportPlugin,
        klass=ExportPlugin,
        help="The plugin class for exporting the grades."
    ).tag(config=True)

    plugin_inst = Instance(ExportPlugin).tag(config=False)

    def init_plugin(self):
        self.log.info("Using exporter: %s", self.plugin_class.__name__)
        self.plugin_inst = self.plugin_class(parent=self)

    @default("classes")
    def _classes_default(self):
        classes = super(ExportApp, self)._classes_default()
        classes.append(ExportApp)
        classes.append(ExportPlugin)
        return classes

    def start(self):
        super(ExportApp, self).start()
        self.init_plugin()
        with Gradebook(self.coursedir.db_url, self.coursedir.course_id) as gb:
            self.plugin_inst.export(gb)


# http://codeforces.com/group/P8UZg7UOT5/contest/225111/problem/G

def SuperMarkets():

    markets, kilos = map(int, input().strip().split())
    min_price = None

    while(markets > 0):

        weight, cost = map(int, input().strip().split())
        price = weight/cost

        if(min_price is None) or (price < min_price):
            min_price = price

        markets -= 1

    return min_price * kilos

if __name__ == '__main__':
    a = SuperMarkets()
    print(a)


'''
Created on 28 jun. 2016

@author: TomLoonen
'''

class _Select_Stent_Endpoints:
    def __init__(self,ptcode,ctcode,basedir, clim=None):
        """ select start and endpoints to be used for centerline generation
        """
        from stentseg.apps._3DPointSelector import select3dpoints
        # from stentseg.apps.ui_dialog import MyDialog
        # from PyQt4 import QtGui

        import imageio
        import os
        from stentseg.utils.datahandling import select_dir, loadvol
        import copy

        # Select dataset to register
        cropname = 'prox'
        what = 'avgreg'

        # Load volumes
        s = loadvol(basedir, ptcode, ctcode, cropname, what)
        vol_org = copy.deepcopy(s.vol)
        s.vol.sampling = [vol_org.sampling[1], vol_org.sampling[1], vol_org.sampling[2]]
        s.sampling = s.vol.sampling

        # # Select nr of stents
        # app = QtGui.QApplication([])
        # m = MyDialog()
        # m.show()
        # m.exec_()
        # nr_of_stents = int(m.combo.currentText())

        # Endpoint selection
        points = select3dpoints(s.vol,nr_of_stents = 6, clim=clim)
        self.StartPoints = points[0]
        self.EndPoints = points[1]

        print('StartPoints are: ' + str(self.StartPoints))
        print('EndPoints are: ' + str(self.EndPoints))


#import numpy as np
#import cv2

#cap = cv2.VideoCapture(0)
#while(True):
#	ret, frame = cap.read()

#	gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

#	cv2.imshow('frame', gray)
#	if cv2.waitKey(1) & 0xFF == ord('q'):
#		break
#cap.release()
#cv2.destroyAllWindows()

if __name__ == '__main__':
	x = "ECE_180_DA_DB"
	if x == "ECE_180_DA_DB":
		print("You are living in 2017")
	else:
		x = x + " - Best class ever"
		print(x)


def fun():
    for i in range(20):
     x = yield i
     print('good', x)

def htest():
    i = 1
    while i < 4:
        n = yield i
        if i == 3:
            return 100
        i += 1

def itest():
    val = yield from htest()
    print("hello")
    print(val)

t = itest()
t.send(None)
j = 0
while j < 3:
    j += 1
    try:
        t.send(j)
    except StopIteration as e:
        print('异常了')
# if __name__ == '__main__':
#
#     a = fun()
#     for x in a:
#         print(x)

def g1(x):
    yield range(x)

def g2(x):
    yield from range(x)

it1 = g1(5)
it2 = g2(5)

print([x for x in it1])
# out [range(0, 5)]
print([x for x in it2])
# out [0, 1, 2, 3, 4]

import time

def func(n):
    yield from range(0, n)
    print('func:')
#
# def func(n):
#     for i in range(0, n):
#         arg = yield i
#         print("dddddddddddd")

f = func(10)
while True:
    try:
        print('main:', next(f))
        # print('main:', f.send(100))
        time.sleep(1)
    except StopIteration:
        exit()
        print("endddddddddddddd")
    finally:
        print("finally")
        #


import time

from kutuphane import *
print("""
****** İşlemler *******
1.Kitapları Göster
2.Kitap Sorgulama
3.Kitap Ekle
4.Kitap Sil
Çıkmak için q'ya basınız
""")
kitap = Kitap("Otomatik Portakal", "Anthony Burges","Palme", 300)
kutuphane = Kutuphane();
while True:
    islem = input("İşlem seçiniz: ")
    if(islem=='q'):
        print("Programdan çıkılıyor...")
        break
    elif(islem=='1'):
        kutuphane.kitaplari_goster()
    elif(islem=='2'):
        kitap_ismi = input("Aradığınız kitap ismini giriniz: ")
        print("Kitap sorgulanıyor...")
        time.sleep(2)
        kutuphane.kitap_sorgula(kitap_ismi)
    elif (islem == '3'):
        isim = input("İsim giriniz: ")
        yazar_adi = input("Yazar adı: ")
        yayinevi = input("Yayınevi giriniz: ")
        sayfa_sayisi = int(input("Sayfa sayısı giriniz: "))
        kitap = Kitap(isim, yazar_adi, yayinevi, sayfa_sayisi)
        print("Kitap ekleniyor...")
        time.sleep(2)
        kutuphane.kitap_ekle(kitap)
        print("Kitap başarıyla eklendi..")
    elif (islem == '4'):
        isim = input("Silmek istediğiniz kitap ismini giriniz: ")
        cevap = input("Emin misiniz(Evet=e, Hayır=h): ")
        if(cevap=='e'):
            print("Kitap siliniyor...")
            time.sleep(2)
            kutuphane.kitap_sil(isim)
            print("Kitap başarıyla silindi..")
    else:
        print("Gecersiz işlem ....")


from time import time

def ant_matrix(len_arr):
    start = time()
    prev_arr = [1]
    print(prev_arr)
    for i in range(1, len_arr):
        current_arr = []
        prev_index = 0
        prev_num = 0
        flg = True
        prev_arr_len = len(prev_arr)
        while(flg):
            count = 0
            prev_num = prev_arr[prev_index]
            current_arr.append(prev_num)
            while True:
                if prev_index == prev_arr_len:
                    flg = False
                    break
                elif prev_arr[prev_index] == prev_num:
                    count += 1
                    prev_index += 1
                else:
                    break
            current_arr.append(count)
        print(current_arr)
        prev_arr = current_arr
    print("Elapsed Time : ", time()-start)

def main():
    input_len = int(input("Length of Matrix : "))
    ant_matrix(input_len)

if __name__ == "__main__":
    main()

# Maid Bie SunYong


from .....parabank.src.base_element import BaseElement, Dropdown
from .....parabank.src.pages.base_parabank_page import BaseParabankPage
from .....parabank.src.pages.locators.account_services_pages_locators.transfer_funds_locators import TransferFundsLocators
from .....parabank.src.pages.exceptions.custom_exceptions import BaseElementException

class TransferFundsPage(BaseParabankPage):

    def __init__(self, driver):
        BaseParabankPage.__init__(self, driver,
                                  title="ParaBank | Transfer Funds",
                                  directory="/transfer.htm")
        self.input_amount = BaseElement(self.driver, *TransferFundsLocators.INPUT_AMOUNT)
        self.dropdown_from_account = Dropdown(self.driver, *TransferFundsLocators.DROPDOWN_FROM_ACCOUNT, "fromAccountId")
        self.dropdown_to_account = Dropdown(self.driver, *TransferFundsLocators.DROPDOWN_TO_ACCOUNT, "toAccountId")
        self.transfer_button = BaseElement(self.driver, *TransferFundsLocators.TRANSFER_BUTTON)

    def transfer_funds(self, amount):
        self.dropdown_from_account.wait_until_not_empty()
        self.dropdown_to_account.wait_until_not_empty()
        self.input_amount.set_text(amount)
        self.transfer_button.click()
        return self

    def is_success(self):
        try:
            return bool(BaseElement(self.driver, *TransferFundsLocators.SUCCESS_HEADING).get_text() ==
                        TransferFundsLocators.SUCCESS_MESSAGE)
        except BaseElementException:
            return False

    def print_transfer_funds_form_error(self):
        try:
            error = BaseElement(self.driver, *TransferFundsLocators.ERROR)
            self.logger.logger.warning('\nTransfer Funds form error: {}'.format(error.get_text()))
        except BaseElementException:
            pass


import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import random
import os
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from model import *
from user_agent import generate_user_agent
import re

MAIN_URL = 'https://usa.tommy.com/ProductListingView'
db_engine = create_engine("sqlite:///calvin.db", echo=True)
basedir = os.path.abspath(os.path.dirname(__file__))
size_list = []
details_list = []
color_list = []
url_list = []
cat_url_list = []
cookie = {
    'sr_browser_id': '33df22be-572e-4904-ba40-0ad50c8bf097',
    'sr_pik_session_id': 'a93a676-c1cc-79d7-d8d1-e0f2e070f5ea',
    '__utma': '230066073.559163455.1579546275.1583593346.1583599172.13',
    '__utmb': '230066073.9.10.1583599172',
    '__utmc': '230066073',
    '__utmz': '230066073.1581354246.9.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)',
    '__wid': '496949504',
    '_ga': 'GA1.2.559163455.1579546275',
    '_px2': 'eyJ1IjoiNDdkNjNiNzAtNjA5NC0xMWVhLWE2NDQtZjFhZjM2YWNiMDBkIiwidiI6ImQ2MGQxMGEyLTNiYjUtMTFlYS1hMjE1LTAyNDJhYz'
           'EyMDAwNSIsInQiOjE1ODM2MDA1OTkzNTgsImgiOiJlMTMzMjExNGY0YjE4N2VkZDU0OThlNTY5ZDRkZjIzYjU3NTgwMTVjY2FjNGFlYjk0N'
           'DAyNzYwZWU1Y2ExMzJlIn0=',
    '_pxvid': 'eyJ1IjoiNDdkNjNiNzAtNjA5NC0xMWVhLWE2NDQtZjFhZjM2YWNiMDBkIiwidiI6ImQ2MGQxMGEyLTNiYjUtMTFlYS1hMjE1LTAyNDJh'
              'YzEyMDAwNSIsInQiOjE1ODM2MDA1OTkzNTgsImgiOiJlMTMzMjExNGY0YjE4N2VkZDU0OThlNTY5ZDRkZjIzYjU3NTgwMTVjY2FjNGFl'
              'Yjk0NDAyNzYwZWU1Y2ExMzJlIn0=',
    'sctr': '1|1583532000000',
    'ADRUM': 's=1583600052675&r=https%3A%2F%2Fusa.tommy.com%2Fen%2Fwomen%2Fnewarrivals-women%2Ficon-wide-leg-stripe-pant-ww28013%3F0',
    'JSESSIONID': '0000einWRcx7PVbTVe62TS9mlJv:1crovuh4f'

}

proxy = {'HTTPS': '157.245.138.230:8118'}
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'calvin.db')
HEADERS = {
    'User-Agent': generate_user_agent(device_type="desktop", os=('mac', 'linux')),
    'Accept':'*/*',
    'Cache-Control':'no-cache',
    'Host':'usa.tommy.com',
    'Accept-Encoding':'gzip, deflate, br',
    'Connection':'keep-alive',
    'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,uz;q=0.6'}

payload = {
    'catalogId': '10551',
    'isHomeDepartment': 'false',
    'pageSize': '30',
    'disableProductCompare': 'true',
    'langId': '-1',
    'storeId': '10151', #CommerceSearch
    'categoryId': '', #pageId
    'beginIndex': '30',
    'minFacetCount': '1',
    'colorfacetselected': 'false',
    'cache': 'true'
}

engine = create_engine(SQLALCHEMY_DATABASE_URI, echo=True)
Session = sessionmaker(bind=engine)
session = Session()

def read_file_url():
    with open('input.txt', 'r') as file:
        for line in file:
            cat_url_list.append(line.strip('\n'))
    return cat_url_list

def get_html(url, payload=None):
    while True:
        time.sleep(random.randint(random.randint(6, 10), random.randint(12, 27)))
        html = requests.get(url, headers=HEADERS, proxies=proxy, params=payload, cookies=cookie)
        if html.status_code == 200:
            print(html.status_code)
            return html
        elif html.status_code == 403:
            print(html.status_code)
            print('weit to 600 sec')
            time.sleep(random.randint(600,800))
        else:
            time.sleep(random.randint(14, 27))
            print(html.status_code)
            continue

def parser_content(html, image_list):
    # порсит все данные из карточки кроме фото, подумать разбить на несколько функций
    soup = BeautifulSoup(html.text, 'html.parser')
    link = html.url
    try:
        # имя товара
        product_name = soup.find('span', class_='productNameInner').text
    except:
        product_name = None

    try:
        # базовая цена(без скидки)
        price = soup.find('div', id='price_display').find_all('span')[0].text[1:]
    except:
        price = None
    try:
        # акционная цена
        price_sale = soup.find('div', id='price_display').find_all('span')[1].text[1:]
    except (IndexError, ValueError):
        price_sale = None

    try:
        # доступные размеры, на сайте все доступные размеры имеют класс available, поэтому парсим только их
        block_size = soup.find('ul', id='sizes').find_all('li')
        for li in block_size:
            if li['class'] == ['available']:
                size_list.append(li.find('span').text)
    except:
        print(f'Size {None}')

    try:
        # маркированый список Details с доп инфой снизу карточки
        details_group = soup.find('ul', class_='bullets')
        for details in details_group.find_all('li'):
            details_list.append(details.text)
    except:
        details_list.append('')

    try:
        # цветовая схема доступных цветов с сайта
        radiogrup = soup.find('ul', class_='productswatches')
        for color in radiogrup.find_all('li'):
            color_list.append(color['data-color-swatch'])
    except:
        color_list.append('')

    try:
        # парсим 1 цвет
        color = soup.find('ul', class_='productswatches').find('li', class_='active')['data-color-swatch']
    except:
        color = ''

    try:
        # айди обьявления
        universal_id = soup.find('div', class_='universalStyleNumber').find_all('span')[1].text
    except:
        universal_id = ''

    try:
        # парсим категорию товара
        category = soup.find('div', id='breadcrumb').find_all('a')[-2].text + ' ' + \
                   soup.find('div', id='breadcrumb').find_all('a')[-1].text
    except:
        category = ''
    count = 1
    Session = sessionmaker(bind=db_engine)
    session = Session()
    try:
        new_element = Tommy(product_name, price, price_sale, ','.join(size_list), color, ','.join(image_list),
                             ','.join(details_list), category, ','.join(color_list), link)
        session.add(new_element)
        session.commit()
    except:
        pass
    count += 1
    size_list.clear()
    color_list.clear()
    details_list.clear()

def create_dir_name():
    dir_name = 'images'
    try:
        os.mkdir(dir_name)
    except OSError:
        print('Папка существует')
    return dir_name

def chek_images():
    # проверяет номер последней фото в папке, и при запуске парсера след фото будет +1
    num_file = []
    last_image = 0
    try:
        file_list = os.listdir('images')
        for list in file_list:
            num_file.append(int(re.findall(r'\d*', list)[0]))
        num_file.sort()
        print(num_file[-1])
    except(IndexError):
        num_file.append(0)
    last_image = num_file[-1]
    return last_image

def get_photo(html, dir_name):
    count_photo = chek_images()
    image_list = []
    img_name = []
    soup = BeautifulSoup(html.content, 'html.parser')
    image_url = soup.find('div', class_='product_main_image').find('img')['data-src']
    image_list.append(image_url)
    image_list.append(image_url.replace('main', 'alternate1'))
    image_list.append(image_url.replace('main', 'alternate2'))
    image_list.append(image_url.replace('main', 'alternate3'))
    for img in image_list:
        try:
            photo_name = count_photo
            file_obj = requests.get(img, stream=True)
            if file_obj.status_code == 200:
                with open(dir_name+'/'+str(photo_name)+'.JPG', 'bw') as photo:
                    for chunk in file_obj.iter_content(8192):
                        photo.write(chunk)
                count_photo +=1
                img_name.append(str(photo_name))
        except:
            print('Error file_obj')
    return img_name

def get_url_category(html):
    # функция будет парсить в список url всех карточек в список(отсылает отдельные запросы)
    count = 0
    soup = BeautifulSoup(html.content, 'html.parser')
    page_count = soup.find('div', id='filterInfo')['data-total-count']
    all_page = int(page_count) // 30
    prod = soup.find('div', class_='grid').find_all('a', class_='productThumbnail')
    for i in prod:
        url_list.append(i['href'])
    category_id = soup.find('head').find('meta', {'name': 'pageId'})['content']
    payload.update({'categoryId': category_id})
    for page in range(1, all_page + 1):
        count += 30
        payload.update({'beginIndex': count})
        #response = requests.get(MAIN_URL, headers=HEADERS, proxies=proxy, params=payload)
        response = get_html(MAIN_URL, payload=payload)
        print(html.status_code)
        sp = BeautifulSoup(response.content, 'html.parser')
        try:
            prod = sp.find('div', class_='grid').find_all('a', class_='productThumbnail')
            for i in prod:
                url_list.append(i['href'])
        except:
            continue
    return url_list

def main():
    Session = sessionmaker(bind=db_engine)
    session = Session()
    dir_name = create_dir_name()
    cat_url_list = read_file_url()
    for cat_url in cat_url_list:
        html = get_html(cat_url)
        url_list = get_url_category(html)
    for url in url_list:
        card_exist = session.query
        html = get_html(url)
        image_list = get_photo(html, dir_name)
        parser_content(html, image_list)

if __name__ == '__main__':
    main()


import requests
import re

# Manual PDF: https://www.correios.com.br/a-a-z/pdf/rastreamento-de-objetos/manual_rastreamentoobjetosws.pdf
class Objeto(object):
    def __init__(self, *args, **kwargs):
        self.cepDestino = ""
        self.dataPostagem = ""
        self.eventos = list()
        self.numero = kwargs.get('numero', '')
        self.categoria = kwargs.get('categoria', '')
        self.sigla = kwargs.get('sigla', '')
        self.nome = kwargs.get('nome', '')
        self.json = ""

        if 'evento' in kwargs and len(kwargs.get('evento', list())) > 0:
            evento = kwargs.get('evento')[0]
            self.cepDestino = evento.get('cepDestino', '')
            self.dataPostagem = evento.get('dataPostagem', '')

            for evento in kwargs.get('evento', list()):
                self.eventos.append(Evento(**evento))

class Evento(object):
    def __init__(self, *args, **kwargs):
        self.tipo = kwargs.get('tipo', '')
        self.data = kwargs.get('data', '')
        self.hora = kwargs.get('hora', '')
        self.criacao = kwargs.get('criacao', '')
        self.prazoGuarda = kwargs.get('prazoGuarda', '')
        self.diasUteis = kwargs.get('diasUteis', '')
        self.descricao = kwargs.get('descricao', '')
        self.detalhe = kwargs.get('detalhe', '')
        self.status = kwargs.get('status', '')

        if 'unidade' in kwargs:
            self.unidade = Unidade(**kwargs.get('unidade', dict()))

        if 'destino' in kwargs and len(kwargs.get('destino', list())) > 0:
            self.destino = Destino(**kwargs.get('destino')[0])

        if 'detalheOEC' in kwargs:
            self.detalheOEC = OEC(**kwargs.get('detalheOEC', dict()))

class Unidade(object):
    def __init__(self, *args, **kwargs):
        self.tipounidade = kwargs.get('tipounidade', '')
        self.local = kwargs.get('local', '')
        self.sto = kwargs.get('sto', '')
        self.codigo = kwargs.get('codigo', '')
        self.uf = kwargs.get('uf', '')
        self.cidade = kwargs.get('cidade', '')

        if 'endereco' in kwargs:
            self.endereco = Endereco(**kwargs.get('endereco', dict()))

class Endereco(object):
    def __init__(self, *args, **kwargs):
        self.numero = kwargs.get('numero', '')
        self.cep = kwargs.get('cep', '')
        self.localidade = kwargs.get('localidade', '')
        self.bairro = kwargs.get('bairro', '')
        self.codigo = kwargs.get('codigo', '')
        self.logradouro = kwargs.get('logradouro', '')
        self.uf = kwargs.get('uf', '')
        self.latitude = kwargs.get('latitude', '')
        self.longitude = kwargs.get('longitude', '')

class Destino(object):
    def __init__(self, *args, **kwargs):
        self.bairro = kwargs.get('bairro', '')
        self.local = kwargs.get('local', '')
        self.cidade = kwargs.get('cidade', '')
        self.uf = kwargs.get('uf', '')
        self.codigo = kwargs.get('codigo', '')

        if 'endereco' in kwargs:
            self.endereco = Endereco(**kwargs.get('endereco', dict()))

class OEC(object):
    def __init__(self, *args, **kwargs):
        self.lista = kwargs.get('lista', '')
        self.longitude = kwargs.get('longitude', '')
        self.latitude = kwargs.get('latitude', '')
        self.carteiro = kwargs.get('carteiro', '')
        self.distrito = kwargs.get('distrito', '')
        self.unidade = kwargs.get('unidade', '')

        if 'endereco' in kwargs:
            self.endereco = Endereco(**kwargs.get('endereco', dict()))

def generate_valid_code(cod, with_cep=False):
    cod = cod.strip()

    if len(cod) < 12 or 13 < len(cod):
        return ""

    prefix = cod[0:2]
    number = cod[2:10]
    suffix = cod[-2:]
    multipliers = [8, 6, 4, 2, 3, 5, 9, 7]

    if len(number) < 8 and len(cod) == 12:
        diff = 8 - len(number)
        zeros = "0" * diff
        number = zeros + number

    sum_ = sum(int(number[i]) * multipliers[i] for i in range(8))
    rest = sum_ % 11

    if rest == 0:
        verifying_digit = "5"
    elif rest == 1:
        verifying_digit = "0"
    else:
        verifying_digit = str(11 - int(rest))

    valid_code = prefix + number + verifying_digit + suffix

    if with_cep:
        obj = track(valid_code)
        return valid_code, str(obj.cepDestino)

    return valid_code

def track(cod):
    if not is_valid(cod):
        return None

    body = '''
   <rastroObjeto>
       <usuario>MobileXect</usuario>
       <senha>DRW0#9F$@0</senha>
       <tipo>L</tipo>
       <resultado>T</resultado>
       <objetos>{obj}</objetos>
       <lingua>101</lingua>
       <token>QTXFMvu_Z-6XYezP3VbDsKBgSeljSqIysM9x</token>
   </rastroObjeto>
   '''

    r = requests.post('http://webservice.correios.com.br/service/rest/rastro/rastroMobile',
                      data=body.format(obj=cod),
                      headers={'Content-Type': 'application/xml'})

    if r.status_code == 200:
        result = r.json().get('objeto', list())
        if result:
            obj = Objeto(**result[0])
            obj.json = r.json()
            return obj

    return None

def is_cod(cod):
    if re.match('^[a-zA-Z]{2}[0-9]{9}[a-zA-Z]{2}$', cod):
        return True
    return False

def is_valid(cod):
    return re.match('^[a-zA-Z]{2}[0-9]{9}[a-zA-Z]{2}$', cod)


import os

# here i'll test the open() function with the "x" (exclusive creation) attribute
# this should only allow me to write to file if it doesn't exist yet
os.chdir(os.path.dirname(__file__))# get absolute path to the file

#first time, should write only if file doesn't exist
f = open("file_xc.txt", "x", encoding = "utf-8")

f.write("This is just a test\n")
f.write("Hope you like my test\n")
f.write("Lovely 3rd line for you\n")
f.close()

# second time, this wil throw an error
f = open("file_xc.txt", "x", encoding = "utf-8")
f.write("Biggest test of all time")
f.close()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov  5 19:54:41 2020

@author: phalinp
"""

import cv2 as cv
import numpy as np

def draw_rectangle(img):
    cv.rectangle(img,(384,0),(510,128),(0,255,255),3)

    #For rectangle if have to give top left corner i.e. (384,0)
    #and bottom right i.e (510,128) (0,255,255) is colour and 3 is
    #thickness

    cv.imshow("image",img)
    cv.waitKey(0)
    cv.destroyAllWindows()

def draw_circle(img):
    cv.circle(img,(447,63),63,(0,0,255),-1)

    #for circle, center(447,63), radius = 63, colour and thickness is needed
    #thickness = -1 to fill colour in circle.

    cv.imshow("image",img)
    cv.waitKey(0)
    cv.destroyAllWindows()

def draw_ellipse(img):
    cv.ellipse(img,(200,200),(100,100),0,0,360,(0,0,255),-1)

    #For ellipse we have to define the center, the length of major and minor
    #axes, angle of rotation of ellipse in anticlock vise direction, startangle
    # and endangle denotes start and end of ellipse arc

    cv.imshow("image",img)
    cv.waitKey(0)
    cv.destroyAllWindows()

def main():
    img = np.zeros((512,512,3), dtype = np.uint8)

main()


# -*- coding：utf-8 -*-
"""
time:2021/2/24
author:李辰旭
organization: BIT
contact: QQ:316469360
——————————————————————————————
description：
$ 处理二值合成轨迹图的一些函数。
主要包括：
滤波降噪
提取轮廓质心
拟合二次曲线
计算像素高度
——————————————————————————————
note:
python3.7以上版本才可运行
"""
import numpy as np
import cv2 as cv
from scipy.optimize import leastsq
def apply(img_BW,k):
    '''输入二值单通道图像
    返回特定区域被涂黑(k=0)或涂白(k=1)的图像'''
    a=img_BW.copy()
    left=400
    right=1920-left
    mid_left=650
    mid_right=1920-mid_left
    mid_high=500
    a[:,:left]=255*k
    a[:,right:]=255*k
    a[mid_high:,mid_left:mid_right]=255*k
    return a
def find_centroid(img_BW):
    '''输入：二值图像
    返回：质心xy列表'''
    cnts,_ = cv.findContours(img_BW, cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
    X_Y=[]
    # 遍历轮廓集
    for c in cnts:
        # 计算轮廓区域的图像矩。 在计算机视觉和图像处理中，图像矩通常用于表征图像中对象的形状。这些力矩捕获了形状的基本统计特性，包括对象的面积，质心（即，对象的中心（x，y）坐标），方向以及其他所需的特性。
        M = cv.moments(c)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        X_Y.append((cX,cY))
    return X_Y

def func(params, x):
    a, b, c = params
    return a * x * x + b * x + c
# 误差函数，即拟合曲线所求的值与实际值的差
def error(params, x, y):
    return func(params, x) - y
# 对参数求解
def slovePara(X,Y):
    '''输入：两个列表
       返回：二次函数的三个参数abc
    '''
    p0 = [10, 10, 10]#abc的初值，还要迭代呢
    X=np.array(X)
    Y=np.array(Y)
    Para = leastsq(error, p0, args=(X, Y))
    a, b, c = Para[0]
    return a,b,c

def track_progress(img_BW,img,grand=950,startline=1250):
    '''输入合成的轨迹图（二值化的单通道图及二值化的三通道图）
       返回发球点的像素高度,返回处理过的图片'''
    #涂抹噪声
    applied=apply(img_BW,0)
    #滤波降噪
    #中值滤波
    mid_filer=cv.medianBlur(applied,3)
    #膨胀
    kernel = np.ones((5, 5), np.uint8)
    frame = cv.dilate(mid_filer, kernel, iterations=2)
    #找质心
    X_Y = find_centroid(frame)
    X=[]
    Y=[]
    for i in X_Y:
        X.append(i[0])
        Y.append(i[1])
        cv.circle(img, (i[0], i[1]), 10, (0, 0, 255), -1)
    #拟合抛物线
    try:
        a,b,c=slovePara(X,Y)
        print('抛物线参数：a=',a,'b=',b,'c=',c)
        #画抛物线
        for w in range(1920):
            h=int(a*(w*w)+b*w+c)
            if h>0&h<1080:
                cv.circle(img, (w, h), 3, (0, 255, 0), -1)
    except:
        print('拟合抛物线时出现错误，好像是因为拟合点少于三个')
    #画地面和起始线
    cv.line(img,(0,grand), (1919,grand), (255,0,0),3)
    cv.line(img,(startline,0), (startline,1079), (255,0,0),3)
    #找发球点，求高度
    try:
        height=a*(startline*startline)+b*startline+c - grand
        if height < 0:
            height*=-1
        print('像素高度=',height)
        return height,frame
    except:
        print('拟合抛物线时出现错误，abc没值')
        return -1,frame

if __name__ == '__main__':
    import os
    cv.namedWindow("obj", cv.WINDOW_NORMAL)
    cv.resizeWindow("obj", int(1920/3), int(1080/3))
    cv.moveWindow("obj", 0, 0)
    cv.namedWindow("applied", cv.WINDOW_NORMAL)
    cv.resizeWindow("applied", int(1920/3), int(1080/3))
    cv.moveWindow("applied", int(1920/3), 0)
    img = cv.imread("D:\\lalala.png")
    img_BW = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    track_progress(img_BW,img)
    cv.imshow("obj",img)
    cv.imshow("applied",img_BW)
    cv.waitKey(0)


import cv2

# using USB webcam number 1
cam = cv2.VideoCapture(0)

# You can save your video according to the same size as your webcam stream or hardcode the size you like
# frame_width = int(cam.get(3))
# frame_height = int(cam.get(4))
# recorder = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('M','J','P','G'),20, (frame_width,frame_height))

# Saving the video in 640x480 size
recorder = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 20, (640, 480))

while cam.isOpened():
    # read the frames from the webcam
    ret, frame = cam.read()
    # save the frame and write to our output file
    recorder.write(frame)

    # show the frames in a Windows
    cv2.imshow('My Webcam', frame)
    k = cv2.waitKey(1) & 0xFF
    # if 'Q' is pressed, the programs exits
    if k == ord('q'):
        break

# release the webcam frames
cam.release()
# release the video recorder frames
recorder.release()
# destroy all windows
cv2.destroyAllWindows()


import sys

def main(lines):
    class info:
      def __init__(self, number, string):
        self.number = number
        self.string = string

      def calc(self):
        if num % self.number == 0:
          ans.append(self.string)

      def print_ans(self, answer):
        if len(ans) == 1:
          print(num)

        for i in ans[1:]:
          answer += i

        print(answer)

    ans = [0]
    answer = ""
    lines = lines.split()
    informations = {i: info(False, False) for i in range(len(lines) - 1)}

    for i, v in enumerate(lines):
      val = v.split(":")
      val[0] = int(val[0])
      if len(val) != 1:
        informations[i].number = val[0]
        informations[i].string = val[1]

      else:
        num = val[0]

    for i in range(len(lines) - 1):
      informations[i].calc()

    informations[0].print_ans(answer)

if __name__ == '__main__':
    lines = []
    l = sys.stdin.readline()
    main(l)


"""
validate and maniopulate genbank files.
"""
from setuptools import find_packages, setup

dependencies = ['click']

setup(
    name='faketool',
    version='0.1.4',
    url='https://github.com/sgordon007/fake-tool',
    license='BSD',
    author='Sean Gordon',
    author_email='seangordon07@gmail.com',
    description='validate and maniopulate genbank files.',
    long_description=__doc__,
    packages=find_packages(exclude=['tests']),
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    install_requires=['click', 'biopython'],
    entry_points={
        'console_scripts': [
            'genbank_validate = genbank_validate.cli:main',
        ],
    },
    classifiers=[
        # As from http://pypi.python.org/pypi?%3Aaction=list_classifiers
        # 'Development Status :: 1 - Planning',
        # 'Development Status :: 2 - Pre-Alpha',
        # 'Development Status :: 3 - Alpha',
        'Development Status :: 4 - Beta',
        # 'Development Status :: 5 - Production/Stable',
        # 'Development Status :: 6 - Mature',
        # 'Development Status :: 7 - Inactive',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: POSIX',
        'Operating System :: MacOS',
        'Operating System :: Unix',
        'Operating System :: Microsoft :: Windows',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)


N,M=map(int,input().split())
location=list(map(int,input().split()))
location.append(0)
list_plus=[]
list_minus=[]
location.sort()
index=location.index(0)
if index==N:
    list_plus.append(0)
else :
    list_plus=location[index+1:N+1]
list_minus=location[0:index]
minus_count=len(list_minus)
plus_count=len(list_plus)
if minus_count==0:
    list_minus.append(-0)
list_plus.sort(reverse=True)
comp=abs(list_minus[0])-list_plus[0]
sum=0

if M==1:
    if(comp>0):
        last_index=0
    else :
        last_index=N
    sum=abs(location.pop(last_index))

    for i in location:
        sum=sum+abs(i*2)

else :
    arr=[]
    arr2=[]
    if(minus_count<=M and plus_count<=M):
        if(comp>0):
            sum+=abs(list_minus[0])+2*list_plus[0]
        else :
            sum+=2*abs(list_minus[0])+list_plus[0]

    elif(minus_count>M and plus_count<=M):
        count=minus_count-M
        index=minus_count-count
        if(comp>0):
            sum+=list_plus[0]*2+abs(list_minus[0])
        else:
            sum+=list_plus[0]+2*abs(list_minus[0])
        while 1 :
            if(count>M):
                arr.append(list_minus[index:index+M])
                count=count-M
                index=minus_count-count
            else:
                arr.append(list_minus[index:minus_count])
                for i in arr:
                    sum+=abs(i[0])*2
                break

    elif(minus_count<=M and plus_count>M):
        count=plus_count-M
        index=plus_count-count
        if(comp>0):
            sum+=abs(list_minus[0])+2*list_plus[0]
        else :
            sum+=2*abs(list_minus[0])+list_plus[0]

        while 1 :
            if(count>M):
                arr.append(list_plus[index:index+M])
                count=count-M
                index=plus_count-count
            else:
                arr.append(list_plus[index:plus_count])
                for i in arr:
                    sum+=(i[0])*2
                break

    elif(minus_count>M and plus_count>M):
        count1=minus_count-M
        count2=plus_count-M
        index1=minus_count-count1
        index2=plus_count-count2
        if(comp>0):
            sum+=abs(list_minus[0])+2*list_plus[0]
        else:
            sum+=2*abs(list_minus[0])+list_plus[0]

        while 1 :
            if(count1>M):
                arr.append(list_minus[index1:index1+M])
                count1=count1-M
                index1=minus_count-count1
            else :
                arr.append(list_minus[index1:minus_count])
                for i in arr:
                    sum+=abs(i[0])*2
                break
        while 1 :
            if(count2>M):
                arr2.append(list_plus[index2:index2+M])
                count2=count2-M
                index2=plus_count-count2
            else :
                arr2.append(list_plus[index2:plus_count])
                for i in arr2:
                    sum+=(i[0])*2
                break

print(sum)


class Solution:
    def spiralOrder(self, matrix: [[int]]) -> [int]:
        if matrix == []:
            return []

        top = 0
        bottom = len(matrix) - 1
        left = 0
        right = len(matrix[0]) - 1

        res = []

        while top < bottom and left < right:

            res += matrix[top][left:right + 1]

            for x in range(top + 1, bottom):
                res.append(matrix[x][right])

            res += matrix[bottom][left:right + 1][::-1]

            for x in range(bottom - 1, top, -1):
                res.append(matrix[x][left])

            top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1

        if top == bottom:
            res += matrix[top][left:right + 1]
        elif left == right:
            for x in range(top, bottom + 1):
                res.append(matrix[x][right])

        return res


"""
DW NVM implementation
"""
from pyedbglib.protocols.jtagice3protocol import Jtagice3ResponseError

from .nvm import NvmAccessProviderCmsisDapAvr
from .avr8target import TinyAvrTarget

class NvmAccessProviderCmsisDapDebugwire(NvmAccessProviderCmsisDapAvr):
    """
    NVM Access the DW way
    """

    def __init__(self, transport, device_info):
        NvmAccessProviderCmsisDapAvr.__init__(self, device_info)

        self._log_incomplete_stack('AVR-debugWIRE')

        self.avr = TinyAvrTarget(transport)
        self.avr.setup_debug_session()

    def __del__(self):
        pass

    def read_device_id(self):
        """
        Read the device info

        :returns: Device ID raw bytes (Little endian)
        """
        try:
            resp = self.avr.activate_physical()
        except Jtagice3ResponseError:
            self.logger.error("Unable to activate debugWIRE.  Maybe ISP is active?")
            return "Error"
        self.logger.info("ID read: %02X%02X", resp[1], resp[0])
        self.avr.deactivate_physical()
        return bytearray(resp[0:2])

    def erase(self, memory_info=None, address=None):
        """
        Do a chip erase of the device
        """
        _dummy = memory_info
        _dummy = address
        self.logger.info("Unable to erase device using debugWIRE")

    @staticmethod
    def write(memory_info, offset, data):
        """
        Write the memory with data

        :param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class
        :param offset: relative offset within the memory type
        :param data: the data to program
        :return: None
        """
        _dummy = memory_info
        _dummy = offset
        _dummy = data
        # return None

    @staticmethod
    def read(memory_info, offset, numbytes):
        """
        Read the memory in chunks

        :param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class
        :param offset: relative offset in the memory type
        :param numbytes: number of bytes to read
        :return: array of bytes read
        """
        _dummy = memory_info
        _dummy = offset
        _dummy = numbytes
        return []


from trackingsimpy.simulation.revisit_interval import BaseRISimulation
from trackingsimpy.tracking import TrackingComputer
from trackingsimpy.radar import PositionRadar
import filterpy.common
from filterpy.kalman import IMMEstimator, KalmanFilter
from trackingsimpy.common.motion_model import constant_turn_rate_matrix, kinematic_state_transition
from trackingsimpy.target import DefinedTargetProcess
from trackingsimpy.common.measurement_model import position_measurement_matrix

import numpy as np

class DefinedIMM(BaseRISimulation):
    ORDER = 1
    DIM = 2
    DT = 0.1
    MAX_STEPS = 700

    def __init__(self, pfa=1e-6, sn0=50, beamwidth=0.02, n_max=20, x0=np.array([10e3, -200.0, 10e3, 0]),
                 P0=np.eye(4) * 1000, theta_accuracy=0.002):
        var = 0.1*9.81**2
        tr1 = -0.08
        tr2 = 0.1
        probs = np.ones(3) / 3
        p_switch = 1.0 / 100.0
        M = np.array([
            [1 - p_switch, p_switch / 2, p_switch / 2],
            [p_switch / 2, 1 - p_switch, p_switch / 2],
            [p_switch / 2, p_switch / 2, 1 - p_switch]
        ])
        filters = list()

        for i in range(3):
            filters.append(filterpy.common.kinematic_kf(self.DIM, self.ORDER, self.DT))
            filters[i].x = x0
            filters[i].Q = filterpy.common.Q_discrete_white_noise(self.DIM, self.DT, var=var, block_size=self.ORDER+1)

        filters[1].F = constant_turn_rate_matrix(tr1, self.DT)
        filters[2].F = constant_turn_rate_matrix(tr2, self.DT)

        st_models = {
            0: kinematic_state_transition(self.DT, self.ORDER, self.DIM),
            200: constant_turn_rate_matrix(tr1, self.DT),
            300: kinematic_state_transition(self.DT, self.ORDER, self.DIM),
            400: constant_turn_rate_matrix(tr2, self.DT),
            500: kinematic_state_transition(self.DT, self.ORDER, self.DIM)
        }

        p_noises = {
            0: filterpy.common.Q_discrete_white_noise(self.DIM, self.DT, var=var, block_size=self.ORDER + 1)
        }
        target = DefinedTargetProcess(x0, st_models, p_noises, self.MAX_STEPS, self.ORDER, self.DIM)
        tracker = IMMEstimator(filters, probs, M)
        radar = PositionRadar(target, sn0, pfa, beamwidth, self.DIM, self.ORDER, angle_accuracy=theta_accuracy)
        computer = TrackingComputer(tracker, radar, n_max, P0=P0)

        super().__init__(computer)

class DefinedCVCAIMM(BaseRISimulation):
    ORDER = 2
    DIM = 2
    DT = 0.1
    MAX_STEPS = 3000

    def __init__(self, pfa=1e-6, sn0=50, beamwidth=0.02, n_max=20, x0=np.array([30e3, -150, 0, 30e3, 150, 0]),
                 theta_accuracy=0.002):

        # Trackers
        probs = np.ones(2) / 2
        p_switch = 1.0 / 1000.0
        M = np.array([
            [1 - p_switch, p_switch],
            [p_switch, 1 - p_switch]])

        F_ca = kinematic_state_transition(self.DT, self.ORDER, self.DIM)
        F_cv = kinematic_state_transition(self.DT, self.ORDER, self.DIM)
        F_cv[:, 2::3] = 0

        g = 9.81
        var = 4 * g ** 2
        Q = filterpy.common.Q_discrete_white_noise(self.DIM, self.DT, var, block_size=self.ORDER + 1)

        kf_cv = KalmanFilter(dim_x=self.DIM * (self.ORDER + 1), dim_z=self.DIM)
        kf_cv.F = F_cv
        kf_cv.Q = Q
        kf_cv.H = position_measurement_matrix(self.DIM, self.ORDER)

        kf_ca = KalmanFilter(dim_x=self.DIM * (self.ORDER + 1), dim_z=self.DIM)
        kf_ca.F = F_ca
        kf_ca.Q = Q
        kf_ca.H = position_measurement_matrix(self.DIM, self.ORDER)

        filters = [kf_cv, kf_ca]
        tracker = IMMEstimator(filters, probs, M)

        # Target
        st_models = {
            0: F_cv,
            1000: F_ca,
            2000: F_cv
        }
        p_noises = {
            0: Q
        }
        target = DefinedTargetProcess(x0, st_models, p_noises, self.MAX_STEPS, self.ORDER, self.DIM)

        # Radar
        radar = PositionRadar(target, sn0, pfa, beamwidth, self.DIM, self.ORDER, angle_accuracy=theta_accuracy)

        # Computer
        P0 = np.zeros((x0.size,) * 2)
        computer = TrackingComputer(tracker, radar, n_max, P0=P0)

        super().__init__(computer)


import random

dict_options = {1: "Rock", 2: "Paper", 3: "Scissors"}
winner = "Me"
me_i = 0
you_i = 0
error_count = 0

def did_you_win(m, y):
    if (m == 1) and (y == 2):
        return "You"
    elif (m == 1) and (y == 3):
        return "Me"
    elif (m == 2) and (y == 3):
        return "You"
    elif (m == 2) and (y == 1):
        return "Me"
    elif (m == 3) and (y == 1):
        return "You"
    elif (m == 3) and (y == 2):
        return "Me"
    else:
        return "Draw"

while error_count < 5:
    print("Choose your weapon:\n1 - Rock\n2 - Paper\n3 - Scissors")
    my_selection = random.randint(1, 3)
    selection = input("Please select 1, 2 or 3: ")

    try:
        your_selection = int(selection)
    except ValueError:
        your_selection = 4

    if (your_selection == 1) or (your_selection == 2) or (your_selection == 3):
        error_count = 0
        print("\nI chose {} - {}".format(my_selection, dict_options[my_selection]))
        print("You chose {} - {}\n".format(your_selection, dict_options[your_selection]))
        winner = did_you_win(my_selection, your_selection)
        if winner == "Me":
            me_i += 1
            print("I won!\n\nI've won {}\nYou've won {}\n".format(me_i, you_i))
        elif winner == "You":
            you_i += 1
            print("You won!\n\nI've won {}\nYou've won {}\n".format(me_i, you_i))
        else:
            print("It's a draw!\n\nI've won {}\nYou've won {}\n".format(me_i, you_i))
    else:
        if error_count < 4:
            print("You don't quite get this do you?.\nGo on try again.\n")
        else:
            print("You are obviously too stupid to play such a simple game - goodbye")
        error_count += 1


from urllib.request import Request, urlopen
from fake_useragent import UserAgent
import json
import csv

headers = {"user-agent": UserAgent().chrome, "referer": "https://finance.daum.net/"}
path = "./RPAbasic/crawl/download/"
data = []
try:
    url = "https://finance.daum.net/api/search/ranks?limit=10"
    res = urlopen(Request(url, headers=headers)).read().decode("UTF-8")
    # print(res) # JSON 형태로 반환

    # JSON To Dictionary
    rank_json = json.loads(res)["data"]

    for item in rank_json:
        print(
            "순위 {}, 금액 {}, 회사명 {}".format(
                item["rank"], item["tradePrice"], item["name"]
            )
        )
        data.append(item)

    # 크롤링 데이터 저장 ( txt 파일 / csv 파일 )
    with open(path + "finance.txt", "a", encoding="UTF-8") as txt:
        with open(path + "finance.csv", "a", encoding="UTF-8", newline="") as csvfile:
            # 텍스트 저장
            txt.write(
                "순위 {}, 금액 {}, 회사명 {}\n".format(
                    item["rank"], item["tradePrice"], item["name"]
                )
            )

            # csv 저장
            output = csv.writer(csvfile)
            # Column 타이틀 (Header)
            output.writerow(data[0].keys())
            for row in data:
                output.writerow(row.values())  # value 저장

except Exception as e:
    print(e)

# 비동기식 데이터 ( Ajax ) 는 값을 가져오지 못하고 있음

# 브라우저 설정 Network 탭 ( F12 )
# DOC : 실제 브라우저 페이지에 대한 요청 정보
# Fetch/XHR : 비동기식 데이터 접근을 위한 요청 정보
#   일부 사이트는 보안상의 문제로 AJax URL 접근을 제한 (Security ...) >> 403 Error 발생
#   데이터 확인 법 ( preview 탭에서 주고받은 데이터 확인 가능 )
#   ( headers 탭 ) referer: https://finance.daum.net/ ( 정상적으로 동작하기 위해서는 : https://finance.daum.net 에서 해당 데이터를 요청해야 함 )
#       referer : 데이터 요청이 들어온 페이지 ( 크롤링 할 때, fake 주소를 지정해서 Ajax 데이터를 조회해야 한다 )


import sys
import time
import os
import gc
import json
import argparse
from pathlib import Path

os.environ["JAX_PLATFORMS"] = "cpu"

import jax
import flax
import numpy as np
import jax.numpy as jnp
import orbax
import orbax.checkpoint
from optax import MaskedNode
from etils import epath
from praxis import base_hyperparams
from praxis import pax_fiddle
from praxis import py_utils
from paxml import checkpoints
from paxml import checkpoint_managers
from paxml import train_states
from paxml import trainer_lib
from flax.traverse_util import flatten_dict, unflatten_dict

from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import GenerationConfig

try:
    import torch
except:
    command = (
        "pip install torch==2.0.0+cpu torchvision==0.15.1+cpu torchaudio==2.0.1 --index-url"
        "https://download.pytorch.org/whl/cpu", "pip install transformers_stream_generator",
        "pip install accelerate"
    )
    subprocess.run(command, stdout=subprocess.PIPE, shell=True)
    import torch

TrainState = train_states.TrainState
CheckpointType = checkpoints.CheckpointType
Checkpointer = checkpoints.Checkpointer
PaxCheckpointHandler = checkpoints.PaxCheckpointHandler
NestedMap = py_utils.NestedMap
checkpoint_type = CheckpointType.GDA
SAVE_INTERVAL_STEPS = 1

LLAMA_STANDARD_CONFIGS = {
    "7B": {
        "dim": 4096,
        "intermediate_size": 11008,
        "n_layers": 32,
        "n_heads": 32,
        "norm_eps": 1e-6,
        "vocab_size": 151936
    },
    "14B": {
        "dim": 5120,
        "intermediate_size": 13696,
        "n_layers": 40,
        "n_heads": 40,
        "norm_eps": 1e-6,
        "vocab_size": 152064
    },
}

step = 0
model_size = '14B'
params = LLAMA_STANDARD_CONFIGS[model_size]
n_layers = params["n_layers"]
n_heads = params["n_heads"]
dim = params["dim"]
intermediate_size = params["intermediate_size"]
head_dim = dim // n_heads
save_opt = False

model = AutoModelForCausalLM.from_pretrained(f"Qwen/Qwen-{model_size}", device_map="auto", trust_remote_code=True).eval()
# pip install tiktoken
# tokenizer = AutoTokenizer.from_pretrained(f"Qwen/Qwen-{model_size}", trust_remote_code=True)

ckpt = {}
for k, v in model.named_parameters():
    ckpt[k] = v
assert len(ckpt) > 0, print(f"ckpt is empty, please model path whether right or error.....")

save_dir = f'gs://llm_base_models/qwen/{model_size}/paxml/checkpoints/'
options = checkpoint_managers.CheckpointManagerOptions(
    max_to_keep=10,
    save_interval_steps=SAVE_INTERVAL_STEPS,
    cleanup_tmp_directories=True,
)
checkpointer = Checkpointer(
    PaxCheckpointHandler(
        enforce_restore_shape_check=False,
        use_ocdbt=False,
    )
)
save_dir = epath.Path(save_dir)
checkpoint_manager = checkpoint_managers.OrbaxCheckpointManager(
    save_dir,
    checkpointer,
    train_input_checkpointer=False,
    options=options,
    checkpoint_type=checkpoint_type,
    tensorstore_use_ocdbt=False,
)

for k, v in model.named_parameters():
    print(k, v.shape)

paxml_to_hf_key_and_shape = {
    "params.lm.embedding_lookup.emb_var": {
        "shape": (vocab_size, dim),
        "map_to_hf": "wte.weight",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.ff_layer.ffn_layer1.linear.w": {
        "shape": (dim, intermediate_size),
        "map_to_hf": "w1.weight",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.ff_layer.ffn_layer1_gate.linear.w": {
        "shape": (dim, intermediate_size),
        "map_to_hf": "w2.weight",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.ff_layer.ffn_layer2.linear.w": {
        "shape": (intermediate_size, dim),
        "map_to_hf": "mlp.c_proj.weight",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.self_attention.query.w": {
        "shape": (dim, n_heads, head_dim),
        "map_to_hf": "q_proj.weight",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.self_attention.query.b": {
        "shape": (dim, n_heads, head_dim),
        "map_to_hf": "q_proj.bias",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.self_attention.key.w": {
        "shape": (dim, n_heads, head_dim),
        "map_to_hf": "k_proj.weight",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.self_attention.key.b": {
        "shape": (dim, n_heads, head_dim),
        "map_to_hf": "k_proj.bias",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.self_attention.value.w": {
        "shape": (dim, n_heads, head_dim),
        "map_to_hf": "v_proj.weight",
    },
     "params.lm.transformer.repeat.sub.x_layers_0.self_attention.value.b": {
        "shape": (dim, n_heads, head_dim),
        "map_to_hf": "v_proj.bias",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.self_attention.post.w": {
        "shape": (dim, n_heads, head_dim),
        "map_to_hf": "attn.c_proj.weight",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.layer_norm.scale": {
        "shape": (dim,),
        "map_to_hf": "ln_1.weight",
    },
    "params.lm.transformer.repeat.sub.x_layers_0.ff_layer.layer_norm.scale": {
        "shape": (dim,),
        "map_to_hf": "ln_2.weight",
    },
    "params.lm.final_ln.scale": {"shape": (dim,), "map_to_hf": "ln_f.weight"},
    "params.lm.softmax.logits_ffn.linear.w": {
        "shape": (dim, vocab_size),
        "map_to_hf": "lm_head",
    },
}

gold_w = ckpt
split_qkv = {}
for k, v in gold_w.items():
    if v.dtype == torch.float32:
        pass
    else:
        v = v.to(torch.float32)
    # o_proj不进行transpose，是个坑
    if len(v.shape) == 2 and "wte.weight" not in k and "attn.c_proj.weight" not in k:
        v = v.transpose(1, 0)
    else:
        print(f"No transpose k: {k}")

    if "c_attn" in k:
        qq = k.replace("c_attn", "q_proj")
        kk = k.replace("c_attn", "k_proj")
        vv = k.replace("c_attn", "v_proj")
        print(f'v.shape')
        if len(v.shape) == 1:
#             v = v.reshape(n_heads, 3 * head_dim)
            split_qkv[qq] = v[..., :dim].detach().numpy().reshape(-1)
            split_qkv[kk] = v[..., dim: 2 * dim].detach().numpy().reshape(-1)
            split_qkv[vv] = v[..., 2 * dim: ].detach().numpy().reshape(-1)
        elif len(v.shape) == 2:
#             v = v.reshape(dim, n_heads, 3 * head_dim)
            split_qkv[qq] = v[..., :dim].detach().numpy().reshape(dim, -1)
            split_qkv[kk] = v[..., dim: 2 * dim].detach().numpy().reshape(dim, -1)
            split_qkv[vv] = v[..., 2 * dim: ].detach().numpy().reshape(dim, -1)
        else:
            raise ValueError(f'qkv shape is error!!!')
    else:
        split_qkv[k] = v.detach().numpy()

for k, v in split_qkv.items():
    print(k, v.shape)

import re

trans_result = {}
flag = 0
with jax.default_device(jax.devices("cpu")[0]):
    for k, v in paxml_to_hf_key_and_shape.items():
        v = v["map_to_hf"]
        k = tuple(k.split("."))
        values = []
        for gold_key, glod_values in split_qkv.items():
            flag = 0
            if v in gold_key:
                flag = 1
                match_res = re.findall("q_proj|k_proj|v_proj|attn.c_proj", v)
                if match_res:
                    if len(glod_values.shape) > 1:
                        glod_values = glod_values.reshape(dim, n_heads, head_dim)
                    else:
                        glod_values = glod_values.reshape(n_heads, head_dim)
                try:
                    layer_index = int(re.findall("\d+", gold_key)[0])
                except:
                    layer_index = 0
                values.append([layer_index, glod_values])
                print(f"match_res: {match_res}|| {len(values)}")

        values = sorted(values, key=lambda x: x[0])
        if len(values) > 1:
            stack_values = np.stack(list(zip(*values))[1])
        else:
            stack_values = values[0][1]
        trans_result[k] = stack_values

print(f"Please simple check model shape and dtype...")
for k, v in trans_result.items():
    k = '.'.join(k)
    print(k, v.shape, v.dtype)

if step is None:
    latest_step = checkpoint_manager.latest_step()
    if save_dir == read_dir:
        step = latest_step + SAVE_INTERVAL_STEPS if latest_step is not None else SAVE_INTERVAL_STEPS
    else:
        step = latest_step

print(f"Model save step is {step}")
start = time.time()

if save_opt:
    with jax.default_device(jax.devices("cpu")[0]):

        opt_state_mv = jax.tree_map(lambda x: jnp.zeros_like(x), trans_result)
        temp_no_prefix, temp_other = {}, {}
        for key_tuple, param in opt_state_mv.items():
            if "repeat" in key_tuple:
                temp_no_prefix[key_tuple] = MaskedNode()
                temp_other[key_tuple] = param
            else:
                temp_no_prefix[key_tuple] = param
                temp_other[key_tuple] = MaskedNode()

        temp_no_prefix = unflatten_dict(temp_no_prefix)
        temp_other = unflatten_dict(temp_other)

        no_prefix = {"count": jnp.array(step), "m": temp_no_prefix, "v": temp_no_prefix}
        other = {"count": jnp.array([step] * n_layers), "m": temp_other, "v": temp_other}
        trans_opt_states = {
            "no_prefix": [{"count": jnp.array(step)}] * 2 + [no_prefix, {"count": jnp.array(step)}],
            f"p#{n_layers}#i-1": [{"count": jnp.array([step] * n_layers)}] * 2
            + [other, {"count": jnp.array([step] * n_layers)}],
        }
        trans_opt_states = [trans_opt_states]
else:
    trans_opt_states = []

new_trainstate = TrainState(
    step=jnp.array(step),
    mdl_vars=unflatten_dict(trans_result),
    opt_states=trans_opt_states,
)
padded_global_shapes = jax.tree_map(
    lambda x: jax.ShapeDtypeStruct(shape=x.shape, dtype=x.dtype) if hasattr(x, "shape") else x,
    new_trainstate,
)
print(f"padded_global_shapes: {padded_global_shapes}")
checkpoint_manager.save(
    step, new_trainstate, padded_global_shapes, train_input_pipeline=None, force=False
)
print(f"Saved model finished. take time: {time.time() - start}s...")


import random
import os
os.system('title Flip A Coin')
coin = ["heads", "tails"]
heads = 0
tails = 0
while 1:
    heads = 0
    tails = 0
    p = input("Enter times to flip the coin : ")
    for _ in range(int(p)):
        x = "".join(random.choices(coin))
        if 'tails' in x:
            tails+=1
        elif 'heads' in x:
            heads+=1
    tperc = tails * 100 / int(p)
    hperc = heads * 100 / int(p)
    print(f'Tails : {tails} ({int(tperc)}%)')
    print(f'Heads : {heads} ({int(hperc)}%)')


import sys
import random
import re
from functools import partial
from tqdm import tqdm

from junkdrawer import generator_looper

def lindenate(liRules, sInput="", lIterations=1):
    """This function iteratively processes a set of find-and-replace rules, liRules, on a given string, sInput.
        By default, it only goes through a single iteration, and processes the rules against an empty string.
            In a traditional Lindenmayer system, rules replace a single character (called the predecessor) with a string
        (called the successor).  In stochastic Lindenmayer systems, this successor can be chosen at random from a
        number of options. This function is modeled after a stochastic L-system, but with a few modifications;
            In this function, predecessors and successors are defined using Regex, which allows for multi-character and
        pattern-based matching, as well as smart replacement via capture groups. This also opens the door for characters
        or character sets which would match to more than one rule, meaning that, unlike L-systems, the order of rule
        application here matters.  With ordered rule application comes the possibility of a later rule affecting the
        successors of the previous rules inside of a single iteration; what I refer as a rule being "protected".
        :param Inputs:
            :param liRules:
                list of rule dictionaries. Each dctRule must have the following pairs:
                        "name":
                            string. Becomes description for progress bar
                        "enabled":
                            boolean. Whether this rule should be applied, or skipped.
                        "protected":
                            boolean. Whether the successor(s) introduced by this rule can be modified by rules
                            later in the list.
                        "predecessor":
                            string (regex). The regex expression searched for in the find-and-replace process
                        "successor":
                            list of tuples; [(number, string (regex)),(number, string (regex))]
                            The successor is stochastically determined via random.random.
                            The first element is a number between 0 and 1 representing the max random.random
                            value for which its corresponding successor, the second element, will be chosen.
                            If the random value is above all options, the successor is an empty string.
                            The tuples MUST be sorted in ascending order by their first element.
            :param sInput:
                String. The text to be mutated by the function
            :param lIterations:
                Number. The number of times to process the string through the rules.
        :return:
            String. The input text, as transformed by (lMaxGen - lCurrGen) iterations through liRules.
    """
    # If we're out of iterations to perform...
    if lIterations <= 0:
        # ...return the input
        return sInput
    sOut = sInput
    # This protection string is a string of equal length to the output.
    # The character sOut[x] is protected if sProtect[x] == "1"
    sProtect = "0" * len(sInput)
    # Loop through each rule
    for dctRule in liRules:
        # if the rule is not enabled...
        if not dctRule["enabled"]:
            # ...skip it
            continue
        # sTempProtect serves the purpose of sProtect within each rule, as a rule is never allowed to overwrite itself
        sTempProtect = sProtect
        objRgx = re.compile(dctRule["predecessor"])
        liReplacements = dctRule["successor"]
        itMatches = objRgx.finditer(sOut)
        lOffset = 0
        # Loop through all matches
        for objMatch in tqdm(itMatches, desc=dctRule["name"], file=sys.stdout):
            lStart = objMatch.span()[0] + lOffset
            lEnd = objMatch.span()[1] + lOffset
            sShieldCheck = sTempProtect[lStart:lEnd]
            # Check whether the match overlaps any protected substrings
            if "1" in sShieldCheck:
                # If there are some zeros in here, this match could be eclipsing another match.
                if "0" not in sShieldCheck:
                    continue
                # Find the next match.  This will either be the eclipsed match, or simply the next math in the iterable
                objMatch = objRgx.search(sOut[lStart+1:])
                # If there aren't any matches left at all in the string, we're done.
                if objMatch is None:
                    break
                # Adjust lStart and lEnd to account for how we sliced the string in line 111
                lStart += objMatch.span()[0] + 1
                lEnd += objMatch.span()[0] + 1
                # sPredecessor = objMatch.group(0)
            # Choose a successor
            fRand = random.random()
            lChoice = -1
            for i in range(len(liReplacements)):
                if fRand > liReplacements[i][0]:
                    continue
                else:
                    lChoice = i
                    break
            if lChoice == -1:
                sSuccessor = ''
            else:
                # The rest of the string is used here in case there are lookahead groups that are referenced by the
                # successor pattern (since they will not be captured in objMatch.group(0))
                sSuccessor = liReplacements[lChoice][1]
                # Manually swap out backreferences, checking for all notation types: \1, \g<1>, \g<name>
                # Step backward so that \20 gets replaced by group 20, not group 2
                for i in reversed(range(len(objMatch.groups())+1)):
                    sSuccessor = sSuccessor.replace("\\" + str(i), objMatch.group(i))
                    sSuccessor = sSuccessor.replace(r"\g<" + str(i) + ">", objMatch.group(i))
                for sGroupName in objMatch.groupdict():
                    sSuccessor = sSuccessor.replace(r"\g<" + sGroupName + ">", objMatch.group(sGroupName))
            # Stitch things back together
            sOut = sOut[:lStart] + sSuccessor + sOut[lEnd:]
            # Protect the affected substring.
            sShield = "1" * len(sSuccessor)
            sTempProtect = sTempProtect[:lStart] + sShield + sTempProtect[lEnd:]
            if dctRule["protected"]:
                sProtect = sProtect[:lStart] + sShield + sProtect[lEnd:]
            else:
                sProtect = sProtect[:lStart] + "0"*len(sShield) + sProtect[lEnd:]
            # The span of the remaining regex matches has already been set, so we need to accommodate for changing
            # string lengths with the lOffset
            lOffset += len(sSuccessor) - (lEnd - lStart)
    # If we're just spinning our wheels and not transforming the string...
    if sInput == sOut:
        # ...there's no need to run through future iterations.
        return sOut
    lIterations -= 1
    sOut = lindenate(liRules, sOut, lIterations)
    return sOut

def lindenator(liRules, sInput="", lIterations=1, lMaxReturns=None):
    """returns a generator object that returns lIterations additional iteration(s) (by default, 1) of lindenate from its
        previous return. First return is simply sInput. if specified, exhausts after lMaxReturns.
    """
    # Are infinite loops better than recursion? I think so
    # yield sInput
    # yield from lindenator(liRules, lindenate(liRules, sInput, lIterations), lIterations)
    if lMaxReturns is None:
        while True:
            yield sInput
            sInput = lindenate(liRules, sInput, lIterations)
    elif lMaxReturns > 0:
        for _i in range(lMaxReturns):
            yield sInput
            sInput = lindenate(liRules, sInput, lIterations)

def main():
    liRules = [
        {
            "name": "Rule1",
            "enabled": False,
            "protected": False,
            "predecessor": r"test",
            "successor": [(1, r"ans")]
        }, {
            "name": "Rule2",
            "enabled": True,
            "protected": True,
            "predecessor": r"1",
            "successor": [(1, r"3")]
        }, {
            "name": "Rule3",
            "enabled": True,
            "protected": True,
            "predecessor": r"(2(?P<middleLetter>[a-z])2)",
            "successor": [(1, r"Z\g<middleLetter>Z")]
        }, {
            "name": "Rule4",
            "enabled": True,
            "protected": True,
            "predecessor": r"[a-zA-Z][\d]",
            "successor": [(.5, r"7"), (1, r"9")]
        },
    ]
    liOverlapRules = [
        {
            "name": "Axiom",
            "enabled": True,
            "protected": True,
            "predecessor": r"^$",
            "successor": [(1, "ABBAAAA")]
        }, {
            "name": "Rule One",
            "enabled": True,
            "protected": True,
            "predecessor": r"(.)(?=AAA)",
            "successor": [(1, "Z")]
        }, {
            "name": "Rule Two",
            "enabled": True,
            "protected": True,
            "predecessor": r"AA",
            "successor": [(1, "CC")]
        }, {
            "name": "Rule Three",
            "enabled": True,
            "protected": True,
            "predecessor": r"A",
            "successor": [(1, "B")]
        }, {
            "name": "Rule Four",
            "enabled": True,
            "protected": True,
            "predecessor": r"B",
            "successor": [(1, "AAAA")]
        },

    ]
    """
    print(lindenate(liRules, "ttest8est82a22b2", 1))
    print(lindenate(liRules, "ttest8est82a22b2", 2))
    print(lindenate(liOverlapRules, "BBAAAA"))
    print(lindenate(liOverlapRules, lIterations=8))
    """
    sInput = input("test?")
    objLReturn = generator_looper(partial(lindenator, liOverlapRules, sInput, lMaxReturns=10))
    bKeepGoing = True
    while bKeepGoing:
        print(next(objLReturn))
        sInput = input("type 'end' to end")
        if sInput == "end":
            bKeepGoing = False
    print("ended")

if __name__ == "__main__":
    main()


# Add a filter to a palette
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i', default="Palette.dmp", help='Input tileset palette file. default is Palette.dmp')
parser.add_argument('-o', default="Palette2.dmp", help='Output tileset palette file. default is Palette2.dmp')
parser.add_argument('-r', default=4, type=int, help='Red value modifier, [-31, 31]. Default is 4')
parser.add_argument('-g', default=-16, type=int, help='Green value modifier, [-31, 31]. Default is -16')
parser.add_argument('-b', default=-16, type=int, help='Blue value modifier, [-31, 31]. Default is -16')
args = parser.parse_args()

input = open(args.i, "rb")
output = open(args.o, "wb")

# Add these values to each colour's R G and B.
redModifier = args.r
greenModifier = args.g
blueModifier = args.b

# Modify colours and concatenate.
for i in range(16):

    inputEntry = ord(input.read(1)) | (ord(input.read(1)) << 8)

    red = (inputEntry & 31) + redModifier
    green = ((inputEntry >> 5) & 31) + greenModifier
    blue = ((inputEntry >> 10) & 31) + blueModifier

    if red < 0:
      red = 0
    elif red > 31:
      red = 31
    if green < 0:
      green = 0
    elif green > 31:
      green = 31
    if blue < 0:
      blue = 0
    elif blue > 31:
      blue = 31

    outputEntry = red | (green << 5) | (blue << 10)

    output.write((outputEntry).to_bytes(2, byteorder='little', signed=False))

input.close()
output.close()


import urllib.request, json

from libbottles.utils import connection
from libbottles.exceptions import NoConnection

class Request:

    _headers = {}

    def __init__(self, headers: dict = None):
        self._headers["User-Agent"] = "libbottles client (usebottles.com)"

        if headers is not None:
            self._envs = {**self._headers, **headers}

        if not connection.check():
            raise NoConnection()

    def get(self, url: str):

        req = urllib.request.Request(
            url,
            data=None,
            headers=self._headers
        )

        with urllib.request.urlopen(req) as url:
            data = json.loads(url.read().decode())
            return data


import logging
from typing import Dict

import grpc

from needlestack.apis import collections_pb2
from needlestack.apis import servicers_pb2
from needlestack.apis import servicers_pb2_grpc
from needlestack.apis import serializers
from needlestack.collections.collection import Collection
from needlestack.collections.shard import Shard
from needlestack.cluster_managers import ClusterManager
from needlestack.servicers.settings import BaseConfig
from needlestack.utilities.rpc import unhandled_exception_rpc

logger = logging.getLogger("needlestack")

class SearcherServicer(servicers_pb2_grpc.SearcherServicer):
    """A gRPC servicer to perform kNN queries on in-memory index structures"""

    collections: Dict[str, Collection]
    collection_protos: Dict[str, collections_pb2.Collection]

    def __init__(self, config: BaseConfig, cluster_manager: ClusterManager):
        self.config = config
        self.cluster_manager = cluster_manager
        self.collections = {}
        self.collection_protos = {}
        self.cluster_manager.register_searcher()
        self.load_collections()

    @unhandled_exception_rpc(servicers_pb2.SearchResponse)
    def Search(self, request, context):
        X = serializers.proto_to_ndarray(request.vector)
        k = request.count
        collection = self.get_collection(request.collection_name)

        if len(X.shape) == 1:
            X = X.reshape(1, -1)

        if collection.dimension == X.shape[1]:
            results = collection.query(X, k, request.shard_names)
            items = [item for i, item in enumerate(results) if i < k]
            return servicers_pb2.SearchResponse(items=items)
        else:
            context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
            context.set_details(
                f"Collection {collection.name} expected matrix shaped ({collection.dimension}), got {X.shape}"
            )
            return servicers_pb2.SearchResponse()

    @unhandled_exception_rpc(servicers_pb2.RetrieveResponse)
    def Retrieve(self, request, context):
        collection = self.get_collection(request.collection_name)
        item = collection.retrieve(request.id, request.shard_names)
        if item is not None:
            return servicers_pb2.RetrieveResponse(item=item)
        else:
            return servicers_pb2.RetrieveResponse()

    @unhandled_exception_rpc(collections_pb2.CollectionsLoadResponse)
    def CollectionsLoad(self, request, context):
        self.load_collections()
        return collections_pb2.CollectionsLoadResponse()

    def get_collection(self, name: str) -> Collection:
        return self.collections[name]

    def load_collections(self):
        """Load collections from Zookeeper configs

        There are 4 states to handle for each collection:
            - A new collection needs to be loaded
            - An existing collection needs to be dropped
            - An existing collection added/dropped shards
            - No changes
        """
        collection_protos = self.cluster_manager.list_local_collections(
            include_state=False
        )
        current_collections = {name for name in self.collection_protos.keys()}
        new_collections = {proto.name for proto in collection_protos}
        for proto in collection_protos:
            if proto.name in current_collections:
                self._modify_collection(proto)
            else:
                self._add_collection(proto)
        for name in current_collections:
            if name not in new_collections:
                self._drop_collection(name)
        for collection in self.collections.values():
            if collection.update_available():
                logger.debug(f"Update collection {collection.name}")
                self.cluster_manager.set_local_state(
                    collections_pb2.Replica.BOOTING, collection.name
                )
                collection.load()
                self.cluster_manager.set_local_state(
                    collections_pb2.Replica.ACTIVE, collection.name
                )
        self.collection_protos = {proto.name: proto for proto in collection_protos}

    def _add_collection(self, proto: collections_pb2.Collection):
        logger.debug(f"Add collection {proto.name}")
        collection = Collection.from_proto(proto)
        self.cluster_manager.set_local_state(
            collections_pb2.Replica.BOOTING, collection.name
        )
        self.collections[collection.name] = collection
        collection.load()
        self.cluster_manager.set_local_state(
            collections_pb2.Replica.ACTIVE, collection.name
        )

    def _drop_collection(self, name: str):
        logger.debug(f"Drop collection {name}")
        del self.collections[name]

    def _modify_collection(self, proto: collections_pb2.Collection):
        old_proto = self.collection_protos[proto.name]
        if old_proto.SerializeToString() != proto.SerializeToString():
            collection = self.get_collection(proto.name)
            collection.merge_proto(proto)

            old_shards = {shard.name: shard for shard in old_proto.shards}
            new_shards = {shard.name: shard for shard in proto.shards}

            for name, new_shard in new_shards.items():
                if name not in old_shards:
                    logger.debug(f"Add collection shard {proto.name}/{name}")
                    self.cluster_manager.set_local_state(
                        collections_pb2.Replica.BOOTING, collection.name, name
                    )
                    collection.add_shard(Shard.from_proto(new_shard))
                elif (
                    new_shard.SerializeToString()
                    != old_shards[name].SerializeToString()
                ):
                    logger.debug(f"Update collection shard {proto.name}/{name}")
                    self.cluster_manager.set_local_state(
                        collections_pb2.Replica.BOOTING, collection.name, name
                    )
                    collection.drop_shard(name)
                    collection.add_shard(Shard.from_proto(new_shard))

            for name in old_shards.keys():
                if name not in new_shards:
                    logger.debug(f"Drop collection shard {proto.name}/{name}")
                    collection.drop_shard(name)

            collection.load()
            self.cluster_manager.set_local_state(
                collections_pb2.Replica.ACTIVE, collection.name, name
            )


"""
https://leetcode.com/problems/backspace-string-compare/

"""

class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        clean_s, clean_t = list(), list()

        for i, c in enumerate(S):
            if c != '#':
                clean_s.append(c)
            elif c == '#' and clean_s:
                clean_s.pop()

        for i, c in enumerate(T):
            if c != '#':
                clean_t.append(c)
            elif c == '#' and clean_t:
                clean_t.pop()

        return ''.join(clean_s) == ''.join(clean_t)


import json
from datetime import timedelta

from db.redis import init_redis_pool

async def add_test_result_to_redis(result_id: int, user_id: int, id_company: int, id_quiz: int, data: dict):
    redis = await init_redis_pool()

    key = f"result_test:{result_id:}:id_user:{user_id}:id_company:{id_company}:id_quiz:{id_quiz}"

    await redis.setex(key, timedelta(hours=48), json.dumps(data))

async def get_value_by_keys(**kwargs):
    values = await get_values_by_keys(**kwargs)

    return None if len(values) == 0 else values[0]

async def get_values_by_keys(**kwargs):
    redis = await init_redis_pool()

    pattern = '*' + '*'.join([f"{key}:{value}" for key, value in kwargs.items()]) + '*'

    keys = await redis.keys(pattern)

    return await get_values(redis, keys)

async def get_values(redis, keys):
    return [json.loads(await redis.get(key)) for key in keys if await redis.get(key)]


####################################################
##### This is focal loss class for multi class #####
##### University of Tokyo Doi Kento            #####
####################################################

import torch
import torch.nn as nn
import torch.nn.functional as F
# I refered https://github.com/c0nn3r/RetinaNet/blob/master/focal_loss.py

class FocalLoss2d(nn.Module):

    def __init__(self, alpha=1.0, gamma=0, weight=None,ignore_index=-100, size_average=True, with_grad=True):
        super(FocalLoss2d, self).__init__()
        assert gamma>=0.0 and gamma<=5.0,'gamma in [0,5] is okay, but %0.2f'%gamma
        assert alpha>0.0
        self.alpha = alpha
        self.gamma = gamma
        self.weight = weight
        self.size_average = size_average
        self.ignore_index=ignore_index
        self.with_grad=with_grad

    def forward(self, input, target):
        if input.dim()>2:
            input = input.contiguous().view(input.size(0), input.size(1), -1)
            input = input.transpose(1,2)
            input = input.contiguous().view(-1, input.size(2)).squeeze()
        if target.dim()==4:
            target = target.contiguous().view(target.size(0), target.size(1), -1)
            target = target.transpose(1,2)
            target = target.contiguous().view(-1, target.size(2)).squeeze()
        elif target.dim()==3:
            target = target.view(-1)
        else:
            target = target.view(-1, 1)

        # compute the negative likelyhood
        logpt = -F.cross_entropy(input, target,
                                 weight=self.weight,
                                 ignore_index=self.ignore_index,
                                 reduction='none')
        if self.with_grad:
            pt = torch.exp(logpt)
        else:
            with torch.no_grad():
                pt = torch.exp(logpt)
        # compute the loss
        loss = - self.alpha* ((1-pt)**self.gamma) * logpt

        # averaging (or not) loss
        if self.size_average:
            return loss.mean()
        else:
            return loss.sum()

if __name__ == '__main__':
    input=torch.rand(2,10,3,3).float()
    print(input.shape)
    target=torch.rand(2,10,3,3)
    target=torch.argmax(target,dim=1)
    loss_fn=FocalLoss2d()
    loss=loss_fn(input,target)
    print(loss)


import requests
from bs4 import BeautifulSoup
import json

# URL of the web page to scrape
url = 'https://nookipedia.com/wiki/Category:New_Horizons_fish_icons'

# Send an HTTP request to the web page
response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    # Parse the HTML content of the page using BeautifulSoup
    soup = BeautifulSoup(response.text, 'html.parser')

    # Find all image tags on the page
    image_tags = soup.find_all('img')

    # Extract the 'src' attribute from each image tag to get the image links
    image_links = [img['src'] for img in image_tags]

    # Create a dictionary with a "urls" key and the image links as its value
    data = {"urls": image_links}

    # Save the data to a JSON file
    with open('image_links.json', 'w') as json_file:
        json.dump(data, json_file, indent=4)

    print("Image links saved to 'image_links.json'")
else:
    print(f"Failed to retrieve the web page. Status code: {response.status_code}")


from django.db import models
from django.utils.translation import gettext_lazy as _

class VCard(models.Model):
    """
    Vcard model.
    """
    title = models.CharField(
        _("Title"),
        blank=True,
        max_length=150,
        default="",
    )

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = _("VCard")
        verbose_name_plural = _("VCards")


import json
import subprocess
import os
import zmq

class CommandLineBarcodeReader():
    def __init__(self, config_path="scandit_commandline",port=5556):
        self.context = zmq.Context()
        self.process = None
        self.config_path = config_path
        self.port = port
        self.start_commandline_zmq_server_if_unstarted()

    def start_commandline_zmq_server_if_unstarted(self):
        socket = self.context.socket(zmq.REQ)
        socket.connect("tcp://localhost:"+str(self.port))
        socket.send(b"Hello")
        message = ""
        try:
            message = socket.recv(flags=zmq.NOBLOCK)
            print(message)
        except Exception as e:
            print("start error")
            print(e)
            f = open(self.config_path,"r")
            commandline=[]
            for line in f.readlines():
                commandline.append(line.strip())
            f.close()
            self.process = subprocess.Popen(commandline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    def stop_commandline_zmq_server_if_started(self):
        try:
            self.process.kill()
        except:
            print("process not opened")

    def decode_file(self, img_path):
        result_dict = {}
        results = []
        try:
            socket = self.context.socket(zmq.REQ)
            socket.connect("tcp://localhost:"+str(self.port))
            socket.send(bytes(img_path,"utf-8"))
            message = socket.recv()
            json_object = json.loads(message.decode("utf-8"))
            if "results" in json_object:
                results=json_object["results"]
            if "elapsedTime" in json_object:
                result_dict["elapsedTime"]=json_object["elapsedTime"]
        except Exception as e:
            print("decode error")
            print(e)
        result_dict["results"] = results
        return result_dict

if __name__ == '__main__':
    #reader = CommandLineBarcodeReader()
    #reader = CommandLineBarcodeReader(config_path="zxing_commandline",port=5557)
    reader = CommandLineBarcodeReader(config_path="dbr88_commandline",port=6666)

    results = reader.decode_file("D:\\test\\BarcodePerformance\\new\\black_qr_code.png")
    print(results)
    reader.stop_commandline_zmq_server_if_started()


"""
    大多数(nobody)女主喜好
"""
BaiJiaHui = {
    'like': {'服饰搭配', '古典乐', '古装片', '滑雪', '美容', '民谣', '萨克斯', '桑拿', '时尚', '天文', '西餐', '演唱会', '游戏', '瑜伽', '桌游', '温泉', '吉他',
             '游泳', '度假村', '网球', '美容'},
    'dislike': {'美食', '高抬腿'}
}

GaoShanShan = {
    'like': {'高山', '有氧跑', '海边休闲', '剪纸', '民宿', '拼图', '桑拿', '派对', '爱情片', '服饰搭配', '天文', '平板支撑', '度假村', '花滑', '古典乐', '滑雪',
             '跳水'},
    'dislike': {'烹饪', '综艺', '马术', '游乐园', '足球', '科技', '瑜伽', '纯音乐'}
}

ZhuChenXi = {
    'like': {'游泳', '健身操', '瑜伽', '星座', '时尚', '农家乐', '度假村', '露营', '剪纸', '小提琴', '美食', '闽菜', '烹饪', '模玩', '刷视频', '科技'},
    'dislike': {'剧本杀', '推理片', '古装片', '警匪片', '恐怖片', '纪录片', '奇幻片', '仰卧起坐', '平板支撑', '俯卧撑', '深蹲', '高抬腿', '登山', '羽毛球', '网球',
                '逛街', '花艺', '温泉', '钢琴', '手风琴', '吉他', '演唱会', '绘画', '高山', 'up主', '动物园', '花滑', '海边休闲', '乒乓', '舞蹈', '哲学',
                '摇滚乐'}
}

mapping = {1: BaiJiaHui, 2: GaoShanShan, 3: ZhuChenXi}

if __name__ == '__main__':
    print("请选择人物: 1.白嘉卉 2.高珊珊 3.朱晨希")
    obj = mapping[int(input())]

    while 1:
        hobby = input()
        if hobby in obj['like']:
            print('like')
        elif hobby in obj['dislike']:
            print('dislike')
        else:
            print('wrong')


from tkinter import PhotoImage
import tkinter as tk

from ingresar import*
from generar import*
from general import*

from funciones import *
from archivo import *
from validaciones import *
matriz= []
matriz = leerDatos('datos')
print(matriz)

# diccionario de colores
color = {"fondo":"#F0F0F0", "sidebar":"#052744", "topbar":"#0D5D8C", "caja": "#BFBFBF" ,  "principal": "#043E79", "secundario": "#043E79","tercero":"#0E3D5E"}

#Configuaricón de la ventana
root = tk.Tk()
root.title("Sistema de donaciones")
root.geometry("1400x900+150+50")

#Barra superior
topFrame = tk.Frame(root, bg=color["topbar"])
topFrame.pack(side="top", fill=tk.BOTH)

#Header
titulo = tk.Label(topFrame, text="SISTEMA DE DONACIONES", font="Bahnschrift 15", bg=color["topbar"], fg="white", height=1, padx=20)
titulo.pack()

#Panel de navegación:
navFrame = tk.Frame(root, bg=color["sidebar"], width=300)
navFrame.pack(side="left",fill=tk.BOTH)

#Panel Principal
mainFrame = tk.Frame(root, bg=color["principal"])
mainFrame.pack(fill=tk.BOTH, expand=1)

#Cargar el inicio
corazon_img = PhotoImage(file="D:\TEC\I SEMESTRE\Intro-Taller (Laura)\Taller\Tareas\Tarea Programada 2\Tarea-Programada-2\iconos\cardiogram.png")
corazon_lb = tk.Label(mainFrame, image=corazon_img, bd=0)
corazon_lb.pack(side="top")

#Botones de navegación:
#Insertar
insertar_btn = tk.Button(navFrame, text="Insertar",font="BahnschriftLight 12", bg=color["principal"],fg="white", activebackground="white",\
activeforeground="black", bd=0, padx=60, pady=5, command=lambda:insertarDonadorES(mainFrame, corazon_img, matriz))
insertar_btn.place(x=50, y=80, width=200)

#Generar
generar_btn = tk.Button(navFrame, text="Generar",font="BahnschriftLight 12", bg=color["principal"],fg="white", activebackground="white",\
activeforeground="black", bd=0, padx=60, pady=5,command=lambda:generarDonadorES(mainFrame, corazon_img, matriz))
generar_btn.place(x=50, y=160, width=200)

#Actualizar
actualizar_btn = tk.Button(navFrame, text="Actualizar",font="BahnschriftLight 12", bg=color["principal"],fg="white", activebackground="white",\
activeforeground="black", bd=0, padx=60, pady=5, command=lambda:actulizarDonadorES(mainFrame, corazon_img, matriz))
actualizar_btn.place(x=50, y=240, width=200)

#Cargar Ventana:
root.mainloop()


from src.examples.program.traccar.config.config import Config
from src.examples.program.traccar.config.configKey import ConfigKey
from src.examples.program.traccar.model.extendedModel import ExtendedModel

class PropertiesProvider:

    def _initialize_instance_fields(self):

        self._config = None
        self._extendedModel = None

    def __init__(self, config):
        self._initialize_instance_fields()

        self._config = config

    def __init__(self, extendedModel):
        self._initialize_instance_fields()

        self._extendedModel = extendedModel

    def getString(self, key):
        if self._config is not None:
            return self._config.getString(key)
        else:
            result = self._extendedModel.getString(key.getKey())
            return result if result is not None else key.getDefaultValue()

    def getInteger(self, key):
        if self._config is not None:
            return self._config.getInteger(key)
        else:
            result = self._extendedModel.getAttributes().get(key.getKey())
            if result is not None:
                return int(str(result)) if isinstance(result, str) else int(result)
            else:
                return key.getDefaultValue()

    def getBoolean(self, key):
        if self._config is not None:
            if self._config.hasKey(key):
                return self._config.getBoolean(key)
            else:
                return None
        else:
            result = self._extendedModel.getAttributes().get(key.getKey())
            if result is not None:
                return bool(str(result)) if isinstance(result, str) else bool(result)
            else:
                return None


'''
Escreva um programa que leia a profissão e o tempo de serviço (em anos) de cada um dos 5
funcionários de uma empresa e armazene-os no arquivo "emp.txt". Cada linha do arquivo
corresponde aos dados de um funcionário.
'''

raiz = 'c:/Users/Higor H/Documents/Estudos/Python'
pasta = raiz + '/Curso de Programação em Python (Udemy)/Sessão 13 - Exercícios/ex23.txt'

with open(pasta, 'w', encoding='UTF-8') as arquivo:
    for i in range(5):
        nome = input('Digite o nome: ')
        cargo = input('Digite o cargo: ')
        tempo = input('Digite o tempo de serviço: ')
        arquivo.write(f'Nome: {nome} - Cargo: {cargo} - Tempo de Empresa: {tempo}\n')


import sys
from collections import deque
N, M, V = map(int, sys.stdin.readline().split())

graph = [[0]*(N+1) for i in range(N+1)]

#인접행렬생성
for i in range(M):
    a, b = map(int, sys.stdin.readline().split())
    graph[a][b] = graph[b][a] = 1

visited = [False] * (N + 1)

def dfs(V):
    visited[V] = True
    print(V, end=' ')
    for i in range(1, N+1):
        if not visited[i] and graph[V][i] == 1:
            dfs(i)

def bfs(V):
    print()
    visited = [False] * (N + 1)
    queue = deque([V])
    while queue:
        visited[V] = True
        V = queue.popleft()
        print(V, end=" ")
        for i in range(1, N+1):
            if not visited[i] and graph[V][i] == 1:
                queue.append(i)
                visited[i] = True

dfs(1)
bfs(1)