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

def right_insert(given_list: list, value):
    """
    функція, яка вставляє елемент у впорядкований список
    :param given_list: список елементів
    :param value: значення елемента, який треба вставити
    """
    i = 0
    n1 = len(given_list)
    # проходимо по елеменах токи їх значення менші, ніж даний елемент
    while i < n1 and given_list[i] < value:
        i += 1

    # вставляємо даний елемент після останнього меншого
    given_list.insert(i, value)

def rotate(given_dict: dict):
    """
    перевертання словника
    значення стають ключами, а ключі - значеннями

    :param given_dict: словник {ключ - список значень}
    :return: новий словник
    """
    res = {}

    # проходимо по всіх ключах і списках значень словника
    for key, value in given_dict.items():
        # проходимо по всіх значеннях у списку значень
        for v in value:

            # для кожного або створюємо новий запис у результуючому словнику,
            # або впорядковано додаємо до існуючого
            if v not in res.keys():
                res[v] = [key]
            else:
                right_insert(res[v], key)
    return res

if __name__ == '__main__':
    # test_dict = {}         # англо-латинський словник
    #
    # # зчитування
    # while True:
    #     line = input()       # зчитаний рядок, який перевіряємо на непорожність
    #     if not line:
    #         break
    #     line = line.strip().split(' - ')   # розбиваємо рядок по дефісам
    #     line[1] = line[1].split(', ')      # а праву частину результату розбиваємо по комам
    #     test_dict[line[0]] = line[1]       # додаємо новий запис до словника
    #
    # rez = rotate(test_dict)       # перевертаємо і впорядковано виводим
    # print(len(rez))
    # for el in sorted(rez.keys()):
    #     print('{} - {}'.format(el, ', '.join(rez[el])))

    test_dict = {}
    with open('input.txt', 'r') as file:
        for line in file:
            line = line.strip().split(' - ')  # розбиваємо рядок по дефісам
            line[1] = line[1].split(', ')  # а праву частину результату розбиваємо по комам
            test_dict[line[0]] = line[1]  # додаємо новий запис до словника

    rez = rotate(test_dict)
    with open("output.txt", 'w') as outfile:
        outfile.write(str(len(rez)))
        outfile.write('\n')
        for el in sorted(rez.keys()):
            outfile.write('{} - {}\n'.format(el, ', '.join(rez[el])))


import re
import json
import math
import os
from pathlib import Path

# function to convert a number value in a boolean sequence

def bin_convert(x,a0,a1,n):
	Xn = (x-a0)/(a1-a0)
	Xm = pow(2,n)*Xn
	ix = math.floor(Xm)
	x = bin(ix)
	x = '{:0b}'.format(ix)
	m=len(x)
	while m != n:
		x = "0" + x
		m=m+1
	bool_result=[]
	for t in range(n):
		if x[t] == '1':
			x_c = True
			bool_result.append(x_c)
		elif x[t] == '0':
			x_c = False
			bool_result.append(x_c)
	return bool_result

try:

# n-upla parameters:
# x0,x1,x2 => battery
# x3,x4,x5,x6 => x_position
# x7,x8,x9,x10 => y_position
# x11 => grasp

# parameters related to the resolution map:
# -(a0,a1) x-axis extremes
# -(b0,b1) y-axis extremes
# - n bit number

# initialise some variables
	n = 4
	a0 = -3.7
	a1 = 28
	b0 = -17
	b1 = 10
	fail = 0
	reached = 0
	trace = []
	init_bat_found = False
	init_pos_found = False
	init_gra_found = False
	count=0
	count_=0
	i=0

# SET HERE THE LOG_FILE FOLDER DIRECTORY
	path = '/home/gianluca/Desktop/MASTER_THESIS/RAL2022-experiments/logs-volume'

	# keywords to find the lines we are looking for in the log file
	key1 = "Command   : level"
	key2 = "getCurrentPose"
	key3 = "Command   : hasGrasped"

# set the file to analyze
	files = os.listdir(path)
	for file in files:
		count_ = count_+1
		#print(path+"/"+file)
		file_name=Path(path+"/"+file)
# initialize the trace with the zero tuple
		while count < 3:
			with open(file_name) as file_iterator:
				for line in file_iterator:

					if key1 in line and init_bat_found != True:
						nex = next(file_iterator)
						nex_1 = next(file_iterator)
						bat_level = [float(s) for s in re.findall(r'-?\d+\.?\d*', nex_1)]
						if bat_level != []:
	 						#print('\n- start_battery_state -')
	 						bat_level= bat_level[0]
	 						min_bat = 0
	 						max_bat = 101
	 						n_bit = 3
	 						x0_x1_x2 = bin_convert(bat_level, min_bat, max_bat, n_bit)
	 						#print(x0_x1_x2)
	 						init_bat_found = True
	 						count=count+1

					if key2 in line and init_pos_found != True:
	 					nex = next(file_iterator)
	 					nex_1 = next(file_iterator)
	 					rob_pose = [float(s) for s in re.findall(r'-?\d+\.?\d*', nex_1)]

	 					if rob_pose != []:
	 						x_pose = rob_pose[0]
	 						y_pose = rob_pose[1]

	 						x_bin = bin_convert(x_pose, a0, a1, n)
	 						y_bin = bin_convert(y_pose, b0, b1, n)
	 						x3_x4_x5_x6_x7_x8_x9_x10 = x_bin + y_bin

	 						#print('\n- start_position_state: -')
	 						#print(x3_x4_x5_x6_x7_x8_x9_x10)
	 						init_pos_found = True
	 						count=count+1

					if key3 in line and init_gra_found != True:
	 					nex = next(file_iterator)
	 					nex_1 = next(file_iterator)
	 					grasp = [float(s) for s in re.findall(r'-?\d+\.?\d*', nex_1)]
	 					if grasp != []:
	 						if grasp == [27503]:
	 							grasp_var = True
	 						else:
	 							grasp_var = False
	 						x11 = [grasp_var]
	 						#print('\n- start_grasp_state: -')
	 						#print(x11)
	 						init_gra_found = True
	 						count=count+1

		zero_tupla = x0_x1_x2 + x3_x4_x5_x6_x7_x8_x9_x10 + x11
		trace.append(zero_tupla)
		n_upla = [x0_x1_x2,x3_x4_x5_x6_x7_x8_x9_x10,x11]

	# check for new messages

		with open(file_name) as file_iterator:
	 		for line in file_iterator:
	 			if fail == 0:

	 				# check for new battery messages

	 				if key1 in line:
	 					nex = next(file_iterator)
	 					nex_1 = next(file_iterator)
	 					bat_level = [float(s) for s in re.findall(r'-?\d+\.?\d*', nex_1)]
	 					if bat_level != []:
	 						#print('\n- New Battery Message -')
	 						#print(bat_level)
	 						bat_level=bat_level[0]
	 						if bat_level<10:
	 							fail = 1
	 						min_bat = 0
	 						max_bat = 101
	 						n_bit = 3
	 						x0_x1_x2 = bin_convert(bat_level, min_bat, max_bat, n_bit)

	 						# update the trace adding new tupla

	 						if x0_x1_x2 != n_upla[0]:
	 							#print('\n**update battery**')
	 							n_upla[0] = x0_x1_x2
	 							tupla=n_upla[0]+n_upla[1]+n_upla[2]
	 							#print(tupla)
	 							trace.append(tupla)
	 						else:
	 							continue

	 				# check for new position messages

	 				if key2 in line:
	 					nex = next(file_iterator)
	 					nex_1 = next(file_iterator)
	 					rob_pose = [float(s) for s in re.findall(r'-?\d+\.?\d*', nex_1)]
	 					if rob_pose != []:
	 						x_pose = rob_pose[0]
	 						y_pose = rob_pose[1]

	 						if x_pose > 10.8 and y_pose > 2.7:
	 							reached = 1

	 						x_bin = bin_convert(x_pose, a0, a1, n)
	 						y_bin = bin_convert(y_pose, b0, b1, n)
	 						x3_x4_x5_x6_x7_x8_x9_x10 = x_bin + y_bin

	 						# update the trace adding new tupla

	 						if x3_x4_x5_x6_x7_x8_x9_x10 != n_upla[1]:
	 							#print('\n**update position**')
	 							n_upla[1] = x3_x4_x5_x6_x7_x8_x9_x10
	 							tupla=n_upla[0]+n_upla[1]+n_upla[2]
	 							#print(tupla)
	 							trace.append(tupla)
	 						else:
	 							continue

	 				# check for new grasp messages

	 				if key3 in line:
	 					nex = next(file_iterator)
	 					nex_1 = next(file_iterator)
	 					grasp = [float(s) for s in re.findall(r'-?\d+\.?\d*', nex_1)]
	 					if grasp != []:
	 						#print('\n- New Grasp Message -')
	 						if grasp == [27503]:
	 							grasp_var = True
	 						else:
	 							grasp_var = False
	 						x11 = [grasp_var]

	 						# update the trace adding new tupla

	 						if x11 != n_upla[2]:
	 							#print('\n**update grasp**')
	 							n_upla[2] = x11
	 							tupla=n_upla[0]+n_upla[1]+n_upla[2]
	 							#print(tupla)
	 							trace.append(tupla)
	 						else:
	 							continue
	 			elif(fail == 1):
	 				break

		#print('\nTrace:\n')
		#print(len(trace))
		#print(trace)

	# save the trace as a json file, if the robot reached the kitchen the task is complete and the trace will be indicate ad trace_s
	# instead if for some reason the robot don't reach the kicthen the trace is indicate ad trace_f
		dir_path = "/home/gianluca/Desktop/MASTER_THESIS/json_trace_folder"
		os.makedirs(dir_path, exist_ok=True)
		if fail == 0 and reached == 1:
			print('Trace n.',count_)
			print("SUCCESS")
			with open(os.path.join(dir_path, 'trace'+ str(count_) +'_s.json'), "w") as outfile:
	 			json.dump(trace, outfile)

		elif fail == 1 or reached == 0:
			print('Trace n.',count_)
			print("FAILURE")
			with open(os.path.join(dir_path, 'trace'+ str(count_) +'_f.json'), "w") as outfile:
	 			json.dump(trace, outfile)

	# entering except block
except :
	print("\nThe file doesn't exist!")


from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.http import HttpResponseRedirect, JsonResponse
from .models import Product, ProductCategory, ProductBrand, ProductReview
from .forms import ProductReviewForm
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.core.cache import cache
from techshop.settings import CACHE_TIMEOUT
from cart import cart
from cart import forms
from stats import stats
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
# Create your views here.
def product_list(request):
    products = Product.objects.active()
    for product in products:
        categories = product.categories.filter(is_active=True)
    featured_products = Product.objects.featured()
    search_recs = stats.recommended_from_search(request)
    recently_viewed = stats.get_recently_viewed(request)
    view_recs = stats.recommended_from_views(request)
    top_seller = Product.objects.filter(is_bestseller=True)
    return render(request, 'shop/index.html', locals())

def product_detail(request, id, slug):
    cart_items = cart.get_cart_items(request)
    product_cache_key = request.path
    # try to get product from cache
    product = cache.get(product_cache_key)
    # if a cache miss, fall back on db query
    if not product:
        product = get_object_or_404(Product, id=id, slug=slug, active=True)
        # store item in cache for next time
        cache.set(product_cache_key, product, CACHE_TIMEOUT)
    categories = product.categories.filter(is_active=True)
    page_title = product.name
    meta_keywords = product.meta_keywords
    meta_description = product.meta_description
    # evaluate the HTTP method, change as needed
    review_form = ProductReviewForm(request.POST or None)
    if request.method == 'POST':
        #create the bound form
        postdata = request.POST.copy()
        add_to_cart_form = forms.ProductAddToCartForm(request, postdata)
        #check if posted data is valid
        if add_to_cart_form.is_valid():
            #add to cart and redirect to cart page
            cart.add_to_cart(request)
            # if test cookie worked, get rid of it
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return HttpResponseRedirect(reverse("cart:cart_detail"))

        if review_form.is_valid():
            temp = review_form.save(commit=False)
            temp.product = product
            temp.user = request.user
            temp.save()
            return HttpResponseRedirect(product.get_absolute_url)
    else:
        #create the unbound form. Notice the request as a keyword argument
        add_to_cart_form = forms.ProductAddToCartForm(request=request)
    # assign the hidden input the product slug
    add_to_cart_form.fields['product_slug'].widget.attrs['value'] = slug
    # set test cookie to make sure cookies are enabled
    request.session.set_test_cookie()
    all_category = ProductCategory.objects.all()
    stats.log_product_view(request, product)
    # product review additions, CH 10
    product_reviews = ProductReview.approved.filter(product=product).order_by('-date')
    if request.is_ajax():
        html = render_to_string('shop/product_review.html', locals(), request=request)
        return JsonResponse({'product': html})
    return render(request, 'shop/detail.html', locals())

def category_list(request, slug):
    c = get_object_or_404(ProductCategory, slug=slug)
    products = c.product_set.all()
    page_title = c.name
    meta_keywords = c.meta_keywords
    meta_description = c.meta_description
    top_seller = Product.objects.filter(is_bestseller=True)
    return render(request, 'shop/category-shop.html', locals())

def brand_list(request, slug):
    pass
class StoreList(ListView):
    model = Product
    template_name = "shop/store.html"
    paginate_by = 20
    def get_context_data(self,*args,**kwargs):
        request = self.request
        context = super(StoreList,self).get_context_data(*args,**kwargs)
        all_category = ProductCategory.objects.all()
        all_brand = ProductBrand.objects.all()
        all_product = Product.objects.filter(active=True)
        top_seller = Product.objects.filter(is_bestseller=True)
        context["all_category"] = all_category
        context["all_brand"] = all_brand
        context["all_product"] = all_product
        context['top_seller'] = top_seller
        return context


from apscheduler.schedulers.background import BackgroundScheduler
import pytz
from datetime import datetime, timedelta
from kuclass_project.settings import env
from .models import Job, JobState
from .tasks import send_email_deadline_job

def remind_deadline_jobs():
    jobs = Job.objects.filter(
        state=JobState.PENDING,
        end_at__lte=datetime.now(
            tz=pytz.utc)-timedelta(days=env('DEADLINE_JOBS_DAYS', cast=int)),
    )
    for job in jobs:
        send_email_deadline_job.delay(job.title, job.end_at, job.user.email)

def change_state_failed_jobs():
    Job.objects.filter(
        state=JobState.PENDING,
        end_at__lte=datetime.now(
            tz=pytz.utc)-timedelta(seconds=env('DELAY_CHANGE_STATE_JOBS_SECOND', cast=int)),
    ).update(state=JobState.FAILED)

def main():
    scheduler = BackgroundScheduler(timezone='MST')
    scheduler.add_job(remind_deadline_jobs, 'interval', minutes=2)
    scheduler.add_job(change_state_failed_jobs, 'interval', seconds=30)
    scheduler.start()


from selenium import webdriver
import time

url = 'https://www.baidu.com'
driver = webdriver.Chrome()
driver.get(url)

# 使用JavaScript开启新的窗口
js = 'window.open("https://www.baidu.com");'
driver.execute_script(js)

# 获取当前页面的窗口信息
current_window = driver.current_window_handle

# 获取浏览器的全部窗口信息
handles = driver.window_handles

# 设置延时查看效果
time.sleep(3)

# 根据窗口信息进行窗口切换
driver.switch_to.window(handles[0])
time.sleep(3)
driver.switch_to.window(handles[1])


from collections import deque
import sys
input = sys.stdin.readline

def sol():
    q = deque()
    for i in range(1, n+1):
        if indegree[i] == 0:
            q.append(i)
    while q:
        now = q.popleft()
        for i in graph[now]:
            next_dist = distance[now] + d[i-1]
            distance[i] = max(distance[i], next_dist)
            indegree[i] -= 1
            if indegree[i] == 0:
                q.append(i)

t = int(input())
for _ in range(t):
    n, k = map(int, input().split())
    d = list(map(int, input().split()))
    indegree = [0] * (n+1)
    graph = [[] for _ in range(n+1)]
    distance = [0]
    for i in d:
        distance.append(i)
    for _ in range(k):
        x, y = map(int, input().split())
        graph[x].append(y)
        indegree[y] += 1
    w = int(input())
    sol()
    print(distance[w])


#
# Created by Diana Salamanca on 01-Jul-2021
#

import json

valid_chords = json.loads(input())
player_chords = input().split('-')
coincidences = list()
player_score = int()

for chord in player_chords:
    if chord in valid_chords:
        coincidences.append(chord)
        player_score += valid_chords[chord]

print(player_score)
print(",".join(coincidences))


"""
BOJ 문제 목록에 따라 소스 코드와 입출력 텍스트를 만듦.

사용법
1. 문제 목록 페이지에서 문제들 정보를 Ctrl + C 한 후,
2. problem_info.txt에 Ctrl + V.

예시 (문제 번호와 문제 이름 사이에 \t가 있어야 함)
17086	 아기 상어 2	성공	1566	4210	48.348%
1018	 체스판 다시 칠하기		24328	64255	47.159%
15652	 N과 M (4)		18199	28473	79.143%
15654	 N과 M (5)
"""

import os
from pathlib import Path
from datetime import date

# input.txt를 읽어오기 위해 소스 첫 부분에 써주는 코드
input_snippet = '''\
import sys
from pathlib import Path

parent_dir = Path(__file__).parent
file_name = Path(__file__).stem

sys.stdin = open(f"{parent_dir}\{file_name}_input.txt")
input = sys.stdin.readline'''

# 오늘 날짜에 맞는 폴더를 만듦
def makeDirectoryForToday():
    # 오늘 날짜
    today = date.today()
    dir_name = f"{today.month:02}{today.day:02}"

    # 새로운 폴더의 경로
    problem_set_dir = f"{Path(__file__).parent}\{dir_name}"

    # 폴더가 이미 있으면 오류, 없으면 새로 만들기
    try:
        if not os.path.exists(problem_set_dir):
            os.makedirs(problem_set_dir)
    except OSError as e:
        print(e)

    # 새로운 폴더 경로 반환
    return problem_set_dir

def createProblemSet(problem_file):
    text_dir = Path(__file__).parent
    target_dir = makeDirectoryForToday()

    text = open(f"{text_dir}\{problem_file}", encoding='UTF8')
    for line in text:
        # 테이블 열 사이에 탭 문자가 있어서, 탭 기준으로 자름
        # 문제 | 문제 제목 | 정보 | 맞힌 사람 | 제출 | 정답 비율 순.
        info = line.split('\t')
        # 첫 번째 열의 문제 번호 추출
        problem_num = info[0].strip()
        # 두 번째 열의 문제 이름 추출
        problem_name = info[1].strip().replace('/', '')

        # 문제 번호와 이름을 갖는 소스 코드 파일 생성
        file_name = problem_num + '. ' + problem_name
        f = open(f"{target_dir}\{file_name}.py", "w", encoding="UTF8")

        # 소스 코드 첫 부분에 input 텍스트 읽어오는 코드 추가
        f.write(input_snippet)
        f.close()

        # 문제 번호와 이름을 갖는 input txt 생성
        f = open(f"{target_dir}\{file_name} input.txt", "w", encoding="UTF8")
        f.close()

        # output txt 생성
        # f = open(f"{target_dir}\{file_name} output.txt", "w", encoding="UTF8")
        # f.close()

    text.close()

if __name__ == "__main__":
    createProblemSet("problem_info.txt")


# coding: utf-8

"""
    OpenAPI Petstore
    This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\  # noqa: E501
    The version of the OpenAPI document: 1.0.0
    Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
"""

from __future__ import annotations
from petstore_api.shared_imports.schema_imports import *  # pyright: ignore [reportWildcardImportFromLibrary]

A: typing_extensions.TypeAlias = schemas.StrSchema
Properties = typing.TypedDict(
    'Properties',
    {
        "a": typing.Type[A],
    }
)

class ObjWithRequiredPropsDict(schemas.immutabledict[str, schemas.OUTPUT_BASE_TYPES]):

    __required_keys__: typing.FrozenSet[str] = frozenset({
        "a",
    })
    __optional_keys__: typing.FrozenSet[str] = frozenset({
    })

    def __new__(
        cls,
        *,
        a: str,
        configuration_: typing.Optional[schema_configuration.SchemaConfiguration] = None,
        **kwargs: schemas.INPUT_TYPES_ALL,
    ):
        arg_: typing.Dict[str, typing.Any] = {
            "a": a,
        }
        arg_.update(kwargs)
        used_arg_ = typing.cast(ObjWithRequiredPropsDictInput, arg_)
        return ObjWithRequiredProps.validate(used_arg_, configuration=configuration_)

    @staticmethod
    def from_dict_(
        arg: typing.Union[
            ObjWithRequiredPropsDictInput,
            ObjWithRequiredPropsDict
        ],
        configuration: typing.Optional[schema_configuration.SchemaConfiguration] = None
    ) -> ObjWithRequiredPropsDict:
        return ObjWithRequiredProps.validate(arg, configuration=configuration)

    @property
    def a(self) -> str:
        return typing.cast(
            str,
            self.__getitem__("a")
        )

    def get_additional_property_(self, name: str) -> typing.Union[schemas.OUTPUT_BASE_TYPES, schemas.Unset]:
        schemas.raise_if_key_known(name, self.__required_keys__, self.__optional_keys__)
        return self.get(name, schemas.unset)
ObjWithRequiredPropsDictInput = typing.Mapping[str, schemas.INPUT_TYPES_ALL]

@dataclasses.dataclass(frozen=True)
class ObjWithRequiredProps(
    schemas.Schema[ObjWithRequiredPropsDict, tuple]
):
    """NOTE: This class is auto generated by OpenAPI JSON Schema Generator.
    Ref: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator

    Do not edit the class manually.
    """
    types: typing.FrozenSet[typing.Type] = frozenset({schemas.immutabledict})
    required: typing.FrozenSet[str] = frozenset({
        "a",
    })
    properties: Properties = dataclasses.field(default_factory=lambda: schemas.typed_dict_to_instance(Properties)) # type: ignore
    all_of: AllOf = dataclasses.field(default_factory=lambda: schemas.tuple_to_instance(AllOf)) # type: ignore
    type_to_output_cls: typing.Mapping[
        typing.Type,
        typing.Type
    ] = dataclasses.field(
        default_factory=lambda: {
            schemas.immutabledict: ObjWithRequiredPropsDict
        }
    )

    @classmethod
    def validate(
        cls,
        arg: typing.Union[
            ObjWithRequiredPropsDictInput,
            ObjWithRequiredPropsDict,
        ],
        configuration: typing.Optional[schema_configuration.SchemaConfiguration] = None
    ) -> ObjWithRequiredPropsDict:
        return super().validate_base(
            arg,
            configuration=configuration,
        )

from petstore_api.components.schema import obj_with_required_props_base
AllOf = typing.Tuple[
    typing.Type[obj_with_required_props_base.ObjWithRequiredPropsBase],
]


from bs4 import BeautifulSoup
import pandas
from selenium import webdriver
import time

# Set up the webdriver
driver = webdriver.Firefox()

driver.get(
    "https://www.shufersal.co.il/online/he/%D7%A7%D7%98%D7%92%D7%95%D7%A8%D7%99%D7%95%D7%AA/%D7%A1%D7%95%D7%A4%D7%A8%D7%9E%D7%A8%D7%A7%D7%98/%D7%97%D7%98%D7%99%D7%A4%D7%99%D7%9D%2C-%D7%9E%D7%AA%D7%95%D7%A7%D7%99%D7%9D-%D7%95%D7%93%D7%92%D7%A0%D7%99-%D7%91%D7%95%D7%A7%D7%A8/c/A25"
)
# driver.get(
#     "https://www.shufersal.co.il/online/he/%D7%A7%D7%98%D7%92%D7%95%D7%A8%D7%99%D7%95%D7%AA/%D7%A1%D7%95%D7%A4%D7%A8%D7%9E%D7%A8%D7%A7%D7%98/%D7%91%D7%99%D7%A9%D7%95%D7%9C-%D7%90%D7%A4%D7%99%D7%94-%D7%95%D7%A9%D7%99%D7%9E%D7%95%D7%A8%D7%99%D7%9D/c/A22"
# )
driver.implicitly_wait(10)

lenOfPage = driver.execute_script(
    "window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;"
)
lastCount = 0
while True:
    lenOfPage = driver.execute_script(
        "window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;"
    )
    if lastCount == lenOfPage:
        break
    lastCount = lenOfPage
    time.sleep(2)

html = driver.page_source

soup = BeautifulSoup(html, "html.parser")
units_name = soup.find_all(name="div", class_="text description")
print(units_name)
unit_name_list = [
    unit.find("span").get_text() if unit.find("span") else "" for unit in units_name
]

print(unit_name_list)
units_price = soup.find_all(name="span", class_="price")
unit_price_list = [
    unit.find(name="span", class_="number").getText() for unit in units_price
]

unit_gram = soup.find_all(class_="smallText", name="div")
unit_gram_list = [unit.find(name="span") for unit in unit_gram]
unit_gram_list = [unit.getText() for unit in unit_gram_list if unit != None]

image_list = soup.find_all(name="a", class_="imgContainer")
images_src = [image.find(name="img")["src"] for image in image_list]

df = pandas.DataFrame(columns=["NAME", "PRICE", "GRAM", "IMAGE_LINK"])

for unit in zip(unit_name_list, unit_price_list, unit_gram_list, images_src):
    df.loc[len(df.index)] = [unit[0], unit[1], unit[2], unit[3]]

df = df.iloc[1:]
print(df)
df.to_excel("shufersal.xlsx")


import json

from jsonschema import Draft7Validator, validators, exceptions

class ExtendedValidator:
    def __init__(self, jason_path, schema_path):
        self.my_schema = self.__load_json(schema_path)
        self.my_json = self.__load_json(jason_path)

    def extended_validator(self):
        DefaultValidatingDraft7Validator = self.__extend_with_default(Draft7Validator)

        try:
            DefaultValidatingDraft7Validator(self.my_schema).validate(self.my_json)
        except exceptions.ValidationError as e:
            return False, e
        except exceptions.SchemaError as e:
            return False, e
        return True, self.my_json

    @staticmethod
    def __extend_with_default(validator_class):
        validate_properties = validator_class.VALIDATORS["properties"]

        def set_defaults(validator, properties, instance, schema):
            for property, subschema in properties.items():
                if "default" in subschema:
                    instance.setdefault(property, subschema["default"])

            for error in validate_properties(
                    validator, properties, instance, schema,
            ):
                yield error

        return validators.extend(
            validator_class, {"properties": set_defaults},
        )

    @staticmethod
    def __load_json(path):
        with open(path, 'r') as f:
            my_json_file = json.load(f)
            return my_json_file


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

'''
Escreva a sua solução aqui
Code your solution here
Escriba su solución aquí
'''
n=3.14159
R=int(input())
Volume=(4.0/3)*n*(R**3)
print('VOLUME = %.3f' %Volume)


import ctypes
import logging
import socket
import pickle
import zmq

import numpy as np

from enum import Enum
from collections import namedtuple
from threading import Thread

from mpi4py import MPI
from melissa4py.message import MessageType
from melissa4py.message import ServerNodeName
from melissa4py.message import ConnectionRequest, ConnectionResponse
from melissa4py.message import SimulationData
from melissa4py.message import JobDetails
from melissa4py.message import Stop
from melissa4py.message import SimulationStatusMessage
from melissa4py.fault_tolerance import Simulation, SimulationStatus

# logging.basicConfig(filename="melissa_server.log", level=logging.INFO)
# logger = logging.getLogger("melissa_server")

class ServerStatus(Enum):
    CHECKPOINT = 1
    TIMEOUT = 2
#    RECEIVED_SIM_DATA = 3
#    RECEIVED_LAUNCHER_REQST = 4

class Verbose(Enum):
    MELISSA_INFO = 1

class MelissaServer:

    def __init__(self, nb_time_steps, nb_proc_server, nb_parameters,
                 learning=1, restart=False, fields=None,
                 verbose_level=Verbose.MELISSA_INFO,
                 connection_port=2003, text_pull_port=5556,
                 text_push_port=5555, text_request_port=5554,
                 data_puller_port=2005, linger=-1,
                 node_name='localhost',
                 launcher_node_name='localhost',
                 checkpoint_file='checkpoint.pkl',
                 data_hwm=32,
                 sample_size=None):

        # Initlialize MPI
        self.sobol_op = 0
        self.comm = MPI.COMM_WORLD
        self.rank = self.comm.Get_rank()
        self.comm_size = self.comm.Get_size()
        self.fields = fields
        self.checkpoint_file = checkpoint_file
        self.nb_time_steps = nb_time_steps
        self.nb_proc_server = nb_proc_server
        self.nb_parameters = nb_parameters
        self.learning = learning
        self.sample_size = sample_size
        print('Rank {} | Initializing server...'.format(self.rank))
        self.node_name = socket.gethostname()
        self.launcher_node_name = launcher_node_name
        self.connection_port = connection_port
        self.text_pull_port = text_pull_port
        self.text_push_port = text_push_port
        self.text_request_port = text_request_port
        self.linger = linger

        self.data_puller_port = str(data_puller_port) + str(self.rank)
        self.data_puller_port_name = "tcp://{}:{}".format(
            self.node_name, self.data_puller_port,
        )
        self.port_names = self.comm.allgather(self.data_puller_port_name)
        print('port_names', self.port_names)

        # 1. Set up sockets
        self.context = zmq.Context()
        # Simulations (REQ) <-> Server (REP)
        self.connection_responder = self.context.socket(zmq.REP)
        if (self.rank == 0):
            print('Rank {} binding..'.format(self.rank))
            addr = 'tcp://*:{port}'.format(port=self.connection_port)
            try:
                self.connection_responder.bind(addr)
            except Exception as e:
                print('Rank {} could not bind to {}'.format(self.rank, addr))
                raise e
        # Launcher (PUB) -> Server (SUB)
        self.text_puller = self.context.socket(zmq.SUB)
        self.text_puller.setsockopt(zmq.SUBSCRIBE, b"")
        self.text_puller.setsockopt(zmq.LINGER, self.linger)
        self.text_puller_port_name = "tcp://{}:{}".format(
            self.launcher_node_name, self.text_pull_port
        )
        self.text_puller.connect(self.text_puller_port_name)
        # Simulations (PUSH) -> Server (PULL)
        self.data_puller = self.context.socket(zmq.PULL)
        self.data_puller.setsockopt(zmq.RCVHWM, data_hwm)
        addr = "tcp://*:{}".format(self.data_puller_port)
        print('Connecting puller to: ', addr)
        self.data_puller.bind(addr)
        # Server (PUSH) -> Launcher (PULL)
        self.text_pusher = self.context.socket(zmq.PUSH)
        self.text_pusher.setsockopt(zmq.LINGER, self.linger)
        addr = "tcp://{node_name}:{port}".format(
            node_name=self.launcher_node_name, port=self.text_push_port
        )
        print('connected to {}'.format(addr))
        self.text_pusher.connect(addr)
        # Server (REQ) <-> Launcher (REP)
        self.text_requester = self.context.socket(zmq.REQ)
        self.text_requester.setsockopt(zmq.LINGER, self.linger)
        self.text_requester.connect("tcp://{}:{}".format(
            self.launcher_node_name, self.text_request_port)
        )
        # 2. Setup poller
        self.poller = zmq.Poller()
        self.poller.register(self.text_puller, zmq.POLLIN)
        self.poller.register(self.data_puller, zmq.POLLIN)

        # Keep track of simulations
        self.simulations = {}
        # TODO: maybe this should be an MPI gather on rank 0.
        self.verbose_level = 0
        # 2. Send node name to the launcher, get options and recover if necesary
        self._send_node_name()
        self.connection_request = None

        if restart:
            self._recover()
            self.first_connection_recieved = True
        else:
            # 3. Non-root nodes will wait for the root's info
            self.first_connection_recieved = False
            if (self.rank > 0) and not restart:
                print('rank: ', self.rank)
                self._wait_for_first_init()
                # self._get_options()

        if (self.rank == 0):
            self.stopping = False
            self.connection_listener_thread = Thread(
                target=self._listen_for_connections,
            )
            self.connection_listener_thread.start()

    def _listen_for_connections(self):
        poller = zmq.Poller()
        poller.register(self.connection_responder, zmq.POLLIN)
        print(f'Rank: {self.rank} | Listening for connections..')
        while True:
            if self.stopping == True:
                print(f'Rank: {self.rank} [Connection Listener Thread] Stopping.')
                break
            # 1. Poll sockets
            pr = poller.poll(timeout=100)
            sockets = dict(pr)
            # 2 Handle simulation connection message
            if (self.connection_responder in sockets
                and sockets[self.connection_responder] == zmq.POLLIN):
                msg = self.connection_responder.recv()
                print('Got connection request')
                rv = self.handle_simulation_connection(msg)

    def _send_node_name(self):
        """
        Send the node name to the launcher. This message serve as a signal
        the launcher that the server is online, and it can start simulations.
        """
        print('Sending node name..')
        msg = ServerNodeName(self.rank, self.node_name)
        self.text_pusher.send(msg.encode())
        print('Sent node name')

    def _wait_for_first_init(self):
        """
        Simulations will connect only to the root node. The root node
        will then broadcast the simulation's information to the other nodes.
        """
        print('Waithing for first connection..')
        try:
            request = None
            request = self.comm.bcast(request, root=0)
            self.client_comm_size = request.comm_size
        except Exception as e:
            print('Failed to recv simulation connection.')
            raise e

    def _get_options(self):
        """Get stats and options from the launcher"""
        request = 'options '.encode('utf-8')
        self.text_requester.send(request)
        response = self.text_requester.recv()
        self.handle_launcher_message(response)
        print(" === Options (not implemented yet) ===\n")

    def _request_simulation_metadata(self, simulation_id):
        # 1. Send request with simulation id to the launcher.
        print(f'Rank: {self.rank} | [Launcher] Requesting simulation metadata')
        request = 'simu_info {}'.format(simulation_id).encode('utf-8')
        self.text_requester.send(request)
        # 2. Recv response with simulation parameters.
        print(f'Rank: {self.rank} | [Launcher] Waiting launcher response')
        response = self.text_requester.recv()
        print(f'Rank: {self.rank} | [Launcher] Received metadata from launcher')
        job_details = JobDetails.from_msg(response, self.nb_parameters)
        # 3. Update simulation record.
        simulation = self.simulations.get(job_details.simulation_id)
        simulation.job_id = job_details.job_id
        simulation.parameters = job_details.parameters

    def _should_checkpoint(self):
        """
        Condition under which a checkpoint is to be initiated.
        """
        return False

    def _checkpoint(self):
        """
        Write simulation data to a file on pickle format.
        """
        path = '{}.pkl'.format(self.checkpoint_file)
        print('Checkpointing. Writing data to {}'.format(path))
        with open(path, 'wb') as f:
            pickle.dump(self.simulations, f)

    def _recover(self):
        path = '{}.pkl'.format(self.checkpoint_file)
        print('Recovering. Reading data from {}'.format(path))
        try:
            with open(path, 'rb') as f:
                self.simulations = pickle.load(self.simulations, f)
        except Exception as e:
            self.simulations = {}
            print('Could not load checkpoint.')

    def _check_progress(self):
        # TODO: implement a way of checking progress to determine
        # when it's time for the server to stop.
        pass

    def run(self, timeout=100):
        # Checkpoint
        if self._should_checkpoint():
            self._checkpoint()
            return ServerStatus.CHECKPOINT
        rv = None
        # 1. Poll sockets
        sockets = dict(self.poller.poll(timeout=timeout))
        if not sockets:
            return ServerStatus.TIMEOUT
        # 2. Handle launcher message
        if (self.text_puller in sockets
            and sockets[self.text_puller] == zmq.POLLIN):
            msg = self.text_puller.recv()
            rv = self.handle_launcher_message(msg)
        # 3. Handle simulation data message
        if (self.data_puller in sockets
            and sockets[self.data_puller] == zmq.POLLIN):
            msg = self.data_puller.recv()
            rv = self.handle_simulation_data(msg)
        # 4. Check progress
        self._check_progress()
        return rv

    def stop(self):
        """
        Signal to the launcher that the study has ended.
        """
        if (self.rank == 0):
            self.stopping = True
            print(f'Rank: {self.rank} | [Stop] Stopping listener thread..')
            self.connection_listener_thread.join()
            print(f'Rank: {self.rank} | [Stop] Listener stoped.')
        # 1. Syn server threads
        self.comm.Barrier()
        print(f'Rank: {self.rank} | [Stop] Sending termination message..')
        # 2. Send msg to the launcher
        if (self.rank == 0):
            # TODO  blocking if launcher is dead. Server will be stopped once reaching the batch scheduler walltime
            self.text_pusher.send(Stop().encode())
        print(f'Rank: {self.rank} | [Stop] Done')

    def handle_simulation_connection(self, msg):
        # 1. Deserialize connection message.
        request = ConnectionRequest.recv(msg)
        print(f'Rank: {self.rank} | [Connection] Received connection message from simulation {request.simulation_id}.')
        # 2. Broadcast if first connection.
        if not self.first_connection_recieved:
            print(f'Rank: {self.rank} | [Connection] Broadcasting first connection metadata...')
            self.comm.bcast(request, root=0)
            self.first_connection_recieved = True
        # 3. Send response with server metadata.
        print(f'Rank: {self.rank} | [Connection] Sending response to simulation {request.simulation_id}.')
        response = ConnectionResponse(self.comm_size, self.sobol_op,
                                      self.learning, self.nb_parameters,
                                      self.verbose_level, self.port_names)
        self.connection_responder.send(response.encode())
        print(f'Rank: {self.rank} | [Connection] Connection established with simulation {request.simulation_id}')
        return 'Connection'

    def handle_launcher_message(self, msg):
        msg_type = ctypes.c_int32.from_buffer_copy(msg[:4]).value
        print(f'Rank: {self.rank} | [Launcher] Received launcher message.')
        if msg_type == MessageType.JOB.value:
            job_details = JobDetails.from_msg(msg, self.nb_parameters)
            simulation = self.simulations.get(job_details.simulation_id)
            if not simulation:
                simulation = Simulation(job_details.simulation_id, self.fields,
                                        self.nb_time_steps)
                self.simulations[job_details.simulation_id] = simulation
            simulation.job_id = job_details.job_id
            simulation.parameters = job_details.parameters
            print(f'Rank: {self.rank} | [Launcher] New simulation '
                  f'{job_details.simulation_id} with '
                  f'parameters {job_details.parameters}')
        elif msg_type == MessageType.DROP.value:
            simulation_id = ctypes.c_int32.from_buffer_copy(msg[4:8]).value
            print(f'Rank: {self.rank} | [Launcher] Drop simulation {simulation_id}')
            job_id = msg[8:].decode()
            simulation = self.simulations.get(simulation_id)
            if simulation:
                del self.simulations[simulation_id]
            self.sample_size -= 1

    def handle_simulation_data(self, msg):
        """
        Parse and validate incoming data messages from simulations
        """
        # 1. Deserialize message
        simulation_data = SimulationData.from_msg(msg)
        simulation_id = simulation_data.simulation_id
        field = simulation_data.field_name
        print(("Rank: {} | Received timestep {} from rank {} of group {} "
              "(vect_size: {}, field: {})").format(
                  self.rank,
                  simulation_data.timestep,
                  simulation_data.client_rank,
                  simulation_data.simulation_id,
                  simulation_data.data_size,
                  field))
        # 2. Apply filters
        if not (0 <= simulation_data.timestep < self.nb_time_steps):
            print(f'Rank: {self.rank} | Bad timestamp: {simulation_data.timestep}')
            return None
        if field not in self.fields:
            print(f'Rank: {self.rank} | Bad field: {field}')
            return None
        # 3. Add simulation to the record if we don't have it yet.
        simulation = self.simulations.get(simulation_id)
        if simulation is None:
            simulation = Simulation(simulation_id, self.fields, self.nb_time_steps)
            self.simulations[simulation_id] = simulation
            # Notify the launcher of the connection
            msg = SimulationStatusMessage(simulation_id,
                                          SimulationStatus.RUNNING)
            print(f'Rank: {self.rank} | [Simulation Data] Notifying launcher of connection...')
            self.text_pusher.send(msg.encode())
        # 4. Validate timestep (ignore repeated messages)
        if simulation.timesteps[field][simulation_data.timestep] == 1:
            print('Rank: {} | Duplicate timestep: {} | field {} | simulationID: {}'.format(
                self.rank, simulation_data.timestep, field, simulation_id,
            ))
            return None
        else:
            simulation.mark_message_recieved(field, simulation_data.timestep)
        # 5. Request simulation parameters to the launcher.
        if simulation.parameters is None:
            print(f'Rank: {self.rank} | [Simulation Data] Requesting simulation metadata...')
            self._request_simulation_metadata(simulation_id)
        simulation_data.parameters = simulation.parameters
        # 6. Check if the simulation finished
        if simulation.finished():
            print(f'Rank: {self.rank} | Simulation {simulation_id} finished. Notifying launcher..')
            msg = SimulationStatusMessage(simulation_id,
                                          SimulationStatus.FINISHED)
            self.text_pusher.send(msg.encode())
        # 7. Return simulation data message if it has data.
        if simulation_data.data_size > 0:
            return simulation_data
        else:
            return None

    def all_done(self):
        # All simulations run
        if len(self.simulations) < self.sample_size:
            return False
        # All simulations finished or timedout
        for simulation in self.simulations.values():
            if not (simulation.finished() or simulation.crashed()):
                return False
        return True

    @property
    def status(self):
        connected = self.simulations.values()
        finished = [simulation for simulation in connected
                    if simulation.finished()]
        crashed = [simulation for simulation in connected
                   if simulation.crashed()]
        msgs_recieved = np.sum([simulation.timesteps[field]
                                for simulation in connected
                                for field in self.fields])
        missing_messages = np.sum([(1 - simulation.timesteps[field])
                                   for simulation in crashed
                                   for field in self.fields])
        return {
            'connected': len(connected),
            'finished': len(finished),
            'crashed': len(crashed),
            'messages_received': msgs_recieved,
            'messages_missing': missing_messages,
            'total_messages': msgs_recieved + missing_messages,
        }

if __name__ == '__main__':
    server = MelissaServer()
    while True:
        event = server.run()


import time

import jmespath
from botocore.exceptions import ClientError

from touchdown.aws import common
from touchdown.aws.rds import Database
from touchdown.core import errors, plan
from touchdown.core.datetime import now, parse_datetime

def get_from_jmes(db, **kwargs):
    new_kwargs = {}
    for key, value in kwargs.items():
        if callable(value):
            value = value()
        if value:
            newval = jmespath.search(value, db)
            if newval:
                new_kwargs[key] = newval
    return new_kwargs

class Plan(common.SimplePlan, plan.Plan):

    name = "rollback"
    resource = Database
    service_name = "rds"
    api_version = "2014-10-31"

    def get_database(self, name):
        try:
            dbs = self.client.describe_db_instances(DBInstanceIdentifier=name).get(
                "DBInstances", []
            )
        except ClientError:
            return None
        return dbs[0]

    def check_snapshot(self, db, snapshot_name):
        try:
            snapshots = self.client.describe_db_snapshots(
                DBInstanceIdentifier=db["DBInstanceIdentifier"],
                DBSnapshotIdentifier=snapshot_name,
            ).get("DBSnapshots", [])
        except ClientError:
            raise errors.Error("Could not find snapshot {}".format(snapshot_name))
        if len(snapshots) == 0:
            raise errors.Error("Could not find snapshot {}".format(snapshot_name))

    def check_point_in_time(self, db, point_in_time):
        # Ensure we don't restore too recently. For example:
        #  1. Obviously we can't restore the future
        #  2. Equally, there is about 5 minutes of replication lag. We can only
        #     restore to periods that were over 5 minutes ago.
        if point_in_time > db["LatestRestorableTime"]:
            raise errors.Error(
                "You cannot restore to {}. The most recent restorable time is {}".format(
                    point_in_time, db["LatestRestorableTime"]
                )
            )

        # Ensure we don't restore before this instance even existed
        if point_in_time < db["InstanceCreateTime"]:
            raise errors.Error(
                "You cannot restore to {} because it is before the instance was created ({})".format(
                    point_in_time, db["InstanceCreateTime"]
                )
            )

        # We can't restore earlier than the oldest backup either
        # With a caveat that InstanceIdentifier might imply a snapshot belongs
        # to the current database when it doesn't. We filter on matching
        # InstanceCreateTime to avoid that.
        results = self.client.describe_db_snapshots(
            DBInstanceIdentifier=db["DBInstanceIdentifier"]
        )
        snapshots = filter(
            lambda snapshot: snapshot["InstanceCreateTime"] == db["InstanceCreateTime"],
            results.get("DBSnapshots", []),
        )
        snapshots.sort(key=lambda snapshot: snapshot["SnapshotCreateTime"])
        if not snapshots or point_in_time < snapshots[0]["SnapshotCreateTime"]:
            raise errors.Error(
                "You cannot restore to {} because it is before the first available backup was created ({})".format(
                    point_in_time, snapshots[0]["SnapshotCreateTime"]
                )
            )

    def rename_database(self, from_name, to_name):
        print("Renaming {} to {}".format(from_name, to_name))
        self.client.modify_db_instance(
            DBInstanceIdentifier=from_name,
            NewDBInstanceIdentifier=to_name,
            ApplyImmediately=True,
        )

    def delete_database(self, name):
        print("Deleting old database")
        self.client.delete_db_instance(
            DBInstanceIdentifier=name, SkipFinalSnapshot=True
        )

    def wait_for_database(self, name):
        print("Waiting for database to be ready")
        while True:
            db = self.get_database(name)
            if (
                db
                and db["DBInstanceStatus"] == "available"
                and len(db["PendingModifiedValues"]) == 0
            ):
                return
            time.sleep(10)

    def copy_database_settings(self, db_name, db):
        print("Restoring database settings")
        self.client.modify_db_instance(
            DBInstanceIdentifier=db_name,
            ApplyImmediately=True,
            **get_from_jmes(
                db,
                AllocatedStorage="AllocatedStorage",
                DBSecurityGroups="DBSecurityGroups[?Status == 'active'].DBSecurityGroupName",
                VpcSecurityGroupIds="VpcSecurityGroups[?Status == 'active'].VpcSecurityGroupId",
                DBParameterGroupName="DBParameterGroups[0].DBParameterGroupName",
                BackupRetentionPeriod="BackupRetentionPeriod",
                PreferredBackupWindow="PreferredBackupWindow",
                PreferredMaintenanceWindow="PreferredMaintenanceWindow",
                EngineVersion="EngineVersion",
                CACertificateIdentifier="CACertificateIdentifier",
            )
        )

    def check(self, target):
        self.old_db_name = "{}-{:%Y%m%d%H%M%S}".format(self.resource.name, now())

        self.db = self.get_database(self.resource.name)
        if not self.db:
            raise errors.Error("Database {} not found?".format(self.resource.name))

        if self.get_database(self.old_db_name):
            raise errors.Error(
                "Database {} already exists - restore in progress?".format(
                    self.old_db_name
                )
            )

        self.datetime_target = None
        try:
            self.datetime_target = parse_datetime(target)
            self.check_point_in_time(self.db, self.datetime_target)
        except errors.Error:
            self.check_snapshot(self.db, target)

    def rollback(self, target):
        self.rename_database(self.resource.name, self.old_db_name)
        self.wait_for_database(self.old_db_name)

        kwargs = get_from_jmes(
            self.db,
            DBInstanceClass="DBInstanceClass",
            Port="Endpoint.Port",
            AvailabilityZone=lambda: "AvailabilityZone"
            if not self.db.get("MultiAZ", False)
            else None,
            DBSubnetGroupName="DBSubnetGroup.DBSubnetGroupName",
            MultiAZ="MultiAZ",
            PubliclyAccessible="PubliclyAccessible",
            AutoMinorVersionUpgrade="AutoMinorVersionUpgrade",
            LicenseModel="LicenseModel",
            DBName=lambda: "DBName" if self.db["Engine"] != "postgres" else None,
            Engine="Engine",
            Iops="Iops",
            OptionGroupName="OptionGroupMemberships[0].OptionGroupName",
            StorageType="StorageType",
            TdeCredentialArn="TdeCredentialArn",
        )

        print("Spinning database up from backup")
        if self.datetime_target:
            self.client.restore_db_instance_to_point_in_time(
                SourceDBInstanceIdentifier=self.old_db_name,
                TargetDBInstanceIdentifier=self.resource.name,
                RestoreTime=self.datetime_target,
                **kwargs
            )
        else:
            self.client.restore_db_instance_from_db_snapshot(
                DBInstanceIdentifier=self.resource.name,
                DBSnapshotIdentifier=target,
                **kwargs
            )

        self.wait_for_database(self.resource.name)

        self.copy_database_settings(self.resource.name, self.db)
        self.wait_for_database(self.resource.name)

        self.delete_database(self.old_db_name)


def store(wishList):

    with open("wishlist.txt", "w") as wish_file:

        for key,value in wishList.items():
            wish_file.write(f"{key},{value[0]},{value[1]}\n")

def read():
    wish_list = {}

    with open("wishlist.txt", "r") as wish_file:

        n = 1
        for line in wish_file:
            wish = line.strip().split(",")

            wish_list[n] = [wish[1], float(wish[2])]

            n += 1

    return wish_list

# example_wishlist = {
#    1 : ["book", 5.43],
#    2 : ["glasses", 105.43],
#    3 : ["Box", 40],
#    4 : ["Alcohol", 11.15]
#}

print(read())


# Problem Statement: https://www.hackerrank.com/challenges/detect-html-tags-attributes-and-attribute-values/problem

import sys
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
	def handle_starttag(self, tag, attrs):
		print(tag)
		for attr in attrs:
			print('->', ' > '.join(attr))

N = input()
parser = MyHTMLParser()
parser.feed(sys.stdin.read())
parser.close()


import numpy as np
import pandas as pd

from tests.common import assert_series_equal

class TestDataFrameDtypes:
    def test_dtypes(self, df):
        for i in range(0, len(df.dtypes) - 1):
            assert isinstance(df.dtypes[i], type(df.dtypes[i]))

    def test_select_dtypes(self, df):
        df.select_dtypes(include=np.number)
        df.select_dtypes(exclude=np.number)
        df.select_dtypes(include=np.float64)
        df.select_dtypes(exclude=np.float64)

    def test_es_dtypes(self, testdata):
        df = testdata.ed_flights_small()
        assert_series_equal(
            df.es_dtypes,
            pd.Series(
                {
                    "AvgTicketPrice": "float",
                    "Cancelled": "boolean",
                    "Carrier": "keyword",
                    "Dest": "keyword",
                    "DestAirportID": "keyword",
                    "DestCityName": "keyword",
                    "DestCountry": "keyword",
                    "DestLocation": "geo_point",
                    "DestRegion": "keyword",
                    "DestWeather": "keyword",
                    "DistanceKilometers": "float",
                    "DistanceMiles": "float",
                    "FlightDelay": "boolean",
                    "FlightDelayMin": "integer",
                    "FlightDelayType": "keyword",
                    "FlightNum": "keyword",
                    "FlightTimeHour": "float",
                    "FlightTimeMin": "float",
                    "Origin": "keyword",
                    "OriginAirportID": "keyword",
                    "OriginCityName": "keyword",
                    "OriginCountry": "keyword",
                    "OriginLocation": "geo_point",
                    "OriginRegion": "keyword",
                    "OriginWeather": "keyword",
                    "dayOfWeek": "byte",
                    "timestamp": "date",
                }
            ),
        )


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import six
import warnings
import keras
from keras import backend as K
#import tensorflow as K
import numpy as np
import tensorflow as tf # USING TF HERE LEADS TO STRANGE ERRORS!
from keras.utils.generic_utils import deserialize_keras_object
from keras.engine import Layer

def exp(x, eps=None):
    """
    Exponential unit.
    NOTE: This can return inf for large inputs!
    """
    if eps is None:
        eps = 0.0
    act = lambda x: K.exp(x) + eps
    return act(x)

def el(x, eps=None):
    """
    Exponential linear unit.
    """
    if eps is None:
        eps = 0.0
    act = lambda x: K.elu(x) + 1. + eps
    return act(x)

def elog(x, eps=None):
    """
    Exponential log unit.
    Uses TF workaround from: https://github.com/tensorflow/tensorflow/issues/2540
    """
    if eps is None:
        eps = 0.0
    exp_safe = tf.where(x <= 0, K.exp(x), 1.)
    a = 1.7632228343518967
    log_safe = tf.where(x < 0, 0,  a * tf.log(x + a))
    act = lambda x: tf.where(x <= 0, exp_safe, log_safe) + eps
    return act(x)

def et(x, eps=None, max_val=2.):
    """
    Exponential tanh unit.

    Args:
        x:

    """
    if eps is None:
        eps = 0.0
    exp_safe = tf.where(x <= 0, K.exp(x), tf.ones_like(x))
    a = max_val - 1.
    act = lambda x: tf.where(x < 0, exp_safe, a * tf.keras.backend.tanh(x/a) + 1) + eps
    return act(x)

def il(x, eps=None):
    """
    Approaches 0 for x-> -inf as 1/(1-x), with f(0)=1 and f'(0)=1. Cont differentiable.

    Uses TF workaround from: https://github.com/tensorflow/tensorflow/issues/2540

    Args:
        x:

    """
    if eps is None:
        eps = 0.0
    inv_safe = tf.where(x < 0, 1./(1. - x), tf.ones_like(x))
    act = lambda x: tf.where(x < 0, inv_safe, x+1) + eps
    return act(x)

def ilog(x, eps=None):
    """

    Args:
        x:

    Note:
        Tensorflow where statement will evaluate all cases, which can lead to instabilities?
    """
    if eps is None:
        eps = 0.0
    inv_safe = tf.where(x < 0, 1./(1. - x), tf.ones_like(x))
    a = 1.7632228343518967
    log_safe = tf.where(x < 0, 0,  a * tf.log(x + a))
    act = lambda x: tf.where(x < 0, inv_safe, log_safe) + eps
    return act(x)

def it(x, eps=None, max_val=2.):
    """

    Args:
        x:

    """
    a = max_val - 1.
    if eps is None:
        eps = 0.0
    inv_safe = tf.where(x < 0, 1./(1. - x), tf.ones_like(x))
    act = lambda x: tf.where(x < 0, inv_safe, a * tf.keras.backend.tanh(x/a) + 1) + eps
    return act(x)


from flask import Flask, redirect,render_template, request, jsonify
#from flask_socketio import SocketIO, send
from subprocess import call
import requests
from result_test import summarize, summary
from result_test import summarize
from crawling2 import titleArr2, contentArr2, imgArr2, urlArr2

app = Flask(__name__)

'''
@app.route("/", methods=['GET','POST'])
def hello_world():

    if request.method == 'POST':
        value = request.form['input-box']
        value = str(value)
        #print('--------------------------')
        #print(value)
    else:
        value = ''

    #resultSumm = summarize(value)
    #resultSumm = summarize_news_articles(value)
    resultSumm = summarize(value)

    newsSumm = []
    #for i in range(4):
        #newsSumm.append(summarize(newsContent[i]))
        #print(newsSumm[i])
        #print()

    return render_template('index.html', value = value,  titleArr2 = titleArr2, imgArr2 = imgArr2, urlArr2 = urlArr2, resultSumm = resultSumm)
'''

@app.route("/article", methods=['GET','POST'])
def articlePage():

    #newsSumm2 = []
    #for i in range(len(titleArr2)):
        #newsSumm2.append(summarize(newsContent2[i]))
        #print(newsSumm[i])
        #print()

    #print(newsSumm2)

    return render_template('article.html', titleArr2 = titleArr2, contentArr2 = contentArr2, imgArr2 = imgArr2, urlArr2 = urlArr2, summary = summary)

#상호 통신
@app.route("/process_data", methods=['POST'])
def process_data():
    # 클라이언트에서 전송한 데이터를 받습니다.
    input1 = request.form['input1']

    # 받은 데이터를 처리하고 필요한 응답을 생성합니다.
    # 예를 들어, 데이터를 가공하거나 파일을 저장할 수 있습니다.
    # 이 예제에서는 받은 데이터를 그대로 JSON 응답으로 반환합니다.
    response_data = {
        "input1": summarize(input1),
    }
    print('결과: ', response_data)

    return jsonify(response_data)

@app.route("/chat", methods=['GET','POST'])
def chatPage():

    value = ''
    chatSumm = ''
    if request.method == 'POST':
        value = request.form['reply-text']
        #value = request.form['aa']
        value = str(value)
        print('--------------------------')
        print(value)
        chatSumm = summarize(value)
        print('chatSumm: ', chatSumm)

    #chatSumm = summarize(msg)

    return render_template('chat.html',chatSumm = chatSumm, value = value)

@app.route("/", methods=['GET','POST'])
def homePage():

    return render_template('home.html')

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


#!/usr/bin/env python

from distutils.core import setup
import pystaggregator

V = pystaggregator.__version__

setup(name='pystaggregator',
      version=V,
      author='Rob Tandy',
      author_email='rob.tandy@gmail.com',
      url='https://github.com/robtandy/pystaggregator',
      long_description="""
      python client to provide instrumentaiton that will send stats (timers
      and counters) to staggregator (https://github.com/robtandy/staggregator),
      a stats aggregator for graphite, in the spirit of statsd.""",
      install_requires=["six >= 1.7.3", "requests >= 2.2.0"],
      packages=['pystaggregator'],
)


"""config URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from account.views import Login, Register, activate
from rest_framework_simplejwt import views as jwt_views

urlpatterns = [
    path('', include('blog.urls')),
    path('', include('django.contrib.auth.urls')),

    path('login/', Login.as_view(), name='login'),
    path('register/', Register.as_view(), name='register'),
    re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,50})/$',activate, name='activate'),

    path('admin/', admin.site.urls),
    path('comment/', include('comment.urls')),
    path('ratings/', include('star_ratings.urls', namespace='ratings')),
    path('account/', include('account.urls')),

    path("api/", include('api.urls')),
    path("api/", include('comment.api.urls')),
    path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),

    path('api/rest-auth/', include('dj_rest_auth.urls')),
    path('api/rest-auth/registration/', include('dj_rest_auth.registration.urls'))
]

# Just for debug mode , not useable in deploy.
from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import os

power_consumption = 0
gamma_rate = ''
epsilon_rate = ''
# Each position in the array of length 12 has a pair
# array[i] indicates the count of 0s and 1s at position i in the bitstring
# pair[0] represents the count of 0s at this position, pair[1] represents counts of 1
bit_counts = []
for i in range(12):
    bit_counts.append([0, 0])

with open(os.path.join(os.path.dirname(__file__), 'input.txt')) as f:
    lines = f.readlines()
    for i, l in enumerate(lines):
        # Trim last \n character
        l = l[:-1]
        # Go through each character in string
        for j, c in enumerate(l):
            if c is '0':
                bit_counts[j][0] += 1
            elif c is '1':
                bit_counts[j][1] += 1
            else:
                print(
                    'got invalid input, unexpected character {} in string: {}'.format(c, l))
                exit(1)
        print('{}) Got binary string {}, bit_counts: {}'.format(
            i, l, bit_counts))

for pair in bit_counts:
    if pair[0] > pair[1]:
        gamma_rate += '0'
        epsilon_rate += '1'
    elif pair[1] > pair[0]:
        gamma_rate += '1'
        epsilon_rate += '0'
    else:
        print(
            'there was a tie in the number of 0s and 1s when computing gamma & epsilon rates')
        exit(1)

print('gamma rate {}, episilon rate {}'.format(gamma_rate, epsilon_rate))

print('gamma rate integer {}, episilon rate integer {}'.format(
    int(gamma_rate, 2), int(epsilon_rate, 2)))

power_consumption = int(gamma_rate, 2) * int(epsilon_rate, 2)
print('power consumption: {}'.format(power_consumption))


import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import datasets
from sklearn import model_selection
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.svm import LinearSVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.utils import shuffle

df = pd.read_csv("archive/dataset_csv/train_data_clean.csv")

sentences = df["description"].values
vectorizer = TfidfVectorizer()
vectorizer.fit(sentences)
vectorizer.transform(sentences)

Y = df["genre"].values

X_train, X_test, y_train, y_test = train_test_split(
    sentences, Y, test_size=0.1, train_size=0.5)
vectorizer = TfidfVectorizer()
vectorizer.fit(X_train)

X_train = vectorizer.transform(X_train)
X_test = vectorizer.transform(X_test)

models = []
models.append(('LR', LogisticRegression()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', MultinomialNB()))
models.append(('SVM', LinearSVC()))
models.append(('MLP', MLPClassifier(hidden_layer_sizes=(10,))))

results = []
names = []
scoring = 'accuracy'
for name, model in models:
    print(f"Testing with {name}...")
    kfold = model_selection.KFold(n_splits=8)
    cv_results = model_selection.cross_val_score(
        model, X_train, y_train, scoring=scoring, n_jobs=-1, verbose=1, cv=kfold) * 100
    mean = cv_results.mean()
    results.append(mean)
    names.append(name)
    msg = "%s: %f (%f)" % (name, mean, cv_results.std())
    print(msg)

plt.title('How to compare sklearn classification algorithms')
plt.bar(names, results, width=0.7, color=plt.get_cmap(
    'Paired').colors, edgecolor='k', linewidth=2)
plt.xlabel("Classifier")
plt.ylabel("Accuracy (%)")
plt.savefig("compare_classifier.png")


"""Convert apriltags2_ros/AprilTagDetectionArrays to
apriltag_ros/AprilTagDetectionArrays.
"""
from __future__ import print_function

import rospy

from geometry_msgs.msg import PoseArray

from apriltags2_ros.msg import AprilTagDetection as AprilTag2Detection
from apriltags2_ros.msg import AprilTagDetectionArray as AprilTag2DetectionArray

from apriltags2to1.msg import AprilTagDetection, AprilTagDetectionArray

class AprilTagConverter:

    def __init__(self):
        self._camera_frame_id = rospy.get_param('~camera_frame_id', 'camera_link')

        self._targets_pub = rospy.Publisher('targets/out',
                                            AprilTagDetectionArray,
                                            queue_size=10)
        self._targets_array_pub = rospy.Publisher('targets/out/array',
                                                  PoseArray,
                                                  queue_size=10)
        self._targets_sub = rospy.Subscriber('targets/in',
                                             AprilTag2DetectionArray,
                                             self._targets_cb, queue_size=10)

    def _targets_cb(self, msg):
        # type: (AprilTag2DetectionArray) -> None
        """Re-publish each message in the format of an
        apriltags_ros/AprilTagDetectionArray.
        """
        det_arr_out = AprilTagDetectionArray()

        pose_arr_out = PoseArray()
        pose_arr_out.header.frame_id = self._camera_frame_id

        # Stamp current time, to be overwritten if there are any detections.
        pose_arr_out.header.stamp = rospy.Time.now()

        for detection_in in msg.detections:  # type: AprilTag2Detection
            detection_out = AprilTagDetection()

            detection_out.id = detection_in.id[0]
            detection_out.size = detection_in.size[0]

            detection_out.pose.header = msg.header
            detection_out.pose.header.frame_id = self._camera_frame_id
            detection_out.pose.pose = detection_in.pose.pose.pose

            det_arr_out.detections.append(detection_out)

            pose_arr_out.header.stamp = detection_out.pose.header.stamp
            pose_arr_out.poses.append(detection_out.pose.pose)

        self._targets_pub.publish(det_arr_out)
        self._targets_array_pub.publish(pose_arr_out)


from distutils.core import setup

import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(name='mock_request_builder',
      version='1.0',
      description='A generator for simple SQLAlchemy models endpoints in FastAPI',
      long_description=long_description,
      long_description_content_type="text/markdown",
      packages=setuptools.find_packages(),
      author='Maximilian Kutschka von Rothenfels',
      author_email='admin@flexi-servers.com',
      url='https://github.com/flexi-servers/mock_request_builder',
      python_requires='>=3.10',
      install_requires=[
            "sqlalchemy >=2.0.0",
            "fastapi >=0.98.0",
      ],
)


from Connection import *
from WindowCollectionCreateEdit import WindowCollectionCreateEdit
from GUI.GridManager import GridManager
from PreviewCollection import *
from WindowMode import WindowMode
from PIL import Image, ImageTk
from tkinter import ttk
from PreviewDeal import PreviewDeal
from GUI.ListManager import ListManager
from WindowTokenDeal import WindowTokenDeal
from GUI.EntryWithPlaceholder import EntryWithPlaceholder
from SearchUser import SearchUser
from SearchCollection import SearchCollection
from SearchToken import SearchToken
from WindowCoinCreateEditSearch import WindowCoinCreateEditSearch
from WindowBanknoteCreateEditSearch import WindowBanknoteCreateEditSearch
from WindowConsumerEdit import WindowConsumerEdit
from StatisticsConsumerRow import StatisticsConsumerRow
from StatisticsTokenRow import StatisticsTokenRow

from tkinter.messagebox import showwarning
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

class PageHome(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent, bg="white")
        self.controller = controller
        self.username = ""

        account_frame = Frame(self, width=1920, height=100, bg="#57a1f8")
        account_frame.grid(row=0, column=0, sticky='nw')

        img = Image.open(PATH_IMAGE_EMPTY_PROFILE)
        img = img.resize((90, 90), Image.ANTIALIAS)
        self.profile_image = ImageTk.PhotoImage(img)
        self.profile_img = Label(account_frame, image=self.profile_image, bg='white', borderwidth=0)
        self.profile_img.place(x=5, y=5)

        img2 = Image.open(PATH_IMAGE_SETTINGS)
        img2 = img2.resize((70, 70), Image.ANTIALIAS)
        self.settings_image = ImageTk.PhotoImage(img2)
        self.settings_img = Label(account_frame, image=self.settings_image, bg="#57a1f8", borderwidth=0)
        self.settings_img.place(x=1645, y=15)
        self.settings_img.bind("<Button-1>", self.edit_user)

        img3 = Image.open(PATH_IMAGE_BACK_BUTTON)
        img3 = img3.resize((100, 100), Image.ANTIALIAS)
        self.back_image = ImageTk.PhotoImage(img3)
        self.back_img = Label(account_frame, image=self.back_image, bg="#57a1f8", borderwidth=0)
        self.back_img.place(x=1720, y=0)
        self.back_img.bind("<Button-1>", self.close)

        self.profile_name = Label(
            account_frame, text="", fg='white', bg='#57a1f8',
            font=('Microsoft YaHei UI Light', 24, 'bold')
        )
        self.profile_name.place(x=120, y=25)

        section_buttons_frame = Frame(self, width=1920, height=50, bg="#57a1f8")
        section_buttons_frame.grid(row=1, column=0, sticky='nw')
        self.collections_btn = Button(
            section_buttons_frame, width=30, text='Collections', bg='white', fg='black', border=0,
            font=('Microsoft YaHei UI Light', 15), command=lambda: self.load_collections()
        )
        self.collections_btn.grid(row=0, column=0)
        self.deals_btn = Button(
            section_buttons_frame, width=30, text='My deals', bg='white', fg='black', border=0,
            font=('Microsoft YaHei UI Light', 15), command=lambda: self.load_deals()
        )
        self.deals_btn.grid(row=0, column=1)
        self.search_page_btn = Button(
            section_buttons_frame, width=30, text='Search', bg='white', fg='black', border=0,
            font=('Microsoft YaHei UI Light', 15), command=lambda: self.show_search_tab()
        )
        self.search_page_btn.grid(row=0, column=2)
        self.statistics_btn = Button(
            section_buttons_frame, width=30, text='Statistics', bg='white', fg='black', border=0,
            font=('Microsoft YaHei UI Light', 15), command=lambda: self.show_statistics_tab()
        )
        self.statistics_btn.grid(row=0, column=3)

        self.collections = None
        self.collections_frame = None
        self.collection_manager = None

        self.deals_var = StringVar()
        self.deals_combobox = ttk.Combobox(self, width=40, textvariable=self.deals_var, state='readonly')
        self.deals_combobox.configure(values=('Active deals', 'Previous deals'))
        self.deals_combobox.current(0)
        self.deals_combobox.grid(row=3, column=0, padx=(20, 20), pady=(20, 20), sticky="w")
        self.deals_combobox.grid_remove()
        self.deals_var.trace('w', self.load_deals)
        self.deals = None
        self.results = None

        self.search_top_frame = Frame(self, width=1920, height=100, bg="white")
        Label(
            self.search_top_frame, text="Search user/collection", fg='black', bg='white', justify=LEFT,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=0, sticky="we", padx=(20, 20))
        self.search_entry = EntryWithPlaceholder(self.search_top_frame, placeholder='Name')
        self.search_entry.grid(row=1, column=0, sticky="sw", padx=(20, 20))
        br = Frame(self.search_top_frame, width=400, height=2, bg='black')
        br.grid(row=2, column=0, sticky="nw", pady=(0, 20), padx=(20, 20))
        self.search_btn = Button(
            self.search_top_frame, width=30, pady=7, text='Search', bg='#57a1f8', fg='white', border=0,
            font=('Microsoft YaHei UI Light', 11, 'bold'), command=lambda: self.search_by_name()
        )
        self.search_btn.grid(row=3, column=0, sticky='we', padx=(20, 20))
        Label(
            self.search_top_frame, text="OR", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=1, sticky='we', padx=(20, 20))
        Label(
            self.search_top_frame, text="Search by token details", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=2, sticky='we', padx=(20, 20))
        self.search_token_var = StringVar()
        self.search_token_combobox = ttk.Combobox(self.search_top_frame, width=40, textvariable=self.search_token_var,
                                                  values=('Coin', 'Banknote'), state='readonly')
        self.search_token_combobox.current(0)
        self.search_token_combobox.grid(row=1, column=2, pady=(20, 0), sticky="we", padx=(20, 20))
        self.search_token_btn = Button(
            self.search_top_frame, width=30, pady=7, text='Search by details', bg='#57a1f8', fg='white', border=0,
            font=('Microsoft YaHei UI Light', 11, 'bold'), command=lambda: self.search_by_details()
        )
        self.search_token_btn.grid(row=3, column=2, sticky='we', padx=(20, 20))
        self.search_top_frame.grid(row=5, column=0, sticky='we')

        self.statistics_frame = Frame(self, width=1920, height=100, bg="white")
        self.statistics_var = StringVar()
        self.statistics_combobox = ttk.Combobox(
            self.statistics_frame, width=40, textvariable=self.statistics_var,
            values=(STATISTICS_USER, STATISTICS_USER_TOP, STATISTICS_COIN, STATISTICS_COIN_TOP,
                    STATISTICS_BANKNOTE, STATISTICS_BANKNOTE_TOP, STATISTICS_TOTAL),
            state='readonly'
        )
        self.statistics_combobox.current(0)
        self.statistics_combobox.grid(row=1, column=0, pady=(20, 0), sticky="we", padx=(20, 20))
        self.statistics_entry = EntryWithPlaceholder(self.statistics_frame, width=40, placeholder='Value')
        self.statistics_entry.grid(row=2, column=0, sticky="sw", padx=(20, 20), pady=(20, 0))
        br = Frame(self.statistics_frame, width=400, height=2, bg='black')
        br.grid(row=3, column=0, sticky="nw", pady=(0, 20), padx=(20, 20))
        self.show_statistics_btn = Button(
            self.statistics_frame, width=30, pady=7, text='Show', bg='#57a1f8', fg='white', border=0,
            font=('Microsoft YaHei UI Light', 11, 'bold'), command=lambda: self.show_statistics()
        )
        self.show_statistics_btn.grid(row=4, column=0, sticky='we', padx=(20, 20))
        self.statistics_frame.grid(row=7, column=0, sticky='news')

        self.user_statistics_frame = Frame(self.statistics_frame, bg="white")
        Label(
            self.user_statistics_frame, text="Income", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=0, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.user_statistics_frame, text="Spending", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=1, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.user_statistics_frame, text="Deals", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=2, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.user_statistics_frame, text="Tokens", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=3, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.user_statistics_frame, text="Collections", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=4, sticky="we", padx=(20, 20), pady=(20, 20))

        self.user_statistics_income = Label(
            self.user_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.user_statistics_income.grid(row=1, column=0, sticky="we", padx=(20, 20), pady=(20, 20))
        self.user_statistics_spending = Label(
            self.user_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.user_statistics_spending.grid(row=1, column=1, sticky="we", padx=(20, 20), pady=(20, 20))
        self.user_statistics_deals = Label(
            self.user_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.user_statistics_deals.grid(row=1, column=2, sticky="we", padx=(20, 20), pady=(20, 20))
        self.user_statistics_tokens = Label(
            self.user_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.user_statistics_tokens.grid(row=1, column=3, sticky="we", padx=(20, 20), pady=(20, 20))
        self.user_statistics_collections = Label(
            self.user_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.user_statistics_collections.grid(row=1, column=4, sticky="we", padx=(20, 20), pady=(20, 20))
        self.user_statistics_frame.grid(row=5, column=0, sticky='we')

        self.user_statistics_top_frame_list = None

        self.token_statistics_frame = Frame(self.statistics_frame, bg="white")
        Label(
            self.token_statistics_frame, text="Total spending", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=0, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.token_statistics_frame, text="Owners", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=1, sticky="we", padx=(20, 20), pady=(20, 20))

        self.token_statistics_total_spending = Label(
            self.token_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.token_statistics_total_spending.grid(row=1, column=0, sticky="we", padx=(20, 20), pady=(20, 20))
        self.token_statistics_owners = Label(
            self.token_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.token_statistics_owners.grid(row=1, column=1, sticky="we", padx=(20, 20), pady=(20, 20))

        self.token_statistics_frame.grid(row=6, column=0, sticky='we')

        self.tokens_statistics_top_frame_list = None

        self.canvas = None

        self.total_statistics_frame = Frame(self.statistics_frame, bg="white")
        Label(
            self.total_statistics_frame, text="Income", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=0, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.total_statistics_frame, text="Spending", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=1, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.total_statistics_frame, text="Deals", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=2, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.total_statistics_frame, text="Tokens", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=3, sticky="we", padx=(20, 20), pady=(20, 20))
        Label(
            self.total_statistics_frame, text="Collections", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        ).grid(row=0, column=4, sticky="we", padx=(20, 20), pady=(20, 20))

        self.total_statistics_income = Label(
            self.total_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.total_statistics_income.grid(row=1, column=0, sticky="we", padx=(20, 20), pady=(20, 20))
        self.total_statistics_spending = Label(
            self.total_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.total_statistics_spending.grid(row=1, column=1, sticky="we", padx=(20, 20), pady=(20, 20))
        self.total_statistics_deals = Label(
            self.total_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.total_statistics_deals.grid(row=1, column=2, sticky="we", padx=(20, 20), pady=(20, 20))
        self.total_statistics_tokens = Label(
            self.total_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.total_statistics_tokens.grid(row=1, column=3, sticky="we", padx=(20, 20), pady=(20, 20))
        self.total_statistics_collections = Label(
            self.total_statistics_frame, text="", fg='black', bg='white', justify=CENTER,
            font=('Microsoft YaHei UI Light', 11, 'bold')
        )
        self.total_statistics_collections.grid(row=1, column=4, sticky="we", padx=(20, 20), pady=(20, 20))
        self.total_statistics_frame.grid(row=7, column=0, sticky='we')

    def load(self):
        self.controller.geometry("1920x1080+0+0")
        self.controller.state('zoomed')
        self.username = self.controller.username
        self.load_consumer_info()
        self.load_collections()
        print("Home Page page loaded")

    def load_consumer_info(self):
        self.profile_name.configure(text=self.username)
        rs = connection.get_consumer(self.username)
        if rs[3] is not None:
            img = image_from_blob(rs[3])
        else:
            img = Image.open(PATH_IMAGE_EMPTY_PROFILE)
        img = img.resize((90, 90), Image.ANTIALIAS)
        self.profile_image = ImageTk.PhotoImage(img)
        self.profile_img.configure(image=self.profile_image)

    def load_collections(self):
        self.remove_elements()
        rs = connection.get_collections_preview(self.username)
        collections = [
            PreviewCollection(self, ("New collection", None, None), CollectionType.CREATE_NEW)
        ]
        for collection in rs:
            collections.append(PreviewCollection(self, collection, CollectionType.COLLECTION))

        self.collections = GridManager(
            self, column_count=7, row_width=200, column_width=200, width=1920, height=800, objects=collections
        )
        self.collections.grid(row=2, column=0, sticky='news')

    def show_search_tab(self):
        self.remove_elements()
        self.search_top_frame.grid()

    def show_statistics_tab(self):
        self.remove_elements()
        self.statistics_frame.grid()
        self.statistics_entry.configure(state=NORMAL)
        self.statistics_combobox.configure(state="readonly")
        self.statistics_combobox.current(0)
        self.statistics_entry.set_text(self.username)
        self.show_statistics()

    def show_statistics(self):
        self.remove_elements_statistics()
        stat = self.statistics_var.get()
        is_admin = connection.is_admin(self.username)
        if not is_admin:
            self.statistics_entry.configure(state=DISABLED)
            self.statistics_combobox.configure(state=DISABLED)
        if stat == STATISTICS_USER:
            self.user_statistics_frame.grid()
            self.load_statistics_user()
        elif stat == STATISTICS_USER_TOP:
            self.load_statistics_user_top()
        elif stat == STATISTICS_COIN:
            self.token_statistics_frame.grid()
            self.load_statistics_token(is_coin=True)
        elif stat == STATISTICS_COIN_TOP:
            self.load_statistics_token_top(is_coin=True)
        elif stat == STATISTICS_BANKNOTE:
            self.token_statistics_frame.grid()
            self.load_statistics_token(is_coin=False)
        elif stat == STATISTICS_BANKNOTE_TOP:
            self.load_statistics_token_top(is_coin=False)
        elif stat == STATISTICS_TOTAL:
            self.total_statistics_frame.grid()
            self.load_statistics_total()

    def load_statistics_user(self):
        user_name = self.statistics_entry.get_text()
        rs = connection.get_user_statistics(user_name)
        self.user_statistics_income.configure(text=rs[0])
        self.user_statistics_spending.configure(text=rs[1])
        self.user_statistics_deals.configure(text=rs[2])
        self.user_statistics_tokens.configure(text=rs[3])
        self.user_statistics_collections.configure(text=rs[4])

    def load_statistics_user_top(self):
        inp = self.statistics_entry.get_text().split(',')
        if len(inp) != 2 and len(inp) != 4:
            showwarning("Warning", "Incorrect input detected")
        elif len(inp) == 2:
            month_begin = 202201
            month_end = 210001
        elif len(inp) == 4:
            month_begin = int(inp[2])
            month_end = int(inp[3])
        rs = connection.get_user_statistics_top(inp[0], int(inp[1]), month_begin, month_end)
        users = list()
        heading = ("Name", "Income", "Spending", "Deals", "Tokens")
        users.append(StatisticsConsumerRow(heading))
        for user in rs:
            users.append(StatisticsConsumerRow(user))

        self.user_statistics_top_frame_list = ListManager(
            self, row_width=100, width=1920, height=700, objects=users
        )
        self.user_statistics_top_frame_list.grid(row=8, column=0, sticky='news')

    def load_statistics_token(self, is_coin):
        try:
            token_id = int(self.statistics_entry.get_text())
        except ValueError:
            showwarning("Warning", "Incorrect input")
            return
        if is_coin:
            rs = connection.get_coin_statistics(token_id)
        else:
            rs = connection.get_banknote_statistics(token_id)
        self.token_statistics_total_spending.configure(text=rs[0])
        self.token_statistics_owners.configure(text=rs[1])

        x = ['1', '2', '3', '4', '5']
        if is_coin:
            y = list_tuple_to_list(connection.get_coin_previous_prices(token_id, 5))
        else:
            y = list_tuple_to_list(connection.get_banknote_previous_prices(token_id, 5))

        maximum = float(max(y))
        y = [int(item / maximum * 100.0) for item in y]
        y.reverse()
        while len(y) < len(x):
            y.insert(0, 0)
        fig = plt.figure(figsize=(5, 5))
        plt.bar(x=x, height=y)

        # specify the window as master
        self.canvas = FigureCanvasTkAgg(fig, master=self)
        self.canvas.draw()
        self.canvas.get_tk_widget().grid(row=10, column=0)

    def load_statistics_token_top(self, is_coin):
        inp = self.statistics_entry.get_text().split(',')
        if is_coin:
            rs = connection.get_coin_statistics_top(inp[0], int(inp[1]))
        else:
            rs = connection.get_banknote_statistics_top(inp[0], int(inp[1]))
        tokens = list()
        heading = (None, "Token id", "Total spending", "Owners")
        tokens.append(StatisticsTokenRow(heading, is_heading=True))
        for user in rs:
            tokens.append(StatisticsTokenRow(user))

        self.tokens_statistics_top_frame_list = ListManager(
            self, row_width=100, width=1920, height=700, objects=tokens
        )
        self.tokens_statistics_top_frame_list.grid(row=9, column=0, sticky='news')

    def load_deals(self, *args):
        self.remove_elements()
        self.deals_combobox.grid()
        is_active = self.deals_var.get() == 'Active deals'
        rs = connection.get_user_deals_coin_preview(self.username, is_active)
        deals = list()
        for deal in rs:
            deals.append(PreviewDeal(self, deal, is_active, is_coin=True))
        rs = connection.get_user_deals_banknote_preview(self.username, is_active)
        for deal in rs:
            deals.append(PreviewDeal(self, deal, is_active, is_coin=False))

        self.deals = ListManager(
            self, row_width=200, width=1920, height=750, objects=deals
        )
        self.deals.grid(row=4, column=0, sticky='news')

    def create_new_collection(self):
        new_collection_window = WindowCollectionCreateEdit(self, WindowMode.CREATE_NEW)
        new_collection_window.grab_set()

    def load_collection(self, collection_id):
        self.controller.collection_id = collection_id
        self.controller.show_frame("PageCollection")

    def load_coin_deal(self, coin_id):
        deal_window = WindowTokenDeal(self, coin_id, is_coin=True)
        deal_window.grab_set()

    def load_banknote_deal(self, banknote_id):
        deal_window = WindowTokenDeal(self, banknote_id, is_coin=False)
        deal_window.grab_set()

    def after_w_token_deal(self, *args):
        self.load_deals()

    def after_w_banknote_deal(self, *args):
        self.load_deals()

    def remove_elements(self):
        if self.collections is not None:
            self.collections.grid_remove()
        self.deals_combobox.grid_remove()
        if self.deals is not None:
            self.deals.grid_remove()
        self.search_top_frame.grid_remove()
        if self.results is not None:
            self.results.grid_remove()
        self.statistics_frame.grid_remove()
        if self.user_statistics_top_frame_list is not None:
            self.user_statistics_top_frame_list.grid_remove()
        if self.tokens_statistics_top_frame_list is not None:
            self.tokens_statistics_top_frame_list.grid_remove()
        if self.canvas is not None:
            self.canvas.get_tk_widget().grid_remove()

    def remove_elements_statistics(self):
        self.user_statistics_frame.grid_remove()
        self.total_statistics_frame.grid_remove()
        if self.user_statistics_top_frame_list is not None:
            self.user_statistics_top_frame_list.grid_remove()
        self.token_statistics_frame.grid_remove()
        if self.tokens_statistics_top_frame_list is not None:
            self.tokens_statistics_top_frame_list.grid_remove()
        if self.canvas is not None:
            self.canvas.get_tk_widget().grid_remove()

    def search_by_name(self):
        self.show_search_tab()
        input_name = self.search_entry.get()
        users = connection.search_users(input_name)
        collections = connection.search_collections(input_name)
        search_results = list()
        for user in users:
            search_results.append(SearchUser(self, user))
        for coll in collections:
            search_results.append(SearchCollection(self, coll))

        self.results = ListManager(
            self, row_width=200, width=1920, height=750, objects=search_results
        )
        self.results.grid(row=6, column=0, sticky='news', pady=(20, 0))

    def search_by_details(self):
        if self.search_token_var.get() == 'Coin':
            window = WindowCoinCreateEditSearch(self, window_mode=WindowMode.SEARCH, coin_id=None,
                                                offer_username=self.username)
        else:
            window = WindowBanknoteCreateEditSearch(self, window_mode=WindowMode.SEARCH, banknote_id=None,
                                                    offer_username=self.username)
        window.grab_set()

    def load_search_user(self, user_id):
        self.show_search_tab()
        collections = connection.search_user_collections(user_id)
        search_results = list()
        for coll in collections:
            search_results.append(SearchCollection(self, coll))

        self.results = ListManager(
            self, row_width=200, width=1920, height=750, objects=search_results
        )
        self.results.grid(row=6, column=0, sticky='news', pady=(20, 0))

    def load_search_collection(self, collection_id):
        self.show_search_tab()
        coins = connection.search_collection_coins(collection_id)
        search_results = list()
        for coin in coins:
            search_results.append(SearchToken(self, coin, is_coin=True))

        banknotes = connection.search_collection_banknotes(collection_id)
        for banknote in banknotes:
            search_results.append(SearchToken(self, banknote, is_coin=False))

        self.results = ListManager(
            self, row_width=200, width=1920, height=750, objects=search_results
        )
        self.results.grid(row=6, column=0, sticky='news', pady=(20, 0))

    def load_search_coin(self, coin_id):
        coin_window = WindowCoinCreateEditSearch(self, window_mode=WindowMode.SEARCH_RESULT, coin_id=coin_id,
                                                 offer_username=self.username)
        coin_window.grab_set()

    def load_search_banknote(self, banknote_id):
        banknote_window = WindowBanknoteCreateEditSearch(self, window_mode=WindowMode.SEARCH_RESULT,
                                                         banknote_id=banknote_id, offer_username=self.username)
        banknote_window.grab_set()

    def set_search_results(self, rs, is_coins):
        self.show_search_tab()
        search_results = list()
        for res in rs:
            search_results.append(SearchToken(self, res, is_coin=is_coins))

        self.results = ListManager(
            self, row_width=200, width=1920, height=750, objects=search_results
        )
        self.results.grid(row=6, column=0, sticky='news', pady=(20, 0))

    def edit_user(self, *args):
        window = WindowConsumerEdit(self)
        window.grab_set()

    def close(self, e):
        self.username = None
        self.controller.username = None
        self.controller.title('Login')
        self.controller.geometry('925x500+300+200')
        self.controller.state('normal')
        self.controller.show_frame("PageLogin")

    def load_statistics_total(self):
        inp = self.statistics_entry.get_text().split(',')
        rs = connection.get_total_statistics(int(inp[0]), int(inp[1]))
        self.total_statistics_income.configure(text=rs[0])
        self.total_statistics_spending.configure(text=rs[1])
        self.total_statistics_deals.configure(text=rs[2])
        self.total_statistics_tokens.configure(text=rs[3])
        self.total_statistics_collections.configure(text=rs[4])


def extractSodTranslations(item):
	"""
	Sod Translations
	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None

	tagmap = [
		('Ore to Kawazu-san no Isekai Hourouki',       'Ore to Kawazu-san no Isekai Hourouki',                      'translated'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	titlemap = [
		('Ore to Kawazu-san no Isekai Hourouki – ',  '	Ore to Kawazu-san no Isekai Hourouki',      'translated'),
	]

	for titlecomponent, name, tl_type in titlemap:
		if titlecomponent.lower() in item['title'].lower():
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


t2 = 0
def gridTraveler(m,n):
    global t2
    t2 += 1
    if m == 0 or n == 0:
        return 0
    elif m == 1 or n == 1:
        return 1
    else:
        return gridTraveler(m - 1, n) + gridTraveler(m, n - 1)

t = 0
def gridTravMemo(m, n, cache = {}):
    global t
    k = str(m) + ',' + str(n)
    if k in cache:
        return cache[k]
    else:
        t += 1
        if m == 0 or n == 0:
            return 0
        elif m == 1 or n == 1:
            return 1
        else:
            cache[k] = gridTravMemo(m - 1, n, cache) + gridTravMemo(m, n - 1, cache)
            return cache[k]

print(gridTraveler(4, 3))
print(f'times: {t2}')
print(gridTravMemo(10, 10))
print(f'times: {t}')

def gridTraveler2(m, n):
    dp = [[0 for j in range(n + 1)] for i in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if i == 1 or j == 1:
                dp[i][j] = 1
            else:
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
    print(dp)
    return dp[m][n]

print(gridTraveler2(3, 3))


import boto3, os
#from app.abcdef import BUCKET_NAME, BUCKET_KEY

BUCKET_NAME = os.environ.get('PYTHONDEV_BUCKET_NAME') or 'tkusiak-s3-test' #'tkusiak-pyt'
BUCKET_KEY = os.environ.get('PYTHONDEV_BUCKET_KEY', '')

bucket = boto3.resource('s3').Bucket(BUCKET_NAME)
s3_client = boto3.client('s3')

class StorageError(Exception):
    pass

def get_presigned_url(object_name):
    #object_key = f'{BUCKET_KEY}/{object_name}'
    presigned_url = s3_client.generate_presigned_url('get_object',
                                                     Params={'Bucket': BUCKET_NAME,
                                                             'Key': object_name},
                                                     ExpiresIn=3600)
    return presigned_url

def generate_presigned_upload_url():
        return s3_client.generate_presigned_post(
            'tkusiak-s3-test',
            '${filename}',
        )

def list_s3_files():
    return bucket.objects.all()

# def upload_file(content, object_name):
#     object_key = f'{BUCKET_KEY}/{object_name}'
#     try:
#         bucket.put_object(Key=object_key, Body=content)
#     except ClientError:
#         raise StorageError
#     return object_key