#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gtts import gTTS
from playsound import playsound
import os
from datetime import datetime
from PyDictionary import PyDictionary
from nltk.corpus import wordnet

now_UTC_hr = datetime.utcnow().hour # Get the UTC time
print('The UTC Time is ', datetime.utcnow())
dictionary=PyDictionary()
language = 'en'

path_of_file = 'C:/Users/khushal/Pictures/temp.txt'
file = open(path_of_file,'w')

def gratitude_wish(word,language):
    print(word)
    myobj = gTTS(text=word, lang=language, slow=False)
    # Saving the converted audio in a mp3 file named
    path_of_file_tst = 'C:/Users/khushal/Documents/Python Scripts/gratiude.mp3'
    # Saving the converted audio in a mp3 file named
    myobj.save(path_of_file_tst)
    # Playing the converted file
    if os.path.exists(path_of_file_tst):
        playsound(path_of_file_tst)
        os.remove(path_of_file_tst)
    else:
        print("The file does not exist")

def gratiude_language(language):
    if now_UTC_hr >= 4 and now_UTC_hr < 12:
        print("It's time to say, Good Morning")
        gratiude = 'Good Morning'
        gratitude_wish(gratiude, language)
    elif now_UTC_hr >= 12 and now_UTC_hr < 17:
        print("It's time to say, Good Afternoon")
        gratiude = 'Good Afternoon'
        gratitude_wish(gratiude, language)
    elif now_UTC_hr >= 17 and now_UTC_hr <= 21:
        print("It's time to say, Good Evening")
        gratiude = 'Good Evening'
        gratitude_wish(gratiude, language)
    elif now_UTC_hr > 21:
        print("It's time to sleep, Good Night")
        gratiude = 'Good Night'
        gratitude_wish(gratiude, language)

gratiude_language(language)

synonyms = []
antonyms = []

#keyword_for_synonyms_antonyms = input("Enter the keyword for in which you want synonyms & antonyms = \n")
keyword_for_synonyms_antonyms = "bring"

def word_for_synonyms_antonyms(keyword_for_synonyms_antonyms):
    print('keyword_for_synonyms_antonyms := ', keyword_for_synonyms_antonyms)
    #to get synonyms and antonyms
    for syn in wordnet.synsets(keyword_for_synonyms_antonyms):
        for l in syn.lemmas():
            synonyms.append(l.name())
            if l.antonyms():
                antonyms.append(l.antonyms()[0].name())

    #print(set(synonyms))
    synonyms_words =set(synonyms)
    synonyms_words_dict = dict()
    pos_l1 = set()
    for words in synonyms_words:
        for tmp in wordnet.synsets(words):
            if tmp.name().split('.')[0] == words:
                pos_l1.add(tmp.pos())
        synonyms_words_dict[words] = pos_l1
    #print(set(antonyms))
    antonyms_words =set(antonyms)
    antonyms_words_dict = dict()
    pos_l2 = set()
    for words in antonyms_words:
        for tmp in wordnet.synsets(words):
            if tmp.name().split('.')[0] == words:
                pos_l2.add(tmp.pos())
        antonyms_words_dict[words] = pos_l2

    return synonyms_words_dict,antonyms_words_dict

w = keyword_for_synonyms_antonyms
pos_all = dict()
pos_l = set()
for tmp in wordnet.synsets(w):
    if tmp.name().split('.')[0] == w:
        pos_l.add(tmp.pos())
pos_all[w] = pos_l

output_synonyms_words,output_antonyms_words = word_for_synonyms_antonyms(keyword_for_synonyms_antonyms)
print('output_synonyms_words = ',output_synonyms_words,'\noutput_antonyms_words = ', output_antonyms_words)

# using Pydictionary module
def word_with_meaning(word):
    meaning_of_word = dictionary.meaning(keyword_for_synonyms_antonyms)
    print(meaning_of_word.keys())
    meaning_of_word_google = dictionary.googlemeaning(keyword_for_synonyms_antonyms)
    print(meaning_of_word_google)
    for key in list(meaning_of_word.keys()):
        if key == 'Noun':
            meaning_of_word_Noun = meaning_of_word['Noun']
            return meaning_of_word_Noun, meaning_of_word_google
            break
            # print("Noun Meaning", meaning_of_word_Noun)
        elif key == 'Verb':
            meaning_of_word_Verb = meaning_of_word['Verb']
            return meaning_of_word_Verb, meaning_of_word_google
            break
            # print("Verb meaning", meaning_of_word_Verb)

meaning_of_word_Output,meaning_of_word_From_google = word_with_meaning(keyword_for_synonyms_antonyms)

def audible_meaning_of_word(value,word):
    if value.upper() == 'Y':
        print('-'*60)
        print('Listen it carefully !!')
        i =0
        for values in word:
            print(values)
            myobj = gTTS(text=values, lang=language, slow=False)
            i +=1
            # Saving the converted audio in a mp3 file named
            path_of_file_tst = 'C:/Users/khushal/Documents/Python Scripts/word_meaning' + str(i) + '.mp3'
            # Saving the converted audio in a mp3 file named
            myobj.save(path_of_file_tst)
            # Playing the converted file
            if os.path.exists(path_of_file_tst):
                playsound(path_of_file_tst)
                os.remove(path_of_file_tst)
            else:
                print("The file does not exist")

    elif value.upper() == 'N':
        print('-'*60)
        print('Displaying the result !!')
        for values in word:
            print(values)
        pass
    else:
        print("You've entered the incorrect value")
word_meaning = list(meaning_of_word_Output)
switch = 'y'
audible_meaning_of_word(switch,word_meaning)
switch = 'n'
audible_meaning_of_word(switch,word_meaning)
file.close()


import sys, copy, math, random, time, heapq

TURN = 0
LEARNED = 0
TYPE_SET = { 'CAST' : 0 , 'OPPONENT_CAST' : 1 , 'LEARN' : 2 , 'BREW' : 3 }
TYPE_CAST, TYPE_OPP_CAST, TYPE_LEARN, TYPE_BREW = 0 , 1 , 2 , 3

FUZZY_GET = {
    -5:0, -4:0, -3:0, -2:0 , -1: 0,
    0: 0,
    1: 1, 2: 1,
    3:2 , 4:2 , 5:2 ,
    6:3 , 7:3 , 8:3 , 9:3 ,
    10: 3, 11:3, 12:3, 13:3
}
FUZZY_MIN = ( 0 , 1 , 3 , 6 )
FUZZY_MAX = ( 0 , 2 , 5 , 9 )
FUZZY_STATE = len(FUZZY_MIN) ** 4

FUZZY_QUANTITY = {
    -6: 300, -5: 300, -4: 300, -3: 300, -2: 300, -1: 300,
    0: 0,
    1: 100, 2: 100,
    3: 200, 4: 200, 5: 200, 6: 200
}

_action_board_ = {}
_learn_board_ = []

_mine_board_ = []
_opp_board_ = []

_mine_agent_ = {}
_opp_agent_ = {}

f_id = lambda obj : obj[0]
f_type = lambda obj : obj[1]
f_ingred = lambda obj : obj[2:6]
f_gain = lambda obj : 1 * obj[2] + 2 * obj[3] + 3 * obj[4] + 4 * obj[5]
f_price = lambda obj : obj[6]
f_tome = lambda obj : obj[7]
f_tax = lambda obj : obj[8]
f_cast = lambda obj : obj[9]
f_repeat = lambda obj : obj[10]

f_state = lambda obj : obj[0:4]
f_quantity = lambda obj : sum(obj[0:4])
f_quality = lambda obj :  13 * (10 - sum(obj[0:4])) + 11 * obj[0] + 7 * obj[1] + 5 * obj[2] + 3 * obj[3]
f_score = lambda obj : obj[4]

def inv_findBrew( state1 , state2 ):
    _ = 0
    for k1, k2 in zip(state1,state2) :
        _ = _ + max( (-k2) - k1 , 0)
    return _

def inv_int2inv( i1 ) :
    _ = [ (i1) % 4 , (i1 >> 2) % 4 , (i1 >> 4) % 4 , (i1 >> 6) % 4 ]
    return _

def inv_inv2int( s1 ) :
    _ = sum([ i1 * (1 << i2) for i1,i2 in zip(s1,[0,2,4,6]) ])
    return _

k_map = {}

class LearnNeuron():

    def __init__(self,param):
        self.param = param

    def spell(self,state):
        _ = state[:]
        _[0] = state[0] - f_tome(self.param)
        if _[0] >= 0 :
            _[0] = _[0] + f_tax(self.param)
        return _

    def gain(self):
        return min( (f_tax(self.param) - f_tome(self.param)) , 4 )

    def __str__(self):
        return f'(learn:{f_id(self.param)})'

    def read(self):
        return f'LEARN {f_id(self.param)}'

class SpellNeuron():

    def __init__(self,param):
        self.param = param

    def spell(self,state):
        _ = state[:]
        for i in range(4):  _[i] = state[i] + f_ingred(self.param)[i]
        return _

    def gain(self):
        return 1 * self.param[2] + 2 * self.param[3] + 3 * self.param[4] + 4 * self.param[5]

    def __str__(self):
        return f'({f_id(self.param)})'

    def read(self):
        return f'CAST {f_id(self.param)}'

class RestNeuron():

    def __init__(self,param):
        self.param = None

    def __str__(self):
        return f'rest'

    def read(self):
        return f'REST'

class BrewNeuron():

    def __init__(self,param):
        self.param = param

    def spell(self,state):
        _ = state[:]
        for i in range(4):  _[i] = state[i] + f_ingred(self.param)[i]
        return _

    def gain(self):
        return f_price(self.param)

    def __str__(self):
        return f'(brew:{f_id(self.param)})'

    def read(self):
        return f'BREW {f_id(self.param)}'

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

class KanbanBoard():

    def __init__(self,clone):
        self.observer = []
        self.cast, self.state, self.learn = set(), [], []
        self.spell = [ [] for i1 in range(FUZZY_STATE) ]
        self.learned = []
        self.tolearnpositive = [ None ] * 4
        #self.tolearnpositive[0] = 1
        self.tolearnnegative = [ None ] * 4
        self.tolearnnegative[3] = 1
        if clone is not None:
            self._predict,  = copy.copy(clone._predict)
            self._memento = clone._memento
        else :
            self._predict, self._memento = None, None
            pass

    def predict(self):
        return self._predict[0]

    def update(self,state):
        self._predict.pop(0)

    @property
    def memento(self):
        if self._memento is None:   return self

        self.state = self._memento.state[:]
        self.spell = self._memento.spell[:]
        self.cast = copy.copy(self._memento.cast)
        pass
        self._predict = copy.copy(self._memento._predict)

    @memento.setter
    def memento(self,setter):
        self._memento.state = setter.state[:]
        self._memento.spell = setter.spell[:]
        self._memento.cast = copy.copy(setter.cast)
        pass
        self._memento._predict = copy.copy(setter._predict)

    def correction(self,state):
        pass

    def compute_4(self):
        _learn_id_, _learn_k1_ = -1,-1

        for i2 , _ in zip([0,1,2,3,4,5], self.learn[ 0 : min(self.state[0] + 1, 2) ]):

            if f_gain(_.param) > 0 :

                for i1, l1, l2 in zip([2,3,4,5],self.tolearnpositive,self.tolearnnegative) :

                    if l1 is None and f_repeat(_.param) == 1 and 4 > _.param[i1] > 0:
                        self.tolearnpositive[i1 - 2] = _
                        _learn_id_ = f_id(_.param)
                        _learn_k1_ = i2
                    if l2 is None and f_repeat(_.param) == 1 and -3 < _.param[i1] < 0:
                        self.tolearnnegative[i1 - 2] = _
                        _learn_id_ = f_id(_.param)
                        _learn_k1_ = i2

                if _learn_id_ != -1:
                    return ( _learn_id_ , _learn_k1_ )

        return ( -1 , -1 )

    def compute_3(self):
        s1 = self.state[:]
        t1 = self.spell[:]

        p1 = []
        #d1 = len(p1) + f_quality(s1)
        c1 = copy.copy(self.cast)
        d1 = f_quality(s1) + len(c1)

        resolve = []
        already = set()
        search_turn = 1

        already_add = already.add
        already_remove = already.remove
        heapq_heappush = heapq.heappush
        heapq_heappop = heapq.heappop

        already_add( ( 1 , d1 ) )
        heapq.heappush( resolve , ( 1 , d1 , s1 , t1 , c1 , p1 ) )

        soluce = []

        while len(resolve) > 0 and search_turn < 325 :
            search_turn = search_turn + 1

            g1 , d1 , s1 , t1 , c1 , p1 = heapq_heappop(resolve)

            already_remove( (g1,d1) )

            delete = []
            for update in self.observer:
                if update.check_2( self , g1 , s1 , p1 ) is not None :
                    delete.append( update )

            for update in delete :
                self.detach_compute(update)

            if len(self.observer) == 0 :
                break

            if g1 > 30 :    break

            i1 = inv_inv2int( [ FUZZY_GET[i1] for i1 in f_state(s1) ] )

            a1 = t1[i1]
            if g1 == 1 :
                a1 = self.learn[ 0 : s1[0] + 1 ] + t1[i1]

            for _ in a1 :

                next_g1, next_d1, next_s1, next_t1, next_c1, next_p1 = g1, d1, s1, t1, c1, p1

                _in_repeat_ = False

                while _ in a1:

                    next_s1 = _.spell(next_s1)

                    next_p1 = next_p1[:]
                    next_p1.append( _ )

                    if _in_repeat_ == True :

                        next_g1 = next_g1 - _.gain()

                        next_d1 = f_quality(next_s1) + len(next_c1)

                    else :

                        next_g1 = next_g1 + (5 - _.gain() )
                        next_c1 = copy.copy(next_c1)

                        if _ in next_c1 :
                            next_g1 = next_g1 + 5
                            next_c1 = set()
                        elif f_type(_.param) == 2 :
                            pass
                        else:
                            next_c1.add(_)

                        next_d1 = f_quality(next_s1) + len(next_c1)

                    if (next_g1,next_d1) not in already and sum(next_s1[0:4]) <= 10 :

                        next_t1 = next_t1
                        if f_type(_.param) == 2 :
                            next_t1 = self.setup_7( _ , next_t1 )

                        already_add( (next_g1, next_d1) )
                        heapq_heappush( resolve , ( next_g1 , next_d1 , next_s1 , next_t1 , next_c1 , next_p1 ) )

                    if f_type(_.param) != 2 and f_repeat(_.param) == 1 :

                        i1 = inv_inv2int( [ FUZZY_GET[i1] for i1 in f_state(next_s1) ] )

                        a1 = next_t1[i1]

                        _in_repeat_ = True

                    else:
                        break

    def setup_4(self,state):
        self.state = state[:]

    def setup_6(self, learn):
        self.learn = learn[:]

    def setup_5(self,spell):
        self.spell = []
        for i1 in range(FUZZY_STATE):
            self.spell.append( [] )
            s1 = inv_int2inv(i1)

            for _ in spell.values():

                min1 = [ FUZZY_MIN[i1] for i1 in s1 ]
                max1 = [ FUZZY_MAX[i1] for i1 in s1 ]

                min1 = _.spell( min1 )
                min1 = sum([1 for i1 in min1 if i1 < 0 ])

                max2 = _.spell( max1 )
                max2 = sum(max2)

                if min1 == 0 and max2 <= 10:
                    self.spell[i1].append(_)

    def setup_8(self,spell):
        if spell in self.learned :
            return
        else :
            self.learned.append(spell)

        for i1 in range(FUZZY_STATE):
            s1 = inv_int2inv(i1)

            _ = spell

            min1 = [ FUZZY_MIN[i1] for i1 in s1 ]
            max1 = [ FUZZY_MAX[i1] for i1 in s1 ]

            min1 = _.spell( min1 )
            min1 = sum([1 for i1 in min1 if i1 < 0 ])

            max2 = _.spell( max1 )
            max2 = sum(max2)

            if min1 == 0 and max2 <= 10:
                self.spell[i1].append(_)

    def setup_7( self , spell , tome ):
        next_t1 = [ [] ] * FUZZY_STATE
        _ = list(spell.param)
        _[1] = 0 # Warning not okay in case opponent
        _ = SpellNeuron( tuple(_))
        for i1, t1 in zip( range(FUZZY_STATE) , tome):
            s1 = inv_int2inv(i1)

            min1 = [ FUZZY_MIN[i1] for i1 in s1 ]
            max1 = [ FUZZY_MAX[i1] for i1 in s1 ]

            min1 = _.spell( min1 )
            min1 = sum([1 for i1 in min1 if i1 < 0 ])

            max2 = _.spell( max1 )
            max2 = sum(max2)

            next_t1[ i1 ] = t1 [:]
            if min1 == 0 and max2 <= 10:
                next_t1[i1].append(_)

        return next_t1

    def attach_compute(self,instance):
        self.observer.append(instance)

    def detach_compute(self,instance):
        if instance in self.observer:
            self.observer.remove(instance)

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

class AgentBoard():

    def __init__(self,clone):
        if clone is not None:
            self.nb_ingred,self.nb_match,self.price = clone.nb_ingred,clone.nb_match,clone.price
            self.state, self.cast = clone.state, clone.cast
            self.action, self.down, self.spell = clone.action, clone.down, clone.spell
            self.k = clone.k
        else :
            self.nb_ingred,self.nb_match,self.price = 0, 0, 0
            self.state, self.cast = [], set()
            self.action, self.down, self.spell = None, None, []
            self.k = 999

        self._predict = copy.copy(clone._predict) if clone is not None else []
        self._memento = clone._memento if clone is not None else self

    def compute_2(self):
        d1 = set()
        _ = []

        for p1 in self._predict:
            if p1 not in d1:
                _.append(p1)
                d1.add(p1)
            else:
                _.append( RestNeuron(None) )
                _.append(p1)
                d1 = set()
                d1.add(p1)

        _.append( self.action )

        self._predict = _

    def check_2( self , caller , gain , state , predict ):
        soluce = []
        if inv_findBrew( f_state(state) , f_ingred(self.action.param) ) == 0 :
            soluce = predict[:]
            soluce.append( self.action )
            pass

        else :
            return None

        self.k = max(gain,1)
        self._predict = soluce
        return self

    def reset_predict(self):
        self._predict = []
        self.k = 999

    def predict(self):
        return self._predict[0]

    def update(self,state):
        self._predict.pop(0)

    @property
    def memento(self):
        if self._memento is None:   return self

        pass

        self._predict = copy.copy(self._memento._predict)
        return self

    @memento.setter
    def memento(self,setter):
        self._memento.down = setter.down
        self._memento.spell = setter.spell
        self._memento.action = setter.action
        self._memento.state = setter.state[:]
        self._memento.cast = copy.copy(setter.cast)

        self._memento = copy.copy(setter)
        self._memento._predict = copy.copy(setter._predict)

    def correction(self,state):
        pass

k_2know = [ 2 , 3 , 4 , 12 , 13 , 14 , 15 , 16 ]

if __name__ == '__main__':

    _min_id_ = -1
    _min_len_ = math.inf

    _learn_id_ = TURN
    _learn_set_ = { 0 : -1 , 1 : -1 , 2 : -1 , 3 : -1 , 4 : -1 }

    _mine_ = KanbanBoard(None)

    while True:
        TURN = TURN + 1
        out = ''

        no_delete = []
        _learn_board_ = []
        for i in range( int(input()) ):
            _ = input().split()

            _[0], _[1], _[2:] = int(_[0]), TYPE_SET[_[1]], map(int,_[2:])

            if f_type(_) == TYPE_CAST :
                if f_id(_) not in _mine_agent_:
                    _mine_agent_[ f_id(_) ] =  SpellNeuron( tuple(_) )
                    _min_id_ = -1
                    _min_len_ = math.inf
                    for _ in _action_board_.values(): _._predict = []

            elif f_type(_) == TYPE_OPP_CAST :
                if f_id(_) not in _opp_agent_:
                    _opp_agent_[ f_id(_) ] = SpellNeuron( tuple(_) )

            elif f_type(_) == TYPE_LEARN :
                _learn_board_.append( LearnNeuron( tuple(_) ) )

            elif f_type(_) == TYPE_BREW and _[0] in _action_board_ :
                no_delete.append( _[0] )

            elif f_type(_) == TYPE_BREW :
                no_delete.append( _[0] )
                _action_board_ [ _[0] ] = AgentBoard(None)
                _action_board_[ _[0] ].action = BrewNeuron( tuple(_) )

        delete = [ _ for _ in _action_board_.keys() if _ not in no_delete ]
        for _ in delete:
            _min_id_ = -1
            _min_len_ = math.inf
            del _action_board_ [_]

        _mine_board_ = [int(j) for j in input().split()]
        _opp_board_ = [int(j) for j in input().split()]

        # SETUP
        _mine_.setup_4( _mine_board_ )
        _mine_.setup_6( _learn_board_ )
        if _learn_id_ != -1 :
            #_mine_.setup_5( _mine_agent_ )
            for _ in _mine_agent_.values():
                _mine_.setup_8( _ )

        # SETUP
        for _ in _action_board_.values():
            if len(_._predict) == 0 :
                #_.memento = _
                _.state = _mine_board_[:]
                _.cast = copy.copy(_mine_.cast)
                _mine_.attach_compute( _ )
            else :
                #
                s1 = _mine_board_[:]
                e1 = False
                for c1 in _._predict:
                    if f_type(c1.param) == 2 :
                        e1 = True
                        break

                    r1 = c1.spell(s1)
                    min1 = sum([1 for i1 in r1[0:4] if i1 < 0])
                    max1 = sum(r1[0:4])

                    if min1 > 0 or max1 > 10 :
                        e1 = True
                        break

                    s1 = r1

                if e1 == True:
                    #_.memento = _
                    _.state = _mine_board_[:]
                    _.cast = copy.copy(_mine_.cast)
                    _._predict, _.k = [] , 999
                    _mine_.attach_compute( _ )

        # SEARCH
        _learn_id_ = -1
        _learn_k1_ = -1

        for _learn_k1_, _ in zip([0,1,2,3],_learn_board_):

            if _mine_board_[0] < _learn_k1_:
                break

            if f_id(_.param) in k_2know:
                _learn_id_ = f_id(_.param)
                for k1, _ in _action_board_.items() :
                    _._predict = []
                    _mine_.detach_compute( _ )
                break

        if _learn_id_ == -1 :
            _learn_id_ , _learn_k1_ = _mine_.compute_4()

        if _learn_id_ != -1 :
            LEARNED = LEARNED + 1

        elif len(_mine_.observer) > 0 :
            _mine_.compute_3()

            _min_id_, _min_len_ = -1, -math.inf
            for k1, _ in _action_board_.items() :

                if len(_._predict) > 0 :
                    s1 = ( f_price(_.action.param) * 30 ) // _.k

                    if s1 > _min_len_:
                        _min_len_, _min_id_ = s1, k1

            if _min_id_ == -1 :
                pass

            elif f_type(_action_board_[_min_id_]._predict[0].param) == 2 :
                _learn_id_ = f_id(_action_board_[_min_id_]._predict[0].param)
                _learn_k1_ = next(iter([i1 for i1,_ in zip([0,1,2,3,4,5],_learn_board_) if f_id(_.param) == _learn_id_ ]))
                _action_board_[_min_id_].k = 1

        # OUT
        if _learn_id_ != -1 :

            _ = _learn_board_[_learn_k1_]

            print(_.read())

        elif _min_id_ != -1 :

            _ = _action_board_[_min_id_].predict()
            _action_board_[_min_id_].k = 1

            if _ in _mine_.cast :

                _mine_.cast = set()

                print('REST')

            elif f_repeat(_.param) == 1 :

                nb = 0
                for spell1 in _action_board_[_min_id_]._predict:
                    if _ == spell1 :
                        nb = nb + 1
                    else :
                        break

                print(f'{_.read()} {nb}')

                _mine_.cast.add( _ )

                for k1, a1 in _action_board_.items():

                    if k1 == _min_id_:
                        for i1 in range(nb):
                            a1.update(None)

                    else:
                        if _ in a1._predict :
                            a1._predict.remove(_)
                            a1.k = max( (a1.k - _.gain() ) , 1 )

            else :

                print(_.read())

                _mine_.cast.add( _ )

                for k1, a1 in _action_board_.items():

                    if k1 == _min_id_:
                        a1.update(None)
                    else:
                        if _ in a1._predict :
                            a1._predict.remove(_)
                            a1.k = max( (a1.k - _.gain() ) , 1 )

        else :

            s1 = _mine_.state[:]

            i1 = inv_inv2int( [ FUZZY_GET[i1] for i1 in f_state(s1) ] )

            t1 = _mine_.spell[:]

            max1 = -1
            keep1 = None
            for _ in t1[i1]:

                if _ in _mine_.cast: continue
                if _.gain() > max1: keep1 = _

            if keep1 is None :
                print('REST')
                _mine_.cast = set()
            else:
                print( keep1.read())
                _mine_.cast.add( keep1 )


from loguru import logger
import select
import utils.base as base
from conf.conf import *
from queue import Queue
import socket
import threading

class IOWorker:
    def __init__(self, inq, outq, buffers, lock):
        logger.debug("init server socket")
        self.m_sock = base.init_server_socket()
        self.epoll = select.epoll()
        self.m_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.epoll.register(self.m_sock.fileno(), select.EPOLLIN | select.EPOLLET)
        self.conns = {}
        self.inq = inq  # 入包
        self.outq = outq  # 出包
        self.buffers = buffers  # 用于处理粘包
        self.lock = lock

    def run(self):
        while True:
            epoll_lst = self.epoll.poll()
            for fd, ev in epoll_lst:
                logger.debug(f"e: {ev}, con {len(self.conns)}, 'inq/ouq' {len(self.inq)}/{len(self.outq)}")
                if fd == self.m_sock.fileno():
                    self.on_connect()
                elif ev & select.EPOLLOUT:
                    self.on_write(fd)
                elif ev & select.EPOLLIN:
                    self.on_read(fd)
                else:
                    self.on_close(fd)

    def on_connect(self):
        try:
            while True:
                conn, addr = self.m_sock.accept()
                conn.setblocking(0)
                self.epoll.register(conn.fileno(), select.EPOLLIN | select.EPOLLET)
                self.conns[conn.fileno()] = conn

                logger.debug(f"new connect {conn.getpeername()}")
                with self.lock:
                    self.inq[conn.fileno()] = bytearray()
                    self.outq[conn.fileno()] = bytearray()
                    self.buffers[conn.fileno()] = bytearray()
        except socket.error:
            pass

    def on_read(self, fd):
        logger.debug(f"new epoll in")
        conn = self.conns[fd]
        try:
            data = conn.recv(1024)
            if not len(data):
                self.on_close(fd)
                return
            while True:
                data += conn.recv(1024)
        except socket.error:
            pass
        logger.debug(f"read data {data}")
        msgs = data.split(DELIM)
        if len(msgs) == 0:  # 当前包不构成完整消息，与buffer拼接
            self.buffers[fd] = self.buffers[fd] + bytearray(data)
        else:
            for idx, msg in enumerate(msgs):
                if len(msg):
                    last = self.buffers.get(fd, bytearray())
                    if idx < len(msgs):  # 后面还有说明本段构成了完整消息
                        self.inq[fd] = last + bytearray(msg) + DELIM
                        self.buffers[fd] = bytearray()
                    else:
                        self.buffers[fd] = bytearray(msg)
        self.epoll.modify(fd, select.EPOLLOUT | select.EPOLLET)

    def on_write(self, fd):
        data = memoryview(self.outq[fd])
        if not len(self.outq[fd]):
            logger.debug("出包为空")
            self.epoll.modify(fd, select.EPOLLOUT | select.EPOLLET)
            return
        try:
            while len(data) > 0:
                cnt = self.conns[fd].send(data)
                data = data[cnt:]
        except socket.error:
            pass
        # self.conns[fd].sendall(self.outq[fd])
        # self.epoll.modify(fd, select.EPOLLIN | select.EPOLLET)
        self.on_close(fd)

    def on_close(self, fd): # todo 超时控制 用堆？链表？map？
        self.conns[fd].shutdown(socket.SHUT_RDWR)
        self.epoll.unregister(fd)
        self.conns[fd].close()
        del self.conns[fd]
        with self.lock:
            try:
                del self.outq[fd]
                del self.buffers[fd]
            except:
                pass


#общая хэш-таблица
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"] ["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}
print(graph)
#таблица созданий стоимостей
costs = {}
inf = float ("inf")
costs["a"] = 6
costs["b"] = 2
costs["fin"] = inf
#таблица родителей
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
#для избежания повторения
processed = []
#итоговый алгоритм
def find_node(costs):
    lowest_cost = inf
    lowest_cost_node = None
    for node in costs:
        cost = costs[node]
        if cost < lowest_cost and node not in processed:
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node
node = find_node(costs) #находим самый мелкий путь (до какого узла)
while node is not None:
    cost = costs[node] #его время
    neighbors = graph[node] #его соседи
    for i in neighbors.keys(): #перебираем соседей
        new_cost = cost + neighbors[i]
        if costs[i] > new_cost:
            costs[i] = new_cost
            parents[i] = node
    processed.append(node)
    node = find_node(costs) #находим следующий узел обработки (самый мелкий путь)
#выводим критический путь
i = "fin"
s = [i]
while i != "start":
    s.append("=>")
    s.append(parents[i])
    i = parents[i]
s.reverse()
print(s)
print(costs["fin"])

алгортим дейкстры.py

алгортим дейкстры.py


#!/usr/bin/env python3
#
# control the VBox virtual machines from command line
#
import subprocess
import sys

class VMS():

    def __init__(self):
        print("\t" + "="*28)
        if sys.platform.startswith('win'):
            self.base_cmd = 'C:/Program Files/Oracle/VirtualBox/VBoxManage.exe'
            self.pingopt = "-n"
            print("\t== vm-control for Windows ==")
        elif sys.platform.startswith('linux'):
            self.base_cmd = '/usr/bin/vboxmanage'
            self.pingopt = "-c"
            print("\t==  vm-control for Linux  ==")
        else:
            print('unable to determine platform')
            raise 'unknown'
        print("\t" + "="*28)

        # hold all the created VMs in VBox or
        # the current running VMs
        # it will repopulated based on user choice
        self.dict_vms = {}
        self.status = ""

    def getPingOpt(self):
        return self.pingopt

    def clear_state(self):
        self.dict_vms.clear()
        self.status = ""

    #
    # display VM name(s) on screen
    #
    def show_dict(self):
        for k, v in self.dict_vms.items():
            print("\t{}  {}".format(k, v))

    def execute_vms(self, cmd, show_cmd=True, show_result=True):
        command = [self.base_cmd] + cmd
        if show_cmd:
            print("[=] executing: {}".format(command))

        p1 = subprocess.Popen(command,
                                stderr = subprocess.STDOUT,
                                stdout = subprocess.PIPE)
        out, err = p1.communicate()
        if not out:
            self.status = err
            print("[=] error: {}".format(self.status) )
            return False
        else:
            self.status = out.decode('utf-8')
            if show_result:
                print("[=] success: \n{}".format(self.status) )
            return True

    def process_output(self, out):
        self.dict_vms.clear()
        # cur_vms = out.splitlines()
        count = 0
        for v in out.splitlines():
            count = count + 1
            # print("line: {}".format(v))
            # fetching VM name and removing surrounding double-quotes
            value = v.split(' {')[0].replace('"', '')
            self.dict_vms[count] = value
        self.show_dict()

    def list_all(self):
        command = ["list", "vms"]
        if self.execute_vms(command, show_cmd=True, show_result=False):
            self.process_output(self.status)
        else:
            # this is error condition
            self.dict_vms.clear()

    def list_running(self):
        command = ["list", "runningvms"]
        if self.execute_vms(command, show_cmd=True, show_result=False):
            self.process_output(self.status)
        else:
            # this is error condition
            self.dict_vms.clear()

    def get_choices(self, all=False):
        self.list_all() if all else self.list_running()

        # validates the choices enter
        # it will ignore any invalid choice
        nokeys = len(self.dict_vms.keys())
        text = "enter input <0 to exit>: "
        choices = list(int(v) for v in input(text).split() if int(v) <= nokeys )
        return choices if 0 not in choices else []

    def start_vm(self):
        for i in self.get_choices(all=True):
            vms = self.dict_vms[i]
            choice = input("start \"{}\" headless <y/n> [y]: ".format(vms))
            print("starting {}".format(vms))

            cmd = ["startvm", vms, "--type"]
            if choice == '' or choice == 'y' or choice =='Y':
                cmd.append("headless")
            elif choice == 'n' or choice == 'N':
                cmd.append("separate")
            else:
                print("invalid option")
                return
            self.execute_vms(cmd)

    def save_vm(self):
        for i in self.get_choices(all=False):
            cmd = ['controlvm', self.dict_vms[i], 'savestate']
            self.execute_vms(cmd, show_cmd=True, show_result=True)

    def restart_vm(self):
        for i in self.get_choices(all=False):
            cmd = ['controlvm', self.dict_vms[i], 'reset']
            self.execute_vms(cmd, show_cmd=True, show_result=True)

def getIPv4(ip):
    ipdefault = ['192', '168', '56', 'x']
    # make sure 'ip' don't start with '.'
    # if it does then remove leading '.'
    if (len(ip) == 0):
        # if no IPv4 provided, then ping default gw
        # for-loop inside join (at return call) will do 192, 168, 56 and append ip ie '1'
        # which will make it '192.168.56.1' ie default gw for vbox installation.
        ip = '1'
    else:
        ip = ip if ip[0] != '.' else ip[1:]
    # since there are at most '3' dots in IPv4
    return '.'.join( [ ipdefault[x] for x in range(0, 3 - ip.count('.')) ] + [ip] )

def ping_test(pingopt, num = 6):
    # valid inputs will be with or without leading '.'
    # [[[192.]168.]56.]40
    # 40 or .40               will become 192.168.56.40
    # 50.40 or .50.40         will become 192.168.50.40
    # 100.56.40 or .100.56.40 will become 192.100.56.40
    # 172.100.21.40           will become 172.100.21.40

    # getIPv4 will return ip as string
    ip = getIPv4( input('enter IPv4: ') )
    print(f'sending {num} ping packets')
    command = ['ping', pingopt, str(num), ip]
    print(command)
    subprocess.run(command, stderr = sys.stdout, stdout = sys.stdout)

def display_menu():
    print("\t1  ping test")
    print("\t2  show running vms")
    print("\t3  start vms")
    print("\t4  --empty--")
    print('\t5  save vms')
    print('\t6  restart vm')
    print('\t0  exit')

if __name__ == "__main__":
    vms = VMS()
    while True:
        display_menu()
        choice = int(input("enter input: "))
        if choice == 1:
            ping_test(vms.getPingOpt())
        elif choice == 2:
            vms.list_running()
        elif choice == 3:
            vms.start_vm()
        elif choice == 4:
            pass
            #vms.save_all_running()
        elif choice == 5:
            vms.save_vm()
        elif choice == 6:
            vms.restart_vm()
        else:
            print("exiting...\n")
            break
        choice = 0
        print("\n\n")

# --end--


from flask import request, jsonify, Response
from werkzeug.utils import secure_filename

from pathlib import Path
from datetime import datetime
from nonrepeat import nonrepeat_filename
import shutil

from . import app

filename = None

@app.route('/api/images/create', methods=['POST'])
def create_image():
    global filename

    if 'file' in request.files:
        image_path = Path(request.form.get('imagePath'))
        if image_path.suffix:
            image_path = image_path.parent
        image_path.mkdir(parents=True, exist_ok=True)

        file = request.files['file']
        filename = str(image_path.joinpath(secure_filename(file.filename)))
        filename = nonrepeat_filename(filename,
                                      primary_suffix=datetime.now().isoformat()[:10])
        file.save(filename)

        return jsonify({
            'filename': filename
        }), 201

    return Response(status=304)

@app.route('/api/images/rename', methods=['POST'])
def rename_image():
    global filename

    if filename is not None:
        new_filename = Path(request.get_json()['filename']).with_suffix(Path(filename).suffix)
        new_filename.parent.mkdir(parents=True, exist_ok=True)

        new_filename = new_filename.with_name(secure_filename(new_filename.name))
        new_filename = nonrepeat_filename(str(new_filename))

        shutil.move(filename, new_filename)
        filename = new_filename

        return jsonify({
            'filename': filename
        }), 201

    return Response(status=304)


infile = open("advent of code 2022/input_day5.txt", "r")
arr = []
for i in range(10):
    arr.append([])
count = 1
for line in infile:
    if(count==1):
        arr[1].append("C")
        arr[4].append("S")
        arr[5].append("H")
    elif(count==2):
        arr[1].append("F")
        arr[2].append("B")
        arr[4].append("C")
        arr[5].append("S")
        arr[7].append("W")
    elif(count==3):
        arr[1].append("B")
        arr[2].append("W")
        arr[4].append("W")
        arr[5].append("M")
        arr[6].append("S")
        arr[7].append("B")
    elif("[" in line):
        line = line[0:len(line)-1]
        parts = line.split("[")
        parts = parts[1:len(parts)]
        for i in range(len(parts)):
            arr[i+1].append(parts[i][0])
    # elif("move" in line):
    #     parts = line.split(" ")
    #     numtaken = int(parts[1])
    #     placetaken = int(parts[3])
    #     placegoing = int(parts[5])
    #     for i in range(numtaken):
    #         arr[placegoing] = [arr[placetaken].pop(0)] + arr[placegoing]
    elif("move" in line):
        parts = line.split(" ")
        numtaken = int(parts[1])
        placetaken = int(parts[3])
        placegoing = int(parts[5])
        temparr = []
        for i in range(numtaken):
            temparr.append(arr[placetaken].pop(0))
        arr[placegoing] = temparr + arr[placegoing]
    count+=1
for i in range(9):
    print(arr[i+1][0], end="")


#!/usr/bin/env python3
# Author: Armit
# Create Time: 2022/11/06

import os
from argparse import ArgumentParser
from collections import Counter

import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
try:
  from sklearnex import patch_sklearn
  patch_sklearn()
except:
  print('cannot import sklearnex, if you have Intel CPU, do `pip install scikit-learn-intelex` for calculation acceleration')
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from model import MODELS, get_model
from util import frac_to_str

stats = {
  # 'layer_name': ((n_kernel_original, n_kernel_clustered), (L0, L1, L2, Linf))
}

def optimal_number_of_clusters(wcss, n_clust_min, n_clust_max, step=1):
  x1, y1 = n_clust_min, wcss[0]
  x2, y2 = n_clust_max, wcss[len(wcss)-1]

  distances = []
  for i in range(len(wcss)):
    x0 = i+n_clust_min
    y0 = wcss[i]
    numerator = np.abs((y2-y1)*x0 - (x2-x1)*y0 + x2*y1 - y2*x1)
    denominator = np.sqrt((y2 - y1)**2 + (x2 - x1)**2)
    distances.append(numerator/denominator)

  return distances.index(max(distances)) * step + n_clust_min

@torch.no_grad()
def cluster_kernels(name:str, layer:nn.Conv2d, args):
  print(f'[cluster_kernels] {name}')

  weight = layer.weight                             # [C_o, C_i, K_h, K_w]
  C_out, C_in, K_h, K_w = weight.shape

  data = weight.flatten(start_dim=1).cpu().numpy()  # [C_o, C_i*K_h*K_w], vectorize

  # reduce by fixed ratio
  if args.method == 'fixed':
    n_clust = round(C_out * args.fixed)

  # reduce by inertia limit
  if args.method == 'inertia':
    for n_clust in range(C_out-1, C_out//2, -1):
      model = KMeans(n_clust)
      model.fit(data)
      inertia = model.inertia_
      del model
      print(f'   n_clust: {n_clust}, inertia: {inertia}')
      if inertia > args.inertia: break

    n_clust = n_clust + 1

  # reduce by optimal `wcss` metric
  if args.method == 'wcss':
    n_clust_min, n_clust_max = round(C_out * args.wcss_from), round(C_out * args.wcss_to)
    rng = n_clust_max - n_clust_min + 1
    step = max(1, round(np.log2(rng) - 3))

    wcss = []
    for n_clust in range(n_clust_min, n_clust_max, step):
      model = KMeans(n_clust)
      model.fit(data)
      print(f'   n_clust: {n_clust}, inertia: {model.inertia_}')
      wcss.append(model.inertia_)
      del model

    if args.show: plt.plot(wcss) ; plt.title('wcss') ; plt.show()

    n_clust = optimal_number_of_clusters(wcss, n_clust_min, n_clust_max)

  model = KMeans(n_clust)
  pred = model.fit_predict(data).tolist()
  centroids = model.cluster_centers_
  print(f'decision: n_clust={model.n_clusters}, inertia={model.inertia_}')

  if args.show:
    plt.subplot(211) ; plt.title('hist') ; plt.hist(pred, bins=n_clust)
    plt.subplot(212) ; plt.title('freq') ; plt.plot(sorted(Counter(pred).values(), reverse=True))
    plt.show()

    distmat = np.abs(centroids[None, :, :] - centroids[:, None, :]).mean(axis=-1)
    sns.heatmap(distmat)
    plt.title('dist matrix')
    plt.show()

  # update kernels
  kernel_prototypes = centroids.reshape([-1, C_in, K_h, K_w])   # de-vectorize
  weight_prototypes = torch.from_numpy(kernel_prototypes[pred])
  if 'repalce with centroids':
    new_weight = weight_prototypes
  if not 'step away from centroids':
    d_w = weight - weight_prototypes
    new_weight = weight + d_w * 0.1
  layer.weight = Parameter(new_weight, requires_grad=True)

  # calc states
  d_weight = new_weight - weight
  d_weight_abs = d_weight.abs()
  n_param = weight.numel()

  L0   = (d_weight != 0).sum() / n_param
  L1   = d_weight_abs.sum() / n_param
  L2   = d_weight.square().sum().sqrt() / n_param
  Linf = d_weight_abs.max()

  stats[name] = (
    (C_out, n_clust),
    (L0, L1, L2, Linf),
  )

def prune(args):
  print(f'>> loading pretrained {args.model}')
  model = get_model(args.model).eval()

  for name, mod in model.named_modules():
    if isinstance(mod, nn.Conv2d):
      cluster_kernels(name, mod, args)
      if args.only_first_layer: break

  fp = os.path.join(args.out_path, f'{args.name}.pth')
  print(f'>> saving weights to {fp}')
  torch.save(model.state_dict(), fp)

  fp = os.path.join(args.out_path, f'{args.name}.txt')
  print(f'>> saving stats to {fp}')
  with open(fp, 'w', encoding='utf-8') as fh:
    for k, v in stats.items():
      lines = [
        f'[{k}] {v[0][0]} => {v[0][1]}',
        f'   L0:   {v[1][0]}',
        f'   L1:   {v[1][1]}',
        f'   L2:   {v[1][2]}',
        f'   Linf: {v[1][3]}',
      ]
      log = '\n'.join(lines)
      fh.write(log) ; fh.write('\n')
      print(log)

if __name__ == '__main__':
  parser = ArgumentParser()
  parser.add_argument('-M', '--model', default='resnet18', choices=MODELS)
  parser.add_argument('--method', default='fixed', choices=['fixed', 'wcss', 'inertia'])
  parser.add_argument('--fixed',     default=0.9,  type=float, help='reduction ratio in range (0, 1)')
  parser.add_argument('--wcss_from', default=0.5,  type=float, help='reduction ratio in range (0, 1)')
  parser.add_argument('--wcss_to',   default=0.75, type=float, help='reduction ratio in range (0, 1)')
  parser.add_argument('--inertia',   default=2.0, type=float,  help='cluster inertia limit')

  parser.add_argument('--only_first_layer', action='store_true')

  parser.add_argument('--show', action='store_true')
  parser.add_argument('--overwrite', action='store_true')
  parser.add_argument('--data_path', default='data')
  parser.add_argument('--out_path', default='out')
  args = parser.parse_args()

  os.makedirs(args.data_path, exist_ok=True)
  os.makedirs(args.out_path, exist_ok=True)

  if args.method == 'fixed':
    suffix = f'_fixed={frac_to_str(args.fixed)}'
  if args.method == 'wcss':
    suffix = f'_wcss={frac_to_str(args.wcss_from)}~{frac_to_str(args.wcss_to)}'
  if args.method == 'inertia':
    suffix = f'_inertia={frac_to_str(args.inertia)}'
  suffix += '_ofl' if args.only_first_layer else ''
  args.name = f'{args.model}{suffix}'

  fp = os.path.join(args.out_path, f'{args.name}.pth')
  if not args.overwrite and os.path.exists(fp):
    print(f'safely ignore {args.name} due to file exists: {fp}')
    exit(0)

  prune(args)


from typing import List

from pydantic import parse_obj_as

from app.repository.residential_repo import get_handbooks_by_block_house_ids, get_handbook_detail
from app.schemas import Handbook, HandbookDetail
from app.utilities.common import get_data_image
from app.utilities.pagination import parsing_pagination, get_paging_config
from configs import get_settings

async def get_list(db, request, house):
    try:
        paging_config = get_paging_config(request)
        data, total = await get_handbooks_by_block_house_ids(
            db=db,
            house=house,
            paging=paging_config
        )
        data = parse_obj_as(List[Handbook], data)
        data = get_data_image(data, 'tb_resident_handbook')
        return parsing_pagination(data, total, request)
    except Exception as e:
        return e

async def get_detail(db, handbook_id):
    try:
        data = await get_handbook_detail(db, handbook_id)
        data = HandbookDetail.from_orm(data)
        data.image = f"{get_settings().residential_server_url}/web/image?model=tb_resident_handbook&id={data.id}&field=image"
        return data
    except Exception as e:
        return e


#g = ["RDU", "LRU"]
def move(g, h, w):
  x = 0
  y = 0

  trajectory = []
  for i in range(h):
    l = []
    for j in range(w):
      l.append(False)
    trajectory.append(l)

  while True:
    if trajectory[x][y]:
      return -1

    trajectory[x][y] = True

    if g[x][y] == "U" and x != 0:
      x = x - 1
    elif g[x][y] == "D" and x != (h - 1):
      x = x + 1
    elif g[x][y] == "L" and y != 0:
      y = y - 1
    elif g[x][y] == "R" and y != (w - 1):
      y = y + 1
    else:
      return x + 1, y + 1

  # 問題設定では(1,1)から移動している想定なので
  # return x + 1, y + 1

H, W = [int(i) for i in input().split()]
G = []
for h in range(H):
  G.append(input())
print(move(G, H, W))


# Data structure to store IT resources
resources = []

# Function to add IT resources
def add_resource():
    name = input("Enter resource name: ")
    r_type = input("Enter resource type (Hardware/Software/License): ")
    quantity = int(input("Enter quantity: "))
    status = input("Enter status: ")

    resource = {"name": name, "type": r_type, "quantity": quantity, "status": status}
    resources.append(resource)

# Function to update IT resources
def update_resource():
    name = input("Enter the resource name you want to update: ")
    for resource in resources:
        if resource["name"] == name:
            resource["type"] = input("Enter new resource type: ")
            resource["quantity"] = int(input("Enter new quantity: "))
            resource["status"] = input("Enter new status: ")
            print("Resource updated.")
            return
    print("Resource not found.")

# Function to display IT resources
def display_resources():
    for resource in resources:
        print(
            f"Name: {resource['name']}, Type: {resource['type']}, Quantity: {resource['quantity']}, Status: {resource['status']}")

# Function to generate a report
def generate_report():
    print("IT Resource Report:")
    for resource in resources:
        print(
            f"Resource: {resource['name']}, Type: {resource['type']}, Quantity: {resource['quantity']}, Status: {resource['status']}")

# Main program
while True:
    print("\nIT Resource Management System")
    print("================================")
    print("(A)dd IT resources")
    print("(U)pdate resources information")
    print("(D)isplay IT resources")
    print("(R)eport")
    print("(E)xit")
    option = input("Enter option: ").upper()

    if option == "A":
        add_resource()
    elif option == "U":
        update_resource()
    elif option == "D":
        display_resources()
    elif option == "R":
        generate_report()
    elif option == "E":
        print("Exiting the program.")
        break
    else:
        print("Invalid option. Please try again.")


from typing import Dict, List, Optional, Tuple, Type, Union

from autoconf import cached_property

import autoarray as aa
import autogalaxy as ag

from autoarray.inversion.inversion.factory import inversion_unpacked_from

from autolens.analysis.preloads import Preloads

class TracerToInversion(ag.AbstractToInversion):
    def __init__(
        self,
        tracer,
        dataset: Optional[Union[aa.Imaging, aa.Interferometer]] = None,
        data: Optional[Union[aa.Array2D, aa.Visibilities]] = None,
        noise_map: Optional[Union[aa.Array2D, aa.VisibilitiesNoiseMap]] = None,
        w_tilde: Optional[Union[aa.WTildeImaging, aa.WTildeInterferometer]] = None,
        settings_pixelization=aa.SettingsPixelization(),
        settings_inversion: aa.SettingsInversion = aa.SettingsInversion(),
        preloads=Preloads(),
        run_time_dict: Optional[Dict] = None,
    ):
        self.tracer = tracer

        super().__init__(
            dataset=dataset,
            data=data,
            noise_map=noise_map,
            w_tilde=w_tilde,
            settings_pixelization=settings_pixelization,
            settings_inversion=settings_inversion,
            preloads=preloads,
            run_time_dict=run_time_dict,
        )

    @property
    def planes(self):
        return self.tracer.planes

    @cached_property
    @aa.profile_func
    def traced_grid_2d_list_of_inversion(self) -> List[aa.type.Grid2DLike]:
        return self.tracer.traced_grid_2d_list_from(grid=self.dataset.grid_pixelization)

    @cached_property
    def lp_linear_func_list_galaxy_dict(
        self,
    ) -> Dict[ag.LightProfileLinearObjFuncList, ag.Galaxy]:
        if not self.tracer.perform_inversion:
            return {}

        lp_linear_galaxy_dict_list = {}

        traced_grids_of_planes_list = self.tracer.traced_grid_2d_list_from(
            grid=self.dataset.grid
        )

        if self.dataset.blurring_grid is not None:
            traced_blurring_grids_of_planes_list = self.tracer.traced_grid_2d_list_from(
                grid=self.dataset.blurring_grid
            )
        else:
            traced_blurring_grids_of_planes_list = [None] * len(
                traced_grids_of_planes_list
            )

        for plane_index, plane in enumerate(self.planes):
            plane_to_inversion = ag.PlaneToInversion(
                plane=plane,
                dataset=self.dataset,
                grid=traced_grids_of_planes_list[plane_index],
                blurring_grid=traced_blurring_grids_of_planes_list[plane_index],
                noise_map=self.noise_map,
            )

            lp_linear_galaxy_dict_of_plane = (
                plane_to_inversion.lp_linear_func_list_galaxy_dict
            )

            lp_linear_galaxy_dict_list = {
                **lp_linear_galaxy_dict_list,
                **lp_linear_galaxy_dict_of_plane,
            }

        return lp_linear_galaxy_dict_list

    def cls_pg_list_from(self, cls: Type) -> List:
        return [plane.cls_list_from(cls=cls) for plane in self.planes]

    @cached_property
    def adapt_galaxy_image_pg_list(self) -> List:
        return [
            plane.adapt_galaxies_with_pixelization_image_list for plane in self.planes
        ]

    @cached_property
    @aa.profile_func
    def sparse_image_plane_grid_pg_list(self) -> List[List]:
        """
        Specific pixelizations, like the `VoronoiMagnification`, begin by determining what will become its the
        source-pixel centres by calculating them  in the image-plane. The `VoronoiBrightnessImage` pixelization
        performs a KMeans clustering.
        """

        sparse_image_plane_grid_list_of_planes = []

        for plane in self.planes:
            plane_to_inversion = ag.PlaneToInversion(
                plane=plane,
                grid_pixelization=self.dataset.grid,
                settings_pixelization=self.settings_pixelization,
                noise_map=self.noise_map,
            )

            sparse_image_plane_grid_list = (
                plane_to_inversion.sparse_image_plane_grid_list
            )
            sparse_image_plane_grid_list_of_planes.append(sparse_image_plane_grid_list)

        return sparse_image_plane_grid_list_of_planes

    @cached_property
    @aa.profile_func
    def traced_sparse_grid_pg_list(self) -> Tuple[List[List], List[List]]:
        """
        Ray-trace the sparse image plane grid used to define the source-pixel centres by calculating the deflection
        angles at (y,x) coordinate on the grid from the galaxy mass profiles and then ray-trace them from the
        image-plane to the source plane.
        """
        if (
            self.preloads.sparse_image_plane_grid_pg_list is None
            or self.settings_pixelization.is_stochastic
        ):
            sparse_image_plane_grid_pg_list = self.sparse_image_plane_grid_pg_list

        else:
            sparse_image_plane_grid_pg_list = (
                self.preloads.sparse_image_plane_grid_pg_list
            )

        traced_sparse_grid_pg_list = []

        for plane_index, plane in enumerate(self.planes):
            if sparse_image_plane_grid_pg_list[plane_index] is None:
                traced_sparse_grid_pg_list.append(None)
            else:
                traced_sparse_grids_list = []

                for sparse_image_plane_grid in sparse_image_plane_grid_pg_list[
                    plane_index
                ]:
                    try:
                        traced_sparse_grids_list.append(
                            self.tracer.traced_grid_2d_list_from(
                                grid=sparse_image_plane_grid
                            )[plane_index]
                        )
                    except AttributeError:
                        traced_sparse_grids_list.append(None)

                traced_sparse_grid_pg_list.append(traced_sparse_grids_list)

        return traced_sparse_grid_pg_list, sparse_image_plane_grid_pg_list

    @cached_property
    def mapper_galaxy_dict(self) -> Dict[aa.AbstractMapper, ag.Galaxy]:
        mapper_galaxy_dict = {}

        if self.preloads.traced_grids_of_planes_for_inversion is None:
            traced_grids_of_planes_list = self.traced_grid_2d_list_of_inversion
        else:
            traced_grids_of_planes_list = (
                self.preloads.traced_grids_of_planes_for_inversion
            )

        if self.preloads.traced_sparse_grids_list_of_planes is None:
            (
                traced_sparse_grids_list_of_planes,
                sparse_image_plane_grid_list,
            ) = self.traced_sparse_grid_pg_list
        else:
            traced_sparse_grids_list_of_planes = (
                self.preloads.traced_sparse_grids_list_of_planes
            )
            sparse_image_plane_grid_list = self.preloads.sparse_image_plane_grid_list

        for plane_index, plane in enumerate(self.planes):
            if plane.has(cls=aa.Pixelization):
                plane_to_inversion = ag.PlaneToInversion(
                    plane=plane,
                    grid_pixelization=traced_grids_of_planes_list[plane_index],
                    settings_pixelization=self.settings_pixelization,
                    preloads=self.preloads,
                    noise_map=self.noise_map,
                )

                galaxies_with_pixelization_list = plane.galaxies_with_cls_list_from(
                    cls=aa.Pixelization
                )

                for mapper_index in range(
                    len(traced_sparse_grids_list_of_planes[plane_index])
                ):
                    pixelization_list = self.cls_pg_list_from(cls=aa.Pixelization)

                    mapper = plane_to_inversion.mapper_from(
                        mesh=pixelization_list[plane_index][mapper_index].mesh,
                        regularization=pixelization_list[plane_index][
                            mapper_index
                        ].regularization,
                        source_plane_mesh_grid=traced_sparse_grids_list_of_planes[
                            plane_index
                        ][mapper_index],
                        image_plane_mesh_grid=sparse_image_plane_grid_list[plane_index][
                            mapper_index
                        ],
                        adapt_galaxy_image=self.adapt_galaxy_image_pg_list[plane_index][
                            mapper_index
                        ],
                    )

                    galaxy = galaxies_with_pixelization_list[mapper_index]

                    mapper_galaxy_dict[mapper] = galaxy

        return mapper_galaxy_dict

    @cached_property
    def inversion(self):
        inversion = inversion_unpacked_from(
            dataset=self.dataset,
            data=self.data,
            noise_map=self.noise_map,
            w_tilde=self.w_tilde,
            linear_obj_list=self.linear_obj_list,
            settings=self.settings_inversion,
            preloads=self.preloads,
            run_time_dict=self.tracer.run_time_dict,
        )

        inversion.linear_obj_galaxy_dict = self.linear_obj_galaxy_dict

        return inversion


# Try-Except
# Try-Except block allows you to try a piece of code and catch any exceptions(errors)
# that occur during execution, then take appropriate action based on type of error.

try:
    # code that may raise an error
    num1 = int(input("Enter a number:  "))
    num2 = 10 / num1
except ValueError:
    # Handle value error
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("A number cannot be divided by zero")
except Exception as e:
    # Handle other type of error other than above mentioned
    print("An error occurred", e)
else:
    # Executed only if no exceptions are raised
    print("Result: ", num2)
# else clause will only be executed if try clause raises no error.

# finally: clause
# Block of code in finally clause will be executed no matter what,
# whether an exception was raised or not
try:
    file = open("example.txt")
    content = file.read()
except FileNotFoundError:
    print("File Not Found!")
else:
    print(content)
    print("File opened successfully.")
finally:
    file.close()
    print("File closed.")

# 1) else clause will be executed only if file is existed and no error was raised.
# 2) finally clause will be executed no matter what

# raise statement:
# You can raise your own exceptions using the "raise" statement.
# Raising on exception is away to signal that an error has occurred in your code.
# It allows you to handle error that are not caught by Python interpreter
# but that's inappropriate to your application

class InvalidInputExecption(Exception):
    pass

def validate_input(input_str):
    if not input_str.isnumeric():
        raise InvalidInputExecption("Input must be a positive integer.")
    return int(input_str)

try:
    user_input = input("Enter a positive number: ")
    num = validate_input(user_input)
    print(f"The square of {num} is {num ** 2}")
except InvalidInputExecption as e:
    print(f"Error: {e}")


import math
import random
from typing import Tuple

import cv2
import numpy as np

def np_free_form_mask(
    max_vertex: int, max_length: int, max_brush_width: int, max_angle: int, height: int, width: int
) -> np.ndarray:
    mask = np.zeros((height, width), np.float32)

    num_vertex = random.randint(0, max_vertex)
    start_y = random.randint(0, height - 1)
    start_x = random.randint(0, width - 1)

    brush_width = 0
    for i in range(num_vertex):
        angle = random.random() * max_angle
        angle = math.radians(angle)

        if i % 2 == 0:
            angle = 2 * math.pi - angle

        length = random.randint(0, max_length)
        brush_width = random.randint(10, max_brush_width) // 2 * 2

        next_y = start_y + length * np.cos(angle)
        next_x = start_x + length * np.sin(angle)

        next_y = np.maximum(np.minimum(next_y, height - 1), 0).astype(np.int)
        next_x = np.maximum(np.minimum(next_x, width - 1), 0).astype(np.int)

        cv2.line(mask, (start_y, start_x), (next_y, next_x), 1, brush_width)
        cv2.circle(mask, (start_y, start_x), brush_width // 2, 2)
        start_y, start_x = next_y, next_x

    cv2.circle(mask, (start_y, start_x), brush_width // 2, 2)

    return mask

def generate_stroke_mask(
    image_size: Tuple[int, int],
    parts: int = 7,
    max_vertex: int = 25,
    max_length: int = 80,
    max_brush_width: int = 80,
    max_angle: int = 360,
) -> np.ndarray:
    mask = np.zeros(image_size, dtype=np.float32)
    for _ in range(parts):
        mask = mask + np_free_form_mask(
            max_vertex, max_length, max_brush_width, max_angle, image_size[0], image_size[1]
        )

    return np.minimum(mask, 1.0)


import sqlite3 as lite

# TODO pr save event... ce ni subjecta, vrni neko napako al neki

# prejsnja verzija:
#(ID,d,m,y,subj,desc,h:m,notify,weekday,repeat,repDays,repUntil,show)
# se mi zdi
################################################################
def create_events():
    # Options.db file must not exist!
    con = lite.connect('Events.db')
    with con:
        cur = con.cursor()
        # dateChanged    - "YYYY-MM-DD HH:MM:SS"  datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # repeat         - one of [none,daily, weekly, monthly, anualy, custom]
        # repeatWeekdays - tuple containing weekday numbers eg. "(1,3,4)"
        # repeatUntil    - tuple "(yyyy,mm,dd)"
        # show           - boolean
        # notify         - boolean
        cur.execute('''CREATE TABLE Events(Id INTEGER PRIMARY KEY,
                       dateChanged TEXT,
                       subject TEXT,
                       description TEXT,
                       year INTEGER,
                       month INTEGER,
                       day INTEGER,
                       h_m TEXT,
                       repeat TEXT,
                       repeatWeekdays TEXT,
                       repeatUntil TEXT,
                       show INTEGER,
                       notify INTEGER)''')

def save_event(dateChanged,subject,description,year,month,day,h_m,repeat='None',repeatWeekdays='()',repeatUntil='(,,)',show=1,notify=0):
##    print dateChanged,subject,year,month,day,h_m
    if subject == '':
        print('No subject!')
        return 0
    con = lite.connect('Events.db')
    with con:
        cur = con.cursor()
        cur.execute('SELECT * FROM Events WHERE year='+str(year)+' AND month='+str(month)+' AND day= '+str(day)+' AND h_m="'+str(h_m)+'" AND subject="'+subject+'"')
        test = cur.fetchall()
        if test: return 0 # event ze obstaja, zato ne shranimo nic
        cur.execute('INSERT INTO Events(dateChanged,subject,description,year,month,day,h_m,repeat,repeatWeekdays,repeatUntil,show,notify) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)', (dateChanged,subject,description,year,month,day,h_m,repeat,repeatWeekdays,repeatUntil,show,notify))

def change_event_id(id, names, values):
    # id - id of event
    # name - tuple of names of values to change
    # value - new values for corresponding names
    if len(names) != len(values): return 0
    if len(names) == 0: return 0
    changes = ''
    for i in range(len(names)):
        if type(values[i]) == type(''):
            changes = changes + str(names[i])+'="'+str(values[i])+'", '
        else:
            changes = changes + str(names[i])+'='+str(values[i])+', '
    changes = changes[:-2]+' '
    print('UPDATE Events set '+changes+'WHERE Id = '+str(id))
    con = lite.connect('Events.db')
    with con:
        cur = con.cursor()
        cur.execute('UPDATE Events set '+changes+'WHERE Id = '+str(id))

def delete_event_id(id):
    print(id)
    con = lite.connect('Events.db')
    with con:
        cur = con.cursor()
        cur.execute('DELETE FROM Events WHERE Id = '+str(id))

def get_events_day(year,month,day):
    # TODO check everything
    con = lite.connect('Events.db')
    with con:
        cur = con.cursor()
        cur.execute('SELECT * FROM Events WHERE year='+str(year)+' AND month='+str(month)+' AND day='+str(day))
        out = cur.fetchall()
    out2 = dict()
    for i in out:
        if out2.get(int(i[7][:2])): out2[int(i[7][:2])].append(i)
        else: out2[int(i[7][:2])] = [i]
    return out2

def get_events_month(year,month,day_first,day_last):
    # TODO repeating events not implemented yet i think

    # for display on main window
    # day_first - month day of the first day of the previous month, that is displayed
    # day_last - month day of the last day of the next month, that is displayed
    con = lite.connect('Events.db')
    with con:
        cur = con.cursor()
        cur.execute('SELECT * FROM Events WHERE year='+str(year if month!=1 else year-1)+' AND month='+str(month-1 if month!=1 else 12)+' AND day>='+str(day_first))
        out = cur.fetchall()
        cur.execute('SELECT * FROM Events WHERE year='+str(year)+' AND month='+str(month))
        out += cur.fetchall()
        cur.execute('SELECT * FROM Events WHERE year='+str(year if month!=12 else year+1)+' AND month='+str(month+1 if month!=12 else 1)+' AND day<='+str(day_last))
        out += cur.fetchall()

    out2 = dict()
    for i in out:
        try:
            # (year, month, day)
            out2[(i[4],i[5],i[6])] += [i]
##            out2[(int(i[4]),int(i[5]),int(i[6]))] += [i]
        except:
            out2[(i[4],i[5],i[6])] = [i]
##            out2[(int(i[4]),int(i[5]),int(i[6]))] = [i]

    return out2

################################################################
################################################################
def create_options():
    # Options.db file must not exist!
    con = lite.connect('Options.db')
    with con:
        cur = con.cursor()
        cur.execute('''CREATE TABLE Colors(Id INTEGER PRIMARY KEY,
                       color1 TEXT,
                       color2 TEXT,
                       color3 TEXT,
                       color4 TEXT,
                       color5 TEXT,
                       color6 TEXT)''')
        cur.execute('INSERT INTO Colors(color1,color2,color3,color4,color5,color6)VALUES (?,?,?,?,?,?)', ('#808080', '#cfcfcf', '#ffffff', '#808080', '#ffffff', '#ffffff'))

        cur.execute('''CREATE TABLE ColorScheme(Id INTEGER PRIMARY KEY,
                       name TEXT,
                       color1 TEXT,
                       color2 TEXT,
                       color3 TEXT,
                       color4 TEXT,
                       color5 TEXT,
                       color6 TEXT)''')
        cur.execute('INSERT INTO ColorScheme(name,color1,color2,color3,color4,color5,color6)VALUES (?,?,?,?,?,?,?)', ('The Grey','#808080', '#cfcfcf', '#ffffff', '#808080', '#ffffff', '#ffffff'))

        cur.execute('''CREATE TABLE Misc(Id INTEGER PRIMARY KEY,
                       width INTEGER,
                       height INTEGER,
                       title INTEGER,
                       x INTEGER,
                       y INTEGER,
                       alpha INTEGER,
                       mouse INTEGER,
                       del INTEGER)''')
        cur.execute('INSERT INTO Misc(width,height,title,x,y,alpha,mouse,del) VALUES (?,?,?,?,?,?,?,?)', (80,60,20,10,10,80,1,0))

################################################################
def get_misc():
    con = lite.connect('Options.db')
    with con:
        cur = con.cursor()
        cur.execute('SELECT * FROM Misc')
        misc = cur.fetchall()[0][1:]
    return misc

def save_misc(width,height,title,x,y,alpha,mouse,delete):
    con = lite.connect('Options.db')
    with con:
        cur = con.cursor()

        cur.execute('DELETE FROM Misc WHERE Id = 1')
        cur.execute('INSERT INTO Misc(width,height,title,x,y,alpha,mouse,del) VALUES (?,?,?,?,?,?,?,?)', (width,height,title,x,y,alpha,mouse,delete))

################################################################
def change_colors_sql(colors):
    con = lite.connect('Options.db')
    with con:
        cur = con.cursor()

        cur.execute('DELETE FROM Colors WHERE Id = 1')
        cur.execute('INSERT INTO Colors(color1,color2,color3,color4,color5,color6)VALUES (?,?,?,?,?,?)', colors)

def get_colors():
    con = lite.connect('Options.db')
    with con:
        cur = con.cursor()
        cur.execute('SELECT * FROM Colors')
        colors = cur.fetchall()[0][1:]
    return colors

def save_color_scheme(name,colors):
    con = lite.connect('Options.db')
    with con:
        cur = con.cursor()
        cur.execute('INSERT INTO ColorScheme(name,color1,color2,color3,color4,color5,color6)VALUES (?,?,?,?,?,?,?)', [name]+colors)

def delete_color_scheme(id):
    con = lite.connect('Options.db')
    with con:
        cur = con.cursor()
        cur.execute('DELETE FROM ColorScheme WHERE Id = '+str(id))

def get_colors_schemes():
    con = lite.connect('Options.db')
    with con:
        cur = con.cursor()
        cur.execute('SELECT * FROM ColorScheme')
        schemes = cur.fetchall()

    return schemes

##def get_colors_scheme(id):
##    con = lite.connect('Options.db')
##    with con:
##        cur = con.cursor()
##        cur.execute('SELECT * FROM ColorScheme WHERE Id = '+str(id))
##        colors = cur.fetchall()[0]
##
##        cur.execute('DELETE FROM Colors WHERE Id = 1')
##        cur.execute('INSERT INTO Colors(color1,color2,color3,color4,color5,color6)VALUES (?,?,?,?,?,?)', colors[2:])
##    return colors

def get():
    con = lite.connect('Events.db')
    with con:
        cur = con.cursor()
        cur.execute('SELECT * FROM Events')
        out = cur.fetchall()
    for i in out:print(i)
##    return out

if __name__ == '__main__':
    try:
        create_options()
    except:
        pass
    try:
        create_events()
    except:
        pass
##    get()


__author__ = 'achandelkar'

def MaxMin(L1):
    Max = L1[0]
    Min = L1[0]
    i = 1
    while i < len(L1):
        if(L1[i] > Max):
            Max = L1[i]
        if(L1[i] < Min):
            Min = L1[i]
        i+=1
    return (Max,Min)

if __name__ == '__main__':
    L1 = eval(input("Enter a List to be reversed::"))
    print(MaxMin(L1))


#!/usr/bin/env python3
from __future__ import unicode_literals
import os
import sys
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning, module='setuptools')
warnings.filterwarnings("ignore", category=UserWarning, module='setuptools')
warnings.filterwarnings("ignore", message=".*is deprecated*")

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

def get_version():
    init_file = os.path.join(os.path.dirname(__file__), 'translatesrt', '__init__.py')
    with open(init_file, 'r') as f:
        for line in f:
            if line.startswith('VERSION'):
                return line.split('=')[1].strip().strip('"\'')

long_description = (
    'translatesrt is a utility for translating a subtitle file to another language'
)

install_requires=[
        "pysrt>=1.0.1",
        "progressbar2>=3.34.3",
]

setup(
    name="translatesrt",
    version=get_version(),
    description="a utility for translating a subtitle file to another language",
    long_description = long_description,
    author="Bot Bahlul",
    author_email="bot.bahlul@gmail.com",
    url="https://github.com/botbahlul/translatesrt",
    packages=["translatesrt"],
    entry_points={
        "console_scripts": [
            "translatesrt = translatesrt:main",
        ],
    },
    install_requires=install_requires,
    license=open("LICENSE").read()
)


import sys
from PyQt5.QtWidgets import QDialog, QMainWindow, QApplication, QFileDialog, QMessageBox
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QIcon
import MainWindow
import pandas as pd
import numpy as np
from pydispatch import dispatcher
import os

class StartPegasusViewer(QMainWindow):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.showMaximized()
        self.ui = MainWindow.Ui_MainWindow()
        # attributes initialised in subsequent methods
        self.dm = None

        self.ui.setupUi(self)
        self.ui.pushButton_2.clicked.connect(self.choose_file)
        # self.ui.comboBox.currentIndexChanged.connect(self.x_changed)
        self.ui.comboBox_2.currentIndexChanged.connect(self.y_changed)
        self.ui.comboBox_session.currentIndexChanged.connect(self.session_changed)
        self.ui.pushButton.clicked.connect(self.apply_btn_press)
        self.ui.pushButton_export.clicked.connect(self.export_btn_press)
        self.ui.pushButton_smooth.clicked.connect(self.apply_moving_avg)

    @pyqtSlot()
    def choose_file(self):
        fd = QFileDialog(self)
        filename = fd.getOpenFileName()
        from os.path import isfile
        if isfile(filename[0]):
            raw_data = pd.read_csv(filename[0], delimiter=',', header=5)
            self.dm = DataManager(raw_data)
            # self.ui.comboBox.addItems(self.dm.x_columns)
            self.ui.comboBox_2.addItems(self.dm.y_columns)
            self.ui.comboBox_session.addItems([str(x) for x in self.dm.get_sorted_session_keys()])
            # dispatcher.send('UpdateXCombo', update=self.dm.x_columns[0])
            self.ui.pushButton_2.setEnabled(False)

    def apply_btn_press(self):
        start_time = self.ui.timeEdit.time().toPyTime()
        end_time = self.ui.timeEdit_2.time().toPyTime()
        self.dm.apply_time_filter(start_time, end_time)
        dispatcher.send("UpdatePlot", plot_params=self.dm.plot_data)

    def export_btn_press(self):
        fd = QFileDialog(self)
        export_dir = str(fd.getExistingDirectory(self, "Select Export Directory"))
        folder_str = str(self.dm.current_session_key).replace(':', '-')
        export_dir = os.path.dirname(export_dir + os.sep + folder_str + os.sep)
        if not os.path.exists(export_dir):
            os.makedirs(export_dir)

        # Load standard plots from config file
        if os.path.isfile(r'config/Standard_Plots.csv'):
            std_plots_df = pd.read_csv(r'config/Standard_Plots.csv')
            read_plots = std_plots_df.columns.tolist()
            export_vars = list(set(read_plots).intersection(self.dm.y_columns))
        else:
            export_vars = ['Temperature (degC)', 'Humidity (%)', 'Pressure (hPa)']
        for export_var in export_vars:
            self.dm.update_y_plot_data(export_var)
            dispatcher.send("ExportPlot", plot_params=self.dm.plot_data, export_dir=export_dir)

    def apply_moving_avg(self):
        self.dm.apply_moving_avg()
        dispatcher.send("UpdatePlot", plot_params=self.dm.plot_data)

    # @pyqtSlot()
    # def x_changed(self):
    #     new_value = self.ui.comboBox.currentText()
    #     self.dm.update_x_plot_data(new_value)
    #     dispatcher.send("UpdatePlot", plot_params=self.dm.plot_data)

    def y_changed(self):
        new_value = self.ui.comboBox_2.currentText()
        self.dm.update_y_plot_data(new_value)
        dispatcher.send("UpdatePlot", plot_params=self.dm.plot_data)

    def session_changed(self):
        new_session_key = pd.to_datetime(self.ui.comboBox_session.currentText(), format='%Y/%m/%d %H:%M:%S')
        self.dm.update_session_plot_data(new_session_key)
        dispatcher.send("UpdatePlot", plot_params=self.dm.plot_data)
        dispatcher.send("UpdateTimeFields", s_time=self.dm.cur_start_time, e_time=self.dm.cur_end_time)

class DataManager():
    def __init__(self, data=None):
        self.data = data
        self.x_columns = None
        self.y_columns = None
        self.plot_data = None
        self.current_session_key = None
        self.cur_start_time = None
        self.cur_end_time = None
        self.cur_plot_df = None
        self.sessions = dict()

        if self.data is not None:
            self.inititialise_data()

    def inititialise_data(self):
        if ('Date (D/M/Y)' in self.data.columns) & ('Time (H:M:S)' in self.data.columns):
            # Filter out null dates
            null_dates = self.data['Date (D/M/Y)'] == '0/0/0'
            self.data = self.data[~null_dates]
            self.data = self.data.dropna()
            self.data = self.data.reset_index()

            # Concatenate date and time into single column
            datetime_str = self.data['Date (D/M/Y)'] + 'T' + self.data['Time (H:M:S)']
            date_times = pd.to_datetime(datetime_str, format='%d/%m/%YT%H:%M:%S')
            date_times = pd.Series(date_times)
            del self.data['Date (D/M/Y)']
            del self.data['Time (H:M:S)']
            if ('Master Index' in self.data.columns):
                del self.data['Master Index']
            del self.data['index']
            # self.x_columns = ['date_time'] + self.data.columns.tolist()
            self.data['date_time'] = date_times
            self.data.set_index(['date_time'], inplace=True)
            # Create dictionary for which each entry is a session
            self.split_on_id()
            session_keys = self.get_sorted_session_keys()
            # Set current session
            self.y_columns = self.data.columns.tolist()
            self.current_session_key = session_keys[0]
            self.cur_plot_df = self.sessions[self.current_session_key]
            self.cur_start_time = self.cur_plot_df.index[0]
            self.cur_end_time = self.cur_plot_df.index[len(self.cur_plot_df)-1]
            # Create plot data dictionary
            self.plot_data = dict()
            self.plot_data['x_name'] = 'date_time'
            self.plot_data['x_data'] = None
            self.plot_data['y_name'] = self.y_columns[1]
            self.plot_data['y_data'] = self.cur_plot_df[self.plot_data['y_name']]
        else:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setWindowTitle('Incorrect Data')
            msg.setInformativeText(
                r"Unable to locate the Date and Time columns with the correctly named column header")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()

    def update_x_plot_data(self, new_value):
        self.plot_data['x_name'] = new_value
        if new_value == 'date_time':
            self.plot_data['x_data'] = None
        else:
            self.plot_data['x_data'] = self.cur_plot_df[new_value].values

    def update_y_plot_data(self, new_value):
        self.plot_data['y_name'] = new_value
        if self.plot_data['x_name'] == 'date_time':
            self.plot_data['y_data'] = self.cur_plot_df[new_value]
        else:
            self.plot_data['y_data'] = self.cur_plot_df[new_value].values

    def update_session_plot_data(self, new_session_key):
        self.current_session_key = new_session_key
        self.cur_plot_df = self.sessions[self.current_session_key]
        # If plotting time series then no need to set x_data, use index instead
        if self.plot_data['x_name'] == 'date_time':
            self.plot_data['x_data'] = None
            self.plot_data['y_data'] = self.cur_plot_df[self.plot_data['y_name']]
        else:
            self.plot_data['x_data'] = self.cur_plot_df[self.plot_data['x_name']].values
            self.plot_data['y_data'] = self.cur_plot_df[self.plot_data['y_name']].values
        start_time = self.cur_plot_df.index[0]
        self.cur_start_time = DataManager.PdTimestamp2Datetime(start_time).time()
        end_time = self.cur_plot_df.index[len(self.cur_plot_df) - 1]
        self.cur_end_time = DataManager.PdTimestamp2Datetime(end_time).time()

    def split_on_id(self):
        gap_indexes = np.where(self.data['Session Index'] == 0)[0]
        del self.data['Session Index']
        if len(gap_indexes) == 1:
            self.sessions[self.data.index[0]] = self.data
        else:
            for i in range(len(gap_indexes) - 1):
                df_session = self.data.iloc[gap_indexes[i]: gap_indexes[i+1]]
                self.sessions[df_session.index[0]] = df_session
            df_session = self.data.iloc[gap_indexes[len(gap_indexes)-1]:]
            self.sessions[df_session.index[0]] = df_session

    def get_sorted_session_keys(self):
        if self.sessions:
            session_keys = []
            for key in self.sessions:
                session_keys.append(key)
            return sorted(session_keys)
        else:
            return None

    def apply_time_filter(self, start_time, end_time):
        import datetime as dt
        self.cur_start_time = start_time
        self.cur_end_time = end_time
        date = self.sessions[self.current_session_key].index[0].date()
        start_time = pd.to_datetime(dt.datetime.combine(date, start_time))
        end_time = pd.to_datetime(dt.datetime.combine(date, end_time))
        current_session = self.sessions[self.current_session_key]
        self.cur_plot_df = current_session[(current_session.index > start_time) &
                                           (current_session.index < end_time)]
        if self.plot_data['x_name'] == 'date_time':
            self.plot_data['y_data'] = self.cur_plot_df[self.plot_data['y_name']]
        else:
            self.plot_data['x_data'] = self.cur_plot_df[self.plot_data['x_name']].values
            self.plot_data['y_data'] = self.cur_plot_df[self.plot_data['y_name']].values

    def apply_moving_avg(self, window_len=10):
        self.cur_plot_df = self.cur_plot_df.rolling(window_len).mean()
        # Get the pandas series from current df
        y_data = self.cur_plot_df[self.plot_data['y_name']]
        # y_data = y_data.rolling(window=window_len).mean()
        null_mask = pd.notnull(y_data)
        y_data = y_data[null_mask]
        self.cur_plot_df = self.cur_plot_df[null_mask]
        if self.plot_data['x_name'] == 'date_time':
            self.plot_data['y_data'] = y_data
        else:
            self.plot_data['y_data'] = y_data.values
            self.plot_data['x_data'] = self.plot_data['x_data'][null_mask]

    @staticmethod
    def PdTimestamp2Datetime(PdTimestamp):
        import datetime
        time_str = str(PdTimestamp)
        return datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyle('cleanlooks')
    app.setWindowIcon(QIcon(r'resources/PegasusLogo.PNG'))
    myapp = StartPegasusViewer()
    myapp.show()
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Warning)
    msg.setWindowTitle('Terms of Use, Software Use and Disclaimer')
    msg.setText('Pegasus Viewer v1.0.0')
    msg.setInformativeText(r"This software is provided on an ‘as is’ basis with no warranty implied or given by "
            "BAE Systems.  It  is supplied as freely distributable software for use by UK Sport, the British Equestrian "
            "Federation and related bodies for the purpose of graphical representation of data derived from Pegasus units.  "
            "The company takes no responsibility for any loss or damage arising, directly or indirectly, as a result of "
            "use of the software, and gives no guarantees as to the veracity of the resultant formatted/plotted data.")
    msg.setStandardButtons(QMessageBox.Ok)
    msg.exec_()

    sys.exit(app.exec_())


import math

class Vector:
    def __init__(self, arr):
        self.arr = arr
        self.len = len(arr)

    def __str__(self):
        return str(tuple(self.arr))

    def equals(self):
        return None

    def add(self, vec):
        arr = []
        if len(vec.arr) != self.len:
            return None
        else:
            for i in range(self.len):
                arr.append(self.arr[i]+vec.arr[i])
        return arr

    def subtract(self, vec):
        arr = []
        if len(vec) != self.len:
            return None
        else:
            for i in range(self.len):
                arr.append(self.arr[i] - vec.arr[i])
        return arr

    def dot(self, vec):
        total = 0
        if len(vec) != self.len:
            return None
        else:
            for i in range(self.len):
                total += self.arr[i] ** vec.arr[i]
        return total

    def norm(self):
        total = 0
        for i in range(self.len):
            total += self.arr[i] ** 2
        return math.sqrt(total)

a = Vector([1, 2, 3])
b = Vector([3, 4, 5])

print(str(a))

Brampton Manor Academy/2022 Pre Release/idk.py


import sqlite3
import requests
import datetime
from bs4 import BeautifulSoup

try:

    URL = 'https://www.crosswalk.com/devotionals/everydaylight/'
    page = requests.get(URL)

    soup = BeautifulSoup(page.content, 'html.parser')
    content = soup.find('div', id='content')
    content1 = content.find('div', class_="articleContentBody")

    divs = content1.find_all('div')
    strongs = content1.find_all('strong')

    reading_and_meditation = content1.find('font', class_="headSub")
    related = reading_and_meditation.find_next_siblings()

    main_scripture = related[0].text  # main scriptural reference
    verse = related[2].text  # focus verse

    day = strongs[0].text
    title = strongs[1].text
    reading = divs[0].text.lstrip()
    prayer = divs[3].text.lstrip()

    other_references = ""
    for tags in divs[0].find_next_siblings():
        ass = tags.find_all('a')
        for yas in ass:
            other_references = other_references + yas.get_text() + ". "

    todays_reading = {
        'day': day,
        'main': main_scripture,
        'focus': verse,
        'topic': title,
        'reference': other_references,
        'reading': reading,
        'prayer': prayer
    }

    postURI = 'http://localhost:3030/add-today'
    response = requests.post(postURI, json=todays_reading)

    r = response.json()
    console.log(r)

except:
    print("Error while creating sqlite table")

finally:
    print("Finally")


import scipy.stats

### Starter code for Homework 2, problem 7 ###

#Our true mean function: will be sin(x/2) on [0,4*pi] and sin(6*x) on [4*pi,8*pi]
def mu(x):
  #Initialize a vector of zeros
  y = np.zeros(len(x))
  #Figure out which points are to the left or right of 4*pi
  left_points = (x<=4*np.pi)
  right_points = (x>4*np.pi)
  #Assign the appropriate sine values
  y[left_points] = np.sin(x[left_points]/2.0)
  y[right_points] = np.sin(6*x[right_points])
  #Return y
  return(y)

#A function to draw a sample from this curve
def generate_sample(n):
  #Sample the x coordinates uniformly on [0,8*pi].
  #We sort the x here to make plotting easier later.
  x = np.random.uniform(low=0, high=8*np.pi, size=n)
  x.sort()

  #Sample the y coordinates as gaussians around mu(x)
  y = mu(x) + np.random.normal(loc=0, scale=0.2, size=n)
  #Bind this all together into a pandas data frame
  return(pd.DataFrame({'x':x, 'y':y}))
  #you can access like df['x'], df['y'], among many other ways

#We set the seed so that your homeworks will match
scipy.random.seed(7)
#Sample 300 points.  This is your data set!
data = generate_sample(500)


# -*- coding: utf-8 -*-
'''
Created on 2012/07/25
@author: YuK_Ota
'''
import numpy
import pandas  # @UnresolvedImport

class BikeScore(object):
    '''
    compute BikeScore and xPower
    '''

    def __init__(self, dataset, cp):
        '''
        Constructor
        dataset=[(datetime.datetime,power)]
        cp CriticalPower
        '''
        self.dataSet = pandas.Series(dataset)
        self.cp = cp
        #Series型に変換する
        sirializeData = dict([(datum[0], datum[1]) for datum in dataset])
        date = sorted(sirializeData.keys())
        power = [sirializeData[key] for key in date]

        self.timePower = pandas.Series(power, index=date)

        (self.smoothTimePower, self.period) = \
            self._ewmaOfTimePower(self.timePower)

        self.xPower = self._computeXPower()
        self.RI = self._computeRelativeIntensity()
        self.normalizedWork = self._computeNormalizedWork()
        self.bikeScore = self._computeBikeScore()

    def _ewmaOfTimePower(self, time_power):
        '''
        calculate ewma of time_power
        時系列区間N=25s
        return ewmaを適用したSeries, 計測時間
        '''
        #時系列間隔を1sごとに調整
        replot = time_power.asfreq('1S', method='pad')
        smoothTimePower = pandas.ewma(replot, span=25)
        return smoothTimePower, len(replot)

    def _computeXPower(self):
        '''
        xPowerを計算する
        1.smoothTimePowerの4乗を取得する
        2.4乗の平均をとる
        3.平均値の4乗根を取る:
        '''
        fourthMean = numpy.array([i ** 4 for i in self.smoothTimePower]).mean()
        xPower = fourthMean ** (1.0 / 4.0)
        return xPower

    def getXPower(self):
        return self.xPower

    def _computeRelativeIntensity(self):
        '''
        RI = xPower/ CriticalPower
        '''
        return self.xPower / self.cp

    def _computeNormalizedWork(self):
        '''
        7.Multiply the xPower by the duration of the workout
        in seconds to obtain a Multiply the xPower
        by the duration of the workout in seconds to obtain a
        “normalized work” value in joules.
        workout時間にxPowerを掛ける
        '''
        return self.xPower * self.period

    def _computeBikeScore(self):
        '''
        9. Divide the values from step 8 by the amount
        of work performed during an hour at Critical Power.
        10. Multiply the number from step 9
        by 100 to obtain the final BikeScore.
        '''
        rawBikeScore = self.normalizedWork * self.RI
        amountTime = self.period / 60
        hourPower = rawBikeScore / amountTime
        bikeScore = hourPower / 100
        return bikeScore

    def getBikeScore(self):
        return self.bikeScore

import scipy.optimize

class CriticalPower(object):
    def __init__(self, dataset):
        '''
        dataset = [(sec,work J)]
        tuple need more than 2.
        compute CriticalPower
        '''
        seconds = numpy.array([datum[0] for datum in dataset])
        works = numpy.array([datum[1] for datum in dataset])

        fitfunc = lambda p, x: p[0] * x + p[1]
        errfunc = lambda p, x, y: fitfunc(p, x) - y
        p0 = [0, 0]
        self._p1, success = \
            scipy.optimize.leastsq(errfunc, p0, args=(seconds, works))
        if success == False:
            raise ArithmeticError

    def getCP(self):
        '''
        Return CriticalPower
        '''
        return self._p1[0]


class Solution:
	def mergeSortedArrays(self, A: List[int], B: List[int]) -> List[int]:
		arr_merged = []
		ind_a = 0
		ind_b = 0
		arr_size = len(A) + len(B)
		compare_a = True
		compare_b = True
		for i in range(arr_size):
			# Check if exceeded array sizes
			if not compare_a:
				arr_merged.append(B[ind_b])
				ind_b += 1
			elif not compare_b:
				arr_merged.append(A[ind_a])
				ind_a += 1
			# The list element in A is smaller
			elif (A[ind_a] <= B[ind_b]):
				arr_merged.append(A[ind_a])
				ind_a += 1
				if (ind_a >= len(A)):
					compare_a = False
			# The list element in B is smaller
			elif (A[ind_a] > B[ind_b]):
				arr_merged.append(B[ind_b])
				ind_b += 1
				if (ind_b >= len(B)):
					compare_b = False
		return arr_merged


import requests
from flask import Flask, render_template, request, session, redirect
from twilio.rest import Client
from flask_session import Session
import random

account_sid = ""
auth_token = ""
client = Client(account_sid, auth_token)
app = Flask(__name__, "/static")

@app.route('/')
def index():
    session["user"] = None
    data_json = requests.get("https://api.covid19india.org/v4/data.json").json()
    data = {}
    for state in data_json:
        districts_list = []
        if "districts" not in data_json[state].keys():
            continue
        data_list = data_json[state]["districts"]
        for district in data_list:
            if "total" not in data_list[district].keys():
                continue
            if "confirmed" not in data_list[district]["total"].keys():
                continue
            if "meta" not in data_list[district].keys():
                continue
            if "population" not in data_list[district]["meta"].keys():
                continue
            districts_list.append(district)
        if len(districts_list) == 0:
            continue
        data[state] = districts_list
    return render_template("index.html", data=data)

@app.route("/verify", methods=["POST"])
def verify():
    session["user"] = request.form
    string = str(random.randint(0, 9))
    string += str(random.randint(0, 9))
    string += str(random.randint(0, 9))
    string += str(random.randint(0, 9))
    mobile_number = request.form["mobile_number"]
    client.messages.create("+91" + str(mobile_number), from_="",
                           body="OTP for ePass registration is " + string)
    session["otp"] = string
    return render_template("verify.html", number=mobile_number, otp=string, check="0")

@app.route("/verification", methods=["POST"])
def verification():
    if session["user"] is None:
        return redirect("/")
    string = request.form["1"]
    string += request.form["2"]
    string += request.form["3"]
    string += request.form["4"]
    if string == session["otp"]:
        return redirect("/status")
    else:
        return render_template("verify.html", number=session["user"]["mobile_number"], otp=string, check="1")

@app.route("/status", methods=["GET"])
def details():
    if session["user"] is None:
        return redirect("/")
    first_name = session["user"]["first_name"]
    last_name = session["user"]["last_name"]
    aadhaar_number = session["user"]["aadhaar_number"]
    from_state = session["user"]["from_state"]
    from_district = session["user"]["from_district"]
    to_state = session["user"]["to_state"]
    to_district = session["user"]["to_district"]
    mobile_number = session["user"]["mobile_number"]
    from_date = session["user"]["from_date"]
    to_date = session["user"]["to_date"]
    data = requests.get("https://api.covid19india.org/v4/data.json").json()
    count = data[to_state]["districts"][to_district]["total"]["confirmed"]
    total = data[to_state]["districts"][to_district]["meta"]["population"]
    percentage = (count / total) * 100
    if percentage < 20:
        status = "CONFIRMED"
    else:
        status = "NOT CONFIRMED"
    client.messages.create("+91" + str(mobile_number), from_="",
                           body="Hello " + first_name + " " + last_name + ", your travel from " + from_district + " to " + to_district + " is " + status.lower() + ".")
    session["user"] = None
    return render_template("status.html", var1=first_name + " " +  last_name, var2=aadhaar_number, var3=from_state,
                           var4=from_district, var5=to_state, var6=to_district, var7=mobile_number, var8=from_date,
                           var9=to_date, var10=status)

if __name__ == "__main__":
    app.config["SESSION_PERMANENT"] = False
    app.config["SESSION_TYPE"] = "filesystem"
    Session(app)
    app.run(port=1000, debug=True)