import pygame
import random
import os
import socket
import _pickle as pickle

#================================================= The connection part ================================================#

class Network:
    def __init__(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.host = "192.168.56.1"
        self.port = 50007
        self.addr = (self.host, self.port)

    def connect(self, name):
        self.client.connect(self.addr)
        self.client.send(str.encode(name))
        val = self.client.recv(1024)
        return print(val)

    def send(self, data, pick=False):
        try:
            if pick:
                self.client.send(pickle.dumps(data))
            else:
                self.client.send(str.encode(data))
            reply = self.client.recv(2048*4)
            try:
                reply = pickle.loads(reply)
            except Exception as e:
                print(e)
            return reply
        except socket.error as e:
            print(e)

#===================================================== The classes ====================================================#

class Players:
    def __init__(self, x, y , health, image, width, height):
        self.imgP1 = pygame.image.load(image).convert_alpha()
        self.x = x
        self.y = y
        self.health = health
        self.image = image
        self.width = width
        self.height = height
        self.missiles = []
        self.score = 0
        self.lives = 3

    def add_Missile(self, MissleObj):
        self.missiles.append(MissleObj)

    def position(self):
        return (self.x, self.y)

    def Increase_Score(self):
        self.score += 100

class Enemy:
    def __init__(self, init_x = 0, init_y = 0):
        self.imgProj = pygame.image.load(r'assets\enemies\enemy1better.png')
        self.x = init_x
        self.y = init_y
        self.speed = random.randint(5,10)
        self.id = id

    def remove_life(self, playerObj):
        playerObj.lives -= 1
        return playerObj.lives

    def SendCoordinates(self):
        return [self.x, self.y]

class Missile:
    def __init__(self, player1Obj, mainwindow):
        self.imgMissile1 = pygame.image.load(r'assets\laser.png').convert_alpha()
        self.shoot_speed = 15
        self.playerObj = player1Obj
        self.y = 700
        self.window = mainwindow
        self.imgMissile2 = pygame.transform.scale(self.imgMissile1, (40, 80))
        self.state = 'ready'
        self.currentx = []

    def ChangeState(self):
        self.state = 'shot'

    def onFire(self, CurrentX):
        self.currentx.append(CurrentX)

    def shoot(self):
        if len(self.currentx) > 1:
            self.currentx.remove(self.currentx[0])

        self.window.blit(self.imgMissile2, (self.currentx[-1] - 15, self.y))
        self.y -= self.shoot_speed

        if self.y < 0:
            self.y = 700
            self.state = 'ready'

    def getCoords(self):
        if self.currentx == []:
            pass
        else:
            return [self.currentx[0], self.y]

#=================================================== The game method ==================================================#

# Move speed of the bullet
move_speed = 15

# =============================================== The pygame innit #===================================================#

def lan_game():

    # Moving the player2 object on the screen
    def move_Player2(data):
        if int(data) == 1000:
            pass
        else:
            Player2Obj.x = int(data)

# ============================================== Establishing connection #=============================================#

    Server = Network()
    Server.connect('Player2')

# =============================================== The pygame innit #===================================================#

    pygame.init()
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    main_window = pygame.display.set_mode((900, 900))

    clock = pygame.time.Clock()
    move_rate = 15
    pygame.mouse.set_visible(False)

    backgroundIMG = pygame.image.load(r'assets\main background.png')

# ===================================================# ALL OBJECTS #===================================================#

    # Players

    Player1Obj = Players(400, 750, 100, r'assets\player 1\player1.png', 58, 61)
    Player2Obj = Players(600, 750, 100, r'assets\player 1\player1.png', 58, 61)

    # Enemies

    Bob = Enemy()
    Martin = Enemy()

    # Missiles

    for i in range (0,2):
        missile = Missile(Player1Obj, main_window)
        Player1Obj.missiles.append(missile)

# =================================================# Sound and Music #=================================================#

    pygame.mixer.music.set_volume(pygame.mixer.music.get_volume() - 0.90)
    music_li = random.randint(1, 4)
    if music_li == 1:
        pygame.mixer.music.load(r'assets\music\all star.mp3')
    elif music_li == 2:
        pygame.mixer.music.load(r'assets\music\what is love 8 bit.mp3')
    elif music_li == 3:
        pygame.mixer.music.load(r'assets\music\feel good.mp3')
    else:
        pygame.mixer.music.load(r'assets\music\remove.mp3')

    pygame.mixer.music.play(0)

    # the hit variable - used when the player 1 hits an enemy of the other player
    global hit

# ================================================ The main game loop #================================================#

    while open:

        # KEY LISTENERS

        key_listener = pygame.key.get_pressed()
        if (key_listener[pygame.K_LEFT] or key_listener[pygame.K_a]) and Player1Obj.x > 30:
            Player1Obj.x -= move_rate

        elif (key_listener[pygame.K_RIGHT] or key_listener[pygame.K_d]) and Player1Obj.x < 855:
            Player1Obj.x += move_rate

        # Blitting main images, background, players
        main_window.blit(backgroundIMG, (0, 0))
        main_window.blit(Player1Obj.imgP1, (Player1Obj.x - 20, Player1Obj.y))
        main_window.blit(Player2Obj.imgP1, (Player2Obj.x - 20, Player2Obj.y))

        # Looping over the missiles
        for missile in Player1Obj.missiles:
            if missile.state == 'shot':
                missile.shoot()

        # Setting hit to default 0
        hit = 0

        # Looping over missile and collision
        for missile in Player1Obj.missiles:
            a = missile.getCoords()
            if a == None:
                pass
            if a == None:
                pass
            else:
                if missile.state == 'ready':
                    break
                if Martin.y - 20 <= a[1] <= Martin.y + 20 and Martin.x - 30 < a[0] <= Martin.x + 80:
                    print('Martin')
                    missile.state = 'ready'
                    missile.y = 700
                    Martin.x = 0
                    Martin.y = 0
                elif Bob.y - 20 <= a[1] <= Bob.y + 20 and Bob.x - 30 < a[0] <= Bob.x + 80:
                    print('Bob')
                    missile.state = 'ready'
                    missile.y = 700
                    hit = 1

# ================================================# Server connection #================================================#

        response = Server.send([[Player1Obj.x], Martin.SendCoordinates(), hit], pick=True)
        print(response)

        Bob.x = response[1][0]
        Bob.y = response[1][1]
        Martin.x = response[2][0]
        Martin.y = response[2][1]

        main_window.blit(Bob.imgProj, (Bob.x, Bob.y))
        main_window.blit(Martin.imgProj, (Martin.x, Martin.y))

        # calling move_Player2 with the response we got from the server
        move_Player2(response[0][0])

        pygame.display.update()

        # KEY LISTENERS PART 2
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYUP:
                if key_listener[pygame.K_SPACE]:
                    Current_Missile_X = Player1Obj.x
                    for missile in Player1Obj.missiles:
                        if missile.state == 'ready':
                            missile.ChangeState()
                            missile.onFire(Current_Missile_X)
                            break

# ========================================================# END #======================================================#

lan_game()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 16:20:25 2018

@author: liyuan
"""

'''
Data_char is prepared by converting each word into a list of characters e.g. explanation[0] contains 200 words, this is converted to 270 (max length of explanation) lists of length 19 (max char in word) integer sequence
the result is a 1663x270x19 array
'''

from Data import Data

from keras.preprocessing.sequence import pad_sequences
import nltk
import numpy as np
import codecs
import keras.backend as K
import time
import datetime
#import config
import re
from Struct import Struct

#%% define class
class Data_char(Data):
    explanations_path = './data/explanations2.txt'
    questions_path = './data/questions2.txt'
    word_embeddings_path = './embeddings/binaries/glove.840B.300d'
#    word_embeddings_path = './embeddings/binaries/glove.6B.50d'
    cache = Struct()
    lengths = Struct()
    indices = []
    questions_intseq = None
    exp_intseq = None
    answers_intseq = None
    answers_intseq2_val = None
    dummy_labels_train = None
    dummy_labels_val = None
    raw_questions = None
    char_vocab = None
    char2index = None

    def __init__(self):
        pass

    def __str__(self):
        """
        print attributes
        """
        attr_list = []
        for attribute in dir(self):
            if attribute != '__weakref__':
                if not hasattr(getattr(self,attribute),'__call__') and not '__' in attribute :
                    attribute_value = getattr(self,attribute)
                    if isinstance(attribute_value, (np.ndarray, np.generic)):
                        attribute_value = 'array with shape {}'.format(str(attribute_value.shape))
                    elif isinstance(attribute_value, Struct):
                        attribute_value = 'Struct with {} attributes'.format(len(attribute_value))
                    elif isinstance(attribute_value, list):
                        attribute_value = 'list with {} elements'.format(len(attribute_value))
                    if (attribute_value is not None) and len(attribute_value) > 100:
                        # print in red then revert to white
#                        attribute_value = '\033[33m'+'too long to display...'+'\033[0m'
                        attribute_value = '[{}]'.format(len(attribute_value))
                    line = '{:>30s} : {:<10s}'.format(attribute,str(attribute_value))
                    attr_list.append(line)
        return '\n'.join(attr_list)

    def preprocess_data(self):
        """
        reads questions2.txt and explanations2.txt and returns questions and explanations in fully processed form, i.e. questions as sequences of numbers, one number for each word, and similarly for explanations
        """
        self.load_raw()
        self.get_vocab()
        self.preprocess_exp()
        self.preprocess_questions()

        num_train = 1363
        num_val = 150
        num_test = 150
        train_indices,val_indices,test_indices = self.get_shuffled_indices(num_examples = 1663, proportions = [num_train,num_val,num_test])
        self.indices = [train_indices,val_indices,test_indices]
        self.dummy_labels_train = np.array([None]*num_train).reshape(num_train,1)
        self.dummy_labels_val = np.array([None]*num_val).reshape(num_val,1)
        self.answers_intseq2_val = self.sample_wrong_answers()

        self.exp_intseq = np.array(self.exp_intseq)
        self.questions_intseq = np.array(self.questions_intseq)
        self.answers_intseq = np.array(self.answers_intseq)
        self.get_lengths()

    def load_raw(self):
        file = open('./data/questions2.txt',encoding = 'utf-8')
        raw_question = file.readlines()
        raw_question = [self.replacer(text.strip()) for text in raw_question]

        file = open('./data/explanations2.txt','r')
        raw_exp = file.readlines()
        raw_exp = [self.replacer(text.strip()) for text in raw_exp]

        self.raw_question = raw_question
        self.raw_exp = raw_exp

    def get_vocab(self):
        raw_question = self.raw_question
        raw_exp = self.raw_exp

        char_vocab = set()
        for text in raw_exp:
            char_vocab = char_vocab | set(text)

        for text in raw_question:
            char_vocab = char_vocab | set(text)

        char_vocab = sorted(char_vocab)
        char2index = {char:i+1 for i,char in enumerate(char_vocab)}

        raw = raw_question+raw_exp
        raw = [nltk.tokenize.word_tokenize(sentence) for sentence in raw]
        max_char_in_word = max([max([len(list(word)) for word in sentence]) for sentence in raw])

        self.char_vocab = char_vocab
        self.char2index = char2index
        self.lengths.max_char_in_word = max_char_in_word

    def replacer(self,raw_sentence):
        raw_sentence = re.sub('[âÂ]','',raw_sentence,flags = re.I)
        raw_sentence = raw_sentence.replace('\x93','')
        raw_sentence = raw_sentence.replace('\x9d','')
        return raw_sentence

    def preprocess_exp(self):
        """
        make vocab dictionary for all explanations, convert explanations to integer sequence
        """
        raw_exp = self.raw_exp
        raw_exp = [self.replace_text_in_braces(line) for line in raw_exp]
        exp_tokenized = [nltk.word_tokenize(paragraph) for paragraph in raw_exp]
        exp_intseq = self.all_examples_to_intseq(self.pad(exp_tokenized))

        self.cache.raw_exp = raw_exp
        self.cache.exp_tokenized = exp_tokenized
        self.exp_intseq = exp_intseq

    def preprocess_questions(self):
        filepath = self.questions_path

        raw_question = self.raw_question
        blank_index = 0

        # remove newline characters and double quotes
        raw_question = [text.rstrip().strip('"') for text in raw_question]

        # turn question into list of separate words, make separate lists for questions and answers
        questions = []
        answers = []
        answer_options_all_questions_with_questions= []
        answer_indices = []
        for text in raw_question:
            raw_question,ans_letter = text.split(' : ')

            # correct_answer_string contains two parts, the letter answer and the answer string
            #'A' and 'sound in a loud classroom' for example.
            split_question = self.split_question_and_answers(raw_question)
            question_part = split_question[0]
            answer_part = split_question[1:]
            answer_options_all_questions_for_one_question = [self.process_sentence(sentence) for sentence in answer_part]
            answer_index = self.convert_to_int(ans_letter)
            answer_indices.append(answer_index)
            correct_ans_string = answer_options_all_questions_for_one_question[answer_index]
            ans = [ans_letter,correct_ans_string]

            # separate question into a list of words and punctuation
            tokenized_question = self.process_sentence(raw_question)
            questions.append(tokenized_question)
            answers.append(ans)
            answer_options_all_questions_with_questions.append([tokenized_question] + answer_options_all_questions_for_one_question)
            answer_options_all_questions = [part[1:] for part in answer_options_all_questions_with_questions]

        # calculate some lengths
        maxlen_question = max([len(sent) for sent in questions])
        maxlen_answer = max([max([len(sentence) for sentence in part]) for part in answer_options_all_questions])

        # make each question into a sequence of integers, use unk if word not in list
        cutoff_length = 150
        questions_intseq = self.all_examples_to_intseq(self.pad(questions, cutoff_length = cutoff_length))
        # note: didn't do padding here

        # answers_words is a list of each answer, expressed as a tokenized list of that answer sentence
        #convert every word in answers_words to its index (e.g. 'teacher' to 1456)
        answers_words = [sent for option,sent in answers]
        answers_intseq = self.all_examples_to_intseq(self.pad(answers_words,maxlen_answer))
        # note: didn't do padding here

        '''
        answer_options_all_questions is a list of tokenized answers e.g. [['large','leaves'],['shallow','roots'],...]
        all_answer_options_intseq is the same list padded and converted to integer representations
        e.g. [[0,0,0,...,]]
        '''

        padded_answer_options = [self.pad(x,maxlen_answer) for x in answer_options_all_questions]
        all_answer_options_intseq = [self.all_examples_to_intseq(answer_options) for answer_options in padded_answer_options]

        wrong_answers = [np.delete(part,index,axis = 0) for part,index in zip(all_answer_options_intseq,answer_indices)]

        self.questions_intseq = questions_intseq
        self.answers_intseq = answers_intseq

        self.raw_question = raw_question
        self.cache.questions = questions
        self.cache.answers = answers
        self.cache.answer_options_all_questions = answer_options_all_questions
        self.cache.all_answer_options_intseq = all_answer_options_intseq
        self.cache.answer_options_all_questions_with_questions = answer_options_all_questions_with_questions
        self.cache.wrong_answers = wrong_answers

    def to_intseq(self,word):
        char2index = self.char2index
        char2index['`'] = 0
        intseq = [char2index[char] for char in list(word)]

        raise_message = 0
        if raise_message and '`' in word:
            print('` detected...' ,end = '')
            print(word)
        return intseq

    def all_examples_to_intseq(self,all_examples):
        '''expects explanations or questions in tokenized form i.e. each explanation paragraph is tokenized into words
        '''
        max_char_in_word = self.lengths.max_char_in_word

        intseq = []
        for words in all_examples:
            intseq_words = [self.to_intseq(word) for word in words]
            intseq_words = pad_sequences(intseq_words,max_char_in_word)
            intseq.append(intseq_words)
        return intseq

    def get_lengths(self):
        '''because must include padding character'''
        self.lengths.maxlen_question = max([len(sent) for sent in self.questions_intseq])
        self.lengths.maxlen_raw_question = max([len(sent) for sent in self.cache.questions])
        self.lengths.maxlen_exp = max([len(sent) for sent in self.exp_intseq])
        self.lengths.num_examples = len(self.cache.questions)
        self.lengths.char2index_length = len(self.char2index) + 1
        self.lengths.maxlen_answer = self.answers_intseq.shape[1]

    def pad(self,tokenized,maxlen = None,cutoff_length = None):
        '''
        pads all examples with '' to same length to facilitate processing
        inputs are tokenized sentences/paragraphs of varying lengths
        '''
        if maxlen == None:
            maxlen = max([len(x) for x in tokenized])
        if cutoff_length == None:
            cutoff_length = maxlen
        padded = [['']*(maxlen - len(sentence)) + sentence for sentence in tokenized]
        padded = [sentence[maxlen-cutoff_length:] for sentence in padded]
        return padded

    def sample_wrong_answers(self):
        answers_intseq2 = [part[np.random.randint(len(part))] for part in self.cache.wrong_answers]
        answers_intseq2 = np.array(answers_intseq2)
        return answers_intseq2

#    def foo(self):
#        exp_tokenized = self.cache.exp_tokenized
#        question_tokenized = self.cache.questions
#
#        vocab = set()
#        for paragraph in exp_tokenized

#            exp_vocab = set()
#            for paragraph in raw_exp:
#                tokenized_paragraph = nltk.word_tokenize(paragraph)
#                exp_vocab = exp_vocab | set(tokenized_paragraph)
#            exp_vocab = sorted(exp_vocab)
#            exp_vocab_dict = {word:ind+1 for ind,word in enumerate(exp_vocab)}

#%% example

if __name__ == '__main__':
    temp = Data_char()
    temp.preprocess_data()
    print(temp)


# -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 09:54:30 2020

@author: BigB
"""

sample_name=[]

with open('./sample_type.txt') as f1:
    for i1 in f1:
        i1=i1.replace('\n', '')
        i1=i1.split('\t')
        sample_name.append(i1[0])

sample_name_num=[]

with open('./title_number.txt') as f2:
    for i2 in f2:
        i2x=i2.replace('\n', '')
        i2xx=i2x.replace(' ', '')
        i2xx=i2xx.split('\t')
        sample_name_num.append(i2xx)

exist_list=[]
total_list=[]
for sample in sample_name:
    for sample_num in sample_name_num:
        if sample == sample_num[1]:
            exist_list.append(sample_num[0])
for sample_num in sample_name_num:
    total_list.append(sample_num[0])

not_exist_list=[item for item in total_list if not item in exist_list]
for i in not_exist_list:
    print('{},'.format(i),end='')

print()


import sklearn.datasets
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
import numpy as np
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import classification_report as clsr
from modules.RankRetrieval.PreP import NLTKPreprocessor
from sklearn.metrics.pairwise import cosine_similarity
import pickle
import os
from pathlib import Path
from nltk.corpus import wordnet

'''variables'''

business = 510
entertainment = 386
politics = 417
sport = 511
tech = 401
path = 'Dataset\\bbc'

'''utility functions'''

def readFile(className,docNo):
    count = 0
    for file in os.listdir(path+'\\'+className):
        count+=1
        if count==docNo:
            fin = open(path+'\\'+className+'\\'+file,'r')
            content = fin.read()
            fin.close()
            #return (className,file,content)
            return (className,file)
    return None

def calcSim(query,exp):
    qWords = query.split()
    eWords = exp.split()
    sim = 0
    for i in range(len(qWords)):
        a = wordnet.synsets(qWords[i])
        if len(a)==0:
            sim+=1
            continue
        b = wordnet.synsets(eWords[i])
        if a[0].wup_similarity(b[0]) is not None:
            sim+= (a[0].wup_similarity(b[0]))
    return sim

def search_main(keyword):

   proData = []
   query = [keyword]
   allSim =[]

   '''reading dataset'''

   for dir in os.listdir(path):
        #className = dir
    #    print(className+'\n\n')
        filePath = path+'\\'+dir
        for file in os.listdir(filePath):
            fileName = file
            fPath = filePath+'\\'+file
            fp = open(fPath,'r')
            #converting to lower case and toeknizing
            fileContent = fp.read()
            fp.close()
            proData.append(fileContent)

   picFile = Path('pickles\\bbc\\preProData.pik')

   if picFile.exists():
        fin = open('pickles\\bbc\\preProData.pik','rb')
        proData = pickle.load(fin)
        fin.close()
   else:
        prePro = NLTKPreprocessor()
        proData = prePro.transform(proData)
        fout = open('pickles\\bbc\\preProData.pik','wb')
        pickle.dump(proData,fout)
        fout.close()

   fin = open('pickles\\bbc\\invertedInd.pik','rb')
   invertedIndex = pickle.load(fin)
   fin.close()

   '''query expansion'''

   preProc = NLTKPreprocessor()
   query = preProc.transform(query)
   qWords = query[0].split()
   dct={}
   for word in qWords:
       value=[word]
       dct[word] = value
       for syn in wordnet.synsets(word):
           for l in syn.lemmas():
               if l.name() not in value:
                   value.append(l.name())

       dct[word]=value

   allQuery = []

   def all_comb(currPos,total,newQuery):
#    print('In rec')
    if(currPos>=total):
        if list(newQuery) not in allQuery:
            allQuery.append(' '.join(list(newQuery)))
        return
    for syn in dct[qWords[currPos]]:
        newQuery.append(syn)
        all_comb(currPos+1,total,newQuery)
        newQuery.pop()

   all_comb(0,len(qWords),[])

   qSim = []

   for exp in allQuery:
       qSim.append(calcSim(query[0],exp))

   docQInv = {}
   i = -1
   for query in allQuery:
       i+=1
       qWords = query.split()
       docList = []
       for word in qWords:
           if word in invertedIndex:
               for doc in invertedIndex[word]:
                   if doc not in docList:
                       docList.append(doc)
       proDataFiltered = []
       for index in docList:
           proDataFiltered.append(proData[index])
       if len(proDataFiltered)==0:
           continue

       count_vect = CountVectorizer()
       cVector = count_vect.fit_transform(proDataFiltered)
       tfidf_transformer = TfidfTransformer()
       tVector = tfidf_transformer.fit_transform(cVector)
       cQuery = count_vect.transform([query])
       tQuery = tfidf_transformer.transform(cQuery)

       sim = cosine_similarity(tQuery, tVector)

       simScore = []
       docCount = 0
       for score in list(sim[0]):
           scoreList = []
           docCount+=1
           scoreList.append(score)
           scoreList.append(docList[docCount-1])
           simScore.append(scoreList)
           simScore.sort(key=lambda x: x[0],reverse=True)
       allSim.append(simScore[0:9])
       resultList = []

       for item in simScore[0:9]:
           docNo = item[1]+1
           if docNo not in docQInv:
               docQInv[docNo] = [[i,item[0]]]
           else:
               docQInv[docNo].append([i,item[0]])

   docScore = []
   for doc in docQInv.keys():
       tScore = 0
       for elem in docQInv[doc]:
           qNo = elem[0]
           dScore = elem[1]
           qScore = qSim[qNo]
           tScore+= dScore*qScore
       docScore.append([tScore,doc])

   docScore.sort(key=lambda x: x[0],reverse=True)
   #print(docScore)

   for item in docScore[0:9]:
    docNo = item[1]
    if docNo>business:
        docNo=docNo-business
    else:
        resultList.append(readFile('business',docNo))
        continue
    if docNo>entertainment:
        docNo=docNo-entertainment
    else:
        resultList.append(readFile('entertainment',docNo))
        continue
    if docNo>politics:
        docNo=docNo-politics
    else:
        resultList.append(readFile('politics',docNo))
        continue
    if docNo>sport:
        docNo=docNo-sport
    else:
        resultList.append(readFile('sport',docNo))
        continue
    resultList.append(readFile('tech',docNo))

   return resultList


from app.utils import helper
from app.mac import mac
from app.utils import helper
import dateparser
from modules.kalender import dbCore
import datetime, time

commands = ["!termin", "!notiz", "!hilfe", "!settings", "!show"]
termine = []
notizen = []
text = ""
dateNow = datetime.datetime.now()
global db
db = dbCore.db()
class Kalender(object):
    pass

def handle_command(message):
    try:
        command, text = message.text.split(" ", 1)
        command = command.lower()
    except:
        command = message.text.lower()
        text = ""
    if command in commands:
        command = int(commands.index(command)) + 1
        if command == 1: #termine
            handle_termin(message, text)
        elif command == 2: #notizen
            handle_notiz(message, text)
        elif command == 3: #help
            handle_help(message, text)
        elif command == 4:
            handle_settings(message, text)
        elif command == 5:
            handle_show(message, text)
        else:
            handle_help(message, text)

def handle_termin(message, text):
    #try:
    answer = handle_date(text)
    mac.send_message(answer, message.conversation)
    termine.append(text + "\n")
    nachricht = getNachricht(text)
    date, nachricht = text.split(";", 1)
    finalDate = dateparser.parse(date, settings={'PREFER_DATES_FROM': 'future', 'PREFER_DAY_OF_MONTH': 'first', 'DATE_ORDER': 'DMY'}, locales=["de"])

    if finalDate.hour == 0 and finalDate.minute == 0:
        try:
            standardTime = db.getStandardTime(str(message.conversation))
            print("Found a StandardTime!")
        except:
            #db.createSettings(str(message.conversation))
            standardTime = db.getStandardTimeDefault()
            print("Used Default StandardTime!")
        hour, minute = standardTime.split(":", 1)
        finalDate = finalDate.replace(hour=int(hour), minute=int(minute))

    db.addEntry(date=finalDate, text=nachricht, message=str(message.conversation))
    print(db.printAllDirectly())
    #searchRemind()
    #except:
    #   answer = "Fehler: Bitte geben sie ihre Anfrage in diesem Format an: !termin dd-mm-yyyy [mm:hh];*name*"
    #   mac.send_message(answer, message.conversation)
def dbArrToStr(dbArray):
    outputStr = ""
    for i in range(len(dbArray)):
        outputStr = outputStr + "Erinnerung: " + str(dbArray[i][3]) + " " + str(dbArray[i][4])+ " ID: " + str(dbArray[i][6])
        if not i == (len(dbArray) - 1):
            outputStr += "\n"
    return outputStr

def handle_notiz(message, text):
    if "showall" in text.lower():
        answer = ''.join(notizen)
        mac.send_message(answer, message.conversation)
    else:
        notizen.append(text + "\n")

def handle_date(text):
    date, nachricht = text.split(";", 1)
    finalDate = dateparser.parse(date, settings={'PREFER_DATES_FROM': 'future', 'PREFER_DAY_OF_MONTH': 'first', 'DATE_ORDER': 'DMY'}, locales=["de"])
    return "Datum: " + str(finalDate.day) + "-" + str(finalDate.month) + "-" + str(finalDate.year)

def getDate(text):
    date, nachricht = text.split(";", 1)
    return date

def getNachricht(text):
    date, nachricht = text.split(";", 1)
    return nachricht

def searchRemind():
    output = db.getAllRoot()
    now = datetime.datetime.now()
    for i in range(len(output)):
        dateObj = datetime.datetime.strptime(output[i][3], '%d-%m-%Y %H:%M')
        if dateObj <= now:
            print(str(dateObj))
            print(str(now))
            id = output[i][6]
            remindTermin(id)
            db.deleteEntry(id)

def searchRemindThread():
    db2 = dbCore.db()
    output = db2.getAllRoot()
    now = datetime.datetime.now()
    for i in range(len(output)):
        dateObj = datetime.datetime.strptime(output[i][3], '%d-%m-%Y %H:%M')
        if dateObj <= now:
            print(str(dateObj))
            print(str(now))
            id = output[i][6]
            remindTerminThread(id, db2)
            db2.deleteEntry(id)
def remindTerminThread(id, db2):
    reqObj = db2.getTermin(id)
    answer = "Erinnerung Termin: " + reqObj.dateAndTime + " " + reqObj.message
    mac.send_message(answer, reqObj.author)
    print("Reminder verschickt!")

def remindTermin(id):
    reqObj = db.getTermin(id)
    answer = "Erinnerung Termin: " + reqObj.dateAndTime + " " + reqObj.message
    mac.send_message(answer, reqObj.author)
    print("Reminder verschickt!")

def searchAlarmThread():
    db2 = dbCore.db()
    now = datetime.datetime.today()
    alarmArr = db2.getAllAlarmSettings()
    for i in range(len(alarmArr)):
        print (str(alarmArr[i]))
        alarmTest = datetime.datetime.strptime(alarmArr[i][0], "%H:%M")
        timeNow = int(str(now.hour)) * 60 * 60 + int(str(now.minute)) * 60
        timeCompare = int(str(alarmTest.hour)) * 60 * 60 + int(str(alarmTest.minute)) * 60
        print(alarmTest)
        timeDifference = timeNow - timeCompare
        if alarmTest.time() == now.time() or (timeDifference <= 600 and timeDifference > 0):
            db2.getLastAlarm()
            testTime = db2.getAlarmTime(alarmArr[i][1])
            print(testTime)
            db2Array = db2.getAllByDay(alarmArr[i][1], timeToIntegerNow())
            answer = dbArrToStr(db2Array)
            if answer:
                pass
            else:
                answer = "Heute gibt es keine Termine!"
            mac.send_message(answer, alarmArr[i][1])

def handle_help(message, text):
    help_text = """Momentane Aktionen möglich:
                    !termin dd-mm-yyyy [mm:hh];*name*
                    !show heute;morgen;woche;monat
                    !settings
                    !help"""
    mac.send_message(help_text, message.conversation)

def timeToIntegerNow():
    return int(str(dateNow.year) + str(dateNow.month) + str(dateNow.day))

def timeToInteger(dateReq):
    return int(str(dateReq.year) + str(dateReq.month) + str(dateReq.day))

def handle_show(message, text):
    if "showall" in text.lower():
        dbArray = db.getAllUser(str(message.conversation))
        answer = dbArrToStr(dbArray)

    elif "heute" in text.lower():
        dbArray = db.getAllByDay(str(message.conversation), timeToIntegerNow())
        answer = dbArrToStr(dbArray)

    elif "morgen" in text.lower():
        dateReq = datetime.date.today() + datetime.timedelta(days=1)
        dbArray = db.getAllByDay(str(message.conversation), timeToInteger(dateReq))
        answer = dbArrToStr(dbArray)

    elif "woche" in text.lower():
        dateReq1 = datetime.datetime.now()
        dateReq2 = datetime.date.today() + datetime.timedelta(days=7)
        dbArray = db.getAllByDays(str(message.conversation), timeToInteger(dateReq1), timeToInteger(dateReq2))
        answer = dbArrToStr(dbArray)

    elif "monat" in text.lower():
        dateReq1 = datetime.datetime.now()
        dateReq2 = datetime.date.today() + datetime.timedelta(days=30)
        dbArray = db.getAllByDays(str(message.conversation), timeToInteger(dateReq1), timeToInteger(dateReq2))
        answer = dbArrToStr(dbArray)
    else:
        answer = """Befehl nicht gefunden!
                    !show heute;morgen;woche;monat"""
    if answer:
        mac.send_message(answer, message.conversation)
    else:
        answer = "Keine Termine für diese Zeit."
        mac.send_message(answer, message.conversation)

def handle_settings(message, text):
    userSettings = db.getUserSettings()


#!/usr/bin/env python
# coding: utf-8

import os
import re
from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))

def load_readme():
    with open(os.path.join(here, 'README.rst')) as f:
        return f.read()

def load_required_modules():
    with open(os.path.join(here, "requirements.txt")) as f:
        return [line.strip() for line in f.readlines() if line.strip()]

setup(
    name='owlmixin',
    version=re.search(
        r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]',  # It excludes inline comment too
        open('owlmixin/__init__.py').read()).group(1),
    description='Mixin which converts ``data class instance`` and others each other more simple.',
    long_description=load_readme(),
    license='MIT',
    author='tadashi-aikawa',
    author_email='syou.maman@gmail.com',
    maintainer='tadashi-aikawa',
    maintainer_email='tadashi-aikawa',
    url='https://github.com/tadashi-aikawa/owlmixin.git',
    keywords='data class mixin instance dict json yaml csv convert parse each other functional',
    packages=find_packages(exclude=['tests*']),
    install_requires=load_required_modules(),
    extras_require={
        'test': ['pytest', 'pytest-cov']
    },
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Utilities',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6'
    ],
)


from db_u.tools import TbModel

class RelayControl:

    @classmethod
    def on(cls):
        cls.change_state(cls.on_value)

    @classmethod
    def off(cls):
        cls.change_state(1 - cls.on_value)

    @classmethod
    def get_state(cls):
        return cls._value()

    @classmethod
    def change_state(cls, _set=None):

        if _set is not None:
            cls._value(_set)
        else:
            cls._value(1 - cls._value())

        state = cls._value()
        if cls._cb:
            cls._cb(state)

        return state

class RelayModel(TbModel):

    def _func(self):

        self.relay_ctrl = RelayControl
        self.relay_ctrl.on_value = self.p_on
        self.relay_ctrl._cb = self.cb

    def cb(self, state):
        st = "OFF"
        if state == self.p_on:
            st = "ON"
        self.mbus.pub_h("relay/{}/state".format(self.name), st)


# -*- mode: python; coding: utf-8 -*-
# Copyright 2020 the AAS WorldWide Telescope project
# Licensed under the MIT License.

"""
Support for loading images from a Djangoplicity database.
"""

__all__ = """
DjangoplicityImageSource
DjangoplicityCandidateInput
""".split()

import codecs
from contextlib import contextmanager
from datetime import datetime, timezone
import functools
import html
import json
import numpy as np
import os.path
import requests
import shutil
from urllib.parse import urljoin, quote as urlquote
import yaml

from ..image import ImageLoader
from . import CandidateInput, ImageSource, NotActionableError

class DjangoplicityImageSource(ImageSource):
    """
    An ImageSource that obtains its inputs from a query to a Djangoplicity website.
    """

    _base_url = None
    _channel_name = None
    _search_page_name = None
    _force_insecure_tls = True  # TODO: migrate to False

    @classmethod
    def get_config_key(cls):
        return "djangoplicity"

    @classmethod
    def deserialize(cls, data):
        inst = cls()
        inst._base_url = data["base_url"]
        inst._channel_name = data["channel_name"]
        inst._search_page_name = data.get("search_page_name", "page")
        inst._force_insecure_tls = data.get(
            "force_insecure_tls", True
        )  # TODO: migrate to false
        return inst

    @contextmanager
    def make_request(self, url, stream=False, none404=False):
        """force_insecure_tls is for noirlab.edu"""

        with requests.get(
            url, stream=stream, verify=not self._force_insecure_tls
        ) as resp:
            if none404 and resp.status_code == 404:
                yield None
                return

            if not resp.ok:
                raise Exception(f"error fetching url `{url}`: {resp.status_code}")

            if stream:
                # By default, `resp.raw` does not perform content decoding.
                # eso.org gives us gzipped content. The following bit is
                # apparently the preferred workaround. Cf:
                # https://github.com/psf/requests/issues/2155
                #
                # A side effect of the content decoding, however, is that the
                # first read of the stream can return a zero-length string,
                # which causes `readlines` iteration to exit. Callers must be
                # prepared to handle this.
                resp.raw.decode_content = True

            yield resp

    def query_candidates(self):
        page_num = 1

        while True:
            url = (
                self._base_url
                + f"archive/search/{self._search_page_name}/{page_num}/?type=Observation"
            )
            print(f"requesting {url} ...")

            with self.make_request(url, stream=True, none404=True) as resp:
                if resp is None:
                    break  # got a 404 -- all done

                text_stream = codecs.getreader("utf8")(resp.raw)
                json_lines = []

                # Cf. stream=True in make_request -- skip the zero-length result
                # to prevent readlines iteration from exiting early. This is
                # definitely OK since our `var images` line won't be the first
                # line.
                text_stream.readline()

                for line in text_stream:
                    if not len(json_lines):
                        if "var images = [" in line:
                            json_lines.append("[")
                    elif "];" in line:
                        json_lines.append("]")
                        break
                    else:
                        json_lines.append(line)

            if not len(json_lines):
                raise Exception(
                    f'error processing url {url}: no "var images" data found'
                )

            # This is really a JS literal, but YAML is compatible enough.
            # JSON does *not* work because the dict keys here aren't quoted.
            data = yaml.safe_load("".join(json_lines))

            for item in data:
                yield DjangoplicityCandidateInput(item)

            page_num += 1

    def fetch_candidate(self, unique_id, cand_data_stream, cachedir):
        url = self._base_url + urlquote(unique_id) + "/api/json/"

        with self.make_request(url) as resp:
            info = json.loads(resp.content)

        # Find the "fullsize original" image URL

        fullsize_url = None

        for resource in info["Resources"]:
            if resource.get("ResourceType") == "Original":
                fullsize_url = resource["URL"]
                break

        if fullsize_url is None:
            raise Exception(
                f'error processing {unique_id}: can\'t identify "fullsize original" image URL'
            )

        ext = fullsize_url.rsplit(".", 1)[-1].lower()
        info["toasty_image_extension"] = ext

        # Validate that there's actually WCS we can use

        if not isinstance(info.get("Spatial.CoordsystemProjection", None), str):
            raise NotActionableError("image does not have full WCS")

        # Download it

        with self.make_request(fullsize_url, stream=True) as resp:
            with open(os.path.join(cachedir, "image." + ext), "wb") as f:
                shutil.copyfileobj(resp.raw, f)

        with open(os.path.join(cachedir, "metadata.json"), "wt", encoding="utf8") as f:
            json.dump(info, f, ensure_ascii=False, indent=2)

    def process(self, unique_id, cand_data_stream, cachedir, builder):
        # Set up the metadata.

        with open(os.path.join(cachedir, "metadata.json"), "rt", encoding="utf8") as f:
            info = json.load(f)

        img_path = os.path.join(cachedir, "image." + info["toasty_image_extension"])
        md = DjangoplicityMetadata(info)

        # Load up the image.

        img = ImageLoader().load_path(img_path)

        # Do the processing.

        builder.tile_base_as_study(img)
        builder.make_thumbnail_from_other(img)

        builder.imgset.set_position_from_wcs(
            md.as_wcs_headers(img.width, img.height),
            img.width,
            img.height,
            place=builder.place,
        )

        builder.set_name(info["Title"])
        builder.imgset.credits_url = info["ReferenceURL"]
        builder.imgset.credits = html.escape(info["Credit"])
        builder.place.description = html.escape(info["Description"])

        # Annotation metadata

        pub_dt = datetime.fromisoformat(info["Date"])
        if pub_dt.tzinfo is None:
            pub_dt = pub_dt.replace(tzinfo=timezone.utc)

        amd = {
            "channel": self._channel_name,
            "itemid": unique_id,
            "publishedUTCISO8601": pub_dt.isoformat(),
        }
        builder.place.annotation = json.dumps(amd)

        # Finally, crunch the rest of the pyramid.

        builder.cascade()

class DjangoplicityCandidateInput(CandidateInput):
    """
    A CandidateInput obtained from an AstroPix query.
    """

    def __init__(self, info):
        self._info = info

    def get_unique_id(self):
        return self._info["id"]

    def save(self, stream):
        with codecs.getwriter("utf8")(stream) as text_stream:
            json.dump(self._info, text_stream, ensure_ascii=False, indent=2)

class DjangoplicityMetadata(object):
    metadata = None

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

    def as_wcs_headers(self, width, height):
        """
        The metadata here are essentially AVM headers. As described in
        `Builder.apply_avm_info()`, the data that we've seen in the wild are a
        bit wonky with regards to parity: the metadata essentially correspond to
        FITS-like parity, and we need to flip them to JPEG-like parity. See also
        very similar code in `astropix.py`.
        """
        headers = {}

        # headers['RADECSYS'] = self.wcs_coordinate_frame  # causes Astropy warnings
        headers["CTYPE1"] = "RA---" + self.metadata["Spatial.CoordsystemProjection"]
        headers["CTYPE2"] = "DEC--" + self.metadata["Spatial.CoordsystemProjection"]
        headers["CRVAL1"] = float(self.metadata["Spatial.ReferenceValue"][0])
        headers["CRVAL2"] = float(self.metadata["Spatial.ReferenceValue"][1])

        # See Calabretta & Greisen (2002; DOI:10.1051/0004-6361:20021327), eqn 186
        crot = np.cos(float(self.metadata["Spatial.Rotation"]) * np.pi / 180)
        srot = np.sin(float(self.metadata["Spatial.Rotation"]) * np.pi / 180)
        scale0 = float(self.metadata["Spatial.Scale"][0])

        # Seen in noao-02274; guessing how to handle this
        if not self.metadata["Spatial.Scale"][1]:
            scale1 = np.abs(scale0)
        else:
            scale1 = float(self.metadata["Spatial.Scale"][1])

        lam = scale1 / scale0

        pc1_1 = crot
        pc1_2 = -lam * srot
        pc2_1 = srot / lam
        pc2_2 = crot

        # If we couldn't get the original image, the pixel density used for
        # the WCS parameters may not match the image resolution that we have
        # available. In such cases, we need to remap the pixel-related
        # headers. From the available examples, `wcs_reference_pixel` seems to
        # be 1-based in the same way that `CRPIXn` are. Since in FITS, integer
        # pixel values correspond to the center of each pixel box, a CRPIXn of
        # [0.5, 0.5] (the lower-left corner) should not vary with the image
        # resolution. A CRPIXn of [W + 0.5, H + 0.5] (the upper-right corner)
        # should map to [W' + 0.5, H' + 0.5] (where the primed quantities are
        # the new width and height).

        factor0 = width / float(self.metadata["Spatial.ReferenceDimension"][0])
        factor1 = height / float(self.metadata["Spatial.ReferenceDimension"][1])

        headers["CRPIX1"] = (
            float(self.metadata["Spatial.ReferencePixel"][0]) - 0.5
        ) * factor0 + 0.5
        headers["CRPIX2"] = (
            float(self.metadata["Spatial.ReferencePixel"][1]) - 0.5
        ) * factor1 + 0.5

        # Now finalize and apply the parity flip.

        cdelt1 = scale0 / factor0
        cdelt2 = scale1 / factor1
        headers["CD1_1"] = cdelt1 * pc1_1
        headers["CD1_2"] = -cdelt1 * pc1_2
        headers["CD2_1"] = cdelt2 * pc2_1
        headers["CD2_2"] = -cdelt2 * pc2_2
        headers["CRPIX2"] = height + 1 - headers["CRPIX2"]

        return headers


# 파일명 : s0121_test1.py

pocket = input("소지물품: ").split()
if "현금" in pocket:
    money = int(input("소지현금: "))
card = input("카드 소지 [y/n]:").lower() in ['yes', 'no']

if money >= 3000 :
    print("택시타")
elif card :
    print("택시타")
else :
    print("걸어가")


import asyncio
from unittest.mock import Mock

from ext.telegram.bot import TelegramBot, TelegramBotCommand

def test_create_bot_instance():
    bot = TelegramBot('token', 'test_bot')
    assert bot.api
    assert bot.logger
    assert bot.url == 'https://telegram.me/test_bot'
    assert bot.name == 'test_bot'
    assert not list(bot.commands)

def test_add_bot_command():

    class CmdFoo(TelegramBotCommand):
        name = 'foo'

    bot = TelegramBot('token', 'bot_name')
    bot.add_command(CmdFoo)
    commands = list(bot.commands)
    assert len(commands) == 1
    assert commands[0] == 'foo'

def test_execute_bot_command():
    mock = Mock()

    class TestHelpCommand(TelegramBotCommand):
        name = 'help'

        async def execute(self, message):
            mock()

    bot = TelegramBot('token', 'bot_name')
    bot.add_command(TestHelpCommand)
    update = {
        'message': {
            'text': '/help',
            'message_id': 2666,
            'date': 1465764948,
            'chat': {
                'id': 425606,
                'username': 'djudman',
                'last_name': 'Dorofeev',
                'type': 'private',
                'first_name': 'Dmitry'
            },
            'entities': [
                {
                    'offset': 0,
                    'length': 5,
                    'type': 'bot_command'
                }
            ],
            'from': {
                'id': 425606,
                'username': 'djudman',
                'last_name': 'Dorofeev',
                'first_name': 'Dmitry'
            }
        },
        'update_id': 84506398
    }
    loop = asyncio.get_event_loop()
    loop.run_until_complete(bot.handle_update(update))
    mock.assert_called_once_with()

def test_on_text_callback():
    mock = Mock()

    class MyBot(TelegramBot):
        async def on_text(self, message):
            mock()

    bot = MyBot('token', 'test_bot')
    update = {
        'message': {
            'chat': {
                'id': 425606,
                'username': 'djudman',
                'last_name': 'Dorofeev',
                'type': 'private',
                'first_name': 'Dmitry'
            },
            'text': 'test text',
            'from': {
                'id': 425606,
                'username': 'djudman',
                'last_name': 'Dorofeev',
                'first_name': 'Dmitry'
            },
            'date': 1465821925,
            'message_id': 2668
        },
        'update_id': 84506399
    }
    loop = asyncio.get_event_loop()
    loop.run_until_complete(bot.handle_update(update))
    mock.assert_called_once_with()


import tensorflow as tf, numpy as np
from utility.exp_replay import ExpReplay
from utility.loss import huber_loss, minimize_and_clip
from utility.utility import get_path
from utility.model import mlp

class MLPDQN(object):
    def __init__(self, params):
        self._env = params['env']
        self.save_path = get_path('tf_log/' + params['env_name'])
        self.logger = params['logger']
        gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
        self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
        self.graph = self.build_graph()
        self.saver = tf.train.Saver()
        self.replay = ExpReplay(50000)
        self.sess.run(tf.global_variables_initializer())

    def take_action(self, obs, eps):
        if np.random.random() < eps:
            return np.random.randint(self._env.action_space.n)
        return self.sess.run(self.graph['act'], feed_dict={self.graph['s']: np.array(obs)[None]})[0]

    def build_graph(self):
        s = tf.placeholder(tf.float32, [None] + list(self._env.observation_space.shape))
        a = tf.placeholder(tf.int32, [None])
        r = tf.placeholder(tf.float32, [None])
        t = tf.placeholder(tf.float32, [None])
        s_ = tf.placeholder(tf.float32, [None] + list(self._env.observation_space.shape))

        network_shape = [list(self._env.observation_space.shape)[0], 512, 512, 512, self._env.action_space.n]
        with tf.variable_scope('q_net', reuse=False):
            q, q_net_w = mlp(s, network_shape)
        q_var = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_net')

        act = tf.argmax(q, axis=1)

        with tf.variable_scope('q_target_net', reuse=False):
            q_target, q_target_w = mlp(s_, network_shape)
        q_target_var = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_target_net')

        q_selected = tf.reduce_sum(q * tf.one_hot(a, self._env.action_space.n), 1)
        q_target_best = tf.reduce_max(q_target, 1)

        q_target_best_masked = (1.0 - t) * q_target_best

        q_target_selected = r + 1.0 * q_target_best_masked
        error = q_selected - tf.stop_gradient(q_target_selected)
        loss = tf.reduce_mean(huber_loss(error))

        opt = tf.train.AdamOptimizer(learning_rate=0.001)
        train_op = minimize_and_clip(opt, loss, q_var)

        update_target_expr = [tf.assign(t, o) for t, o in zip(q_target_w, q_net_w)]

        return {'act': act, 's': s, 'a': a, 'r': r, 't': t, 's_': s_, 'train_op': train_op,
                'loss': loss, 'update_target_expr': update_target_expr}

    def store_transition(self, s, a, r, t, s_):
        self.replay.add(s, a, r, float(t), s_)

    def train(self):
        s, a, r, t, s_ = self.replay.batch(512)
        _, loss = self.sess.run([self.graph['train_op'], self.graph['loss']],
                                feed_dict={self.graph['s']: s, self.graph['a']: a, self.graph['r']: r,
                                           self.graph['t']: t, self.graph['s_']: s_, })
        return loss

    def update_target(self):
        self.sess.run(self.graph['update_target_expr'])

    def load(self):
        checkpoint = tf.train.get_checkpoint_state(self.save_path)
        if checkpoint and checkpoint.model_checkpoint_path:
            self.saver.restore(self.sess, checkpoint.model_checkpoint_path)
            self.logger.info('Successfully loaded: %s' % checkpoint.model_checkpoint_path)
            return True
        else:
            self.logger.info('Could not find old network weights')
            return False

    def save(self):
        self.saver.save(self.sess, self.save_path + '/model.ckpt')


#!/usr/bin/python3

import random
import math

def exp(t) :
    return math.log(random.random())*(-1)/t

class Event :
    def __init__(self, pid, arrive_time, cpu_time) :
        self.pid = pid
        self.arrive_time = arrive_time
        self.cpu_time = cpu_time
        self.departure_time =  0.0
        self.event_time = arrive_time
        self.state = 'ARRIVE'

    def __lt__(self, other) :
        return self.event_time < other.arrive_time

    def __le__(self, other) :
        return self.event_time <= other.arrive_time

    def __eq__(self, other) :
        return self.event_time == other.arrive_time

    def __ne__(self, other) :
        return self.event_time != other.arrive_time

    def __gt__(self, other) :
        return self.event_time > other.arrive_time

    def __ge__(self, other) :
        return self.event_time >= other.arrive_time

    def __str__(self) :
        return 'pid={:05d}, state={:10s}, event_t={:5f}, arrive_t={:5f}, cpu_t={:5f}, departure_t={:5f}'.format(\
                self.pid, self.state, self.event_time, self.arrive_time, self.cpu_time, self.departure_time)

class Simulate :
    def __init__(self, init_event_num) :
        self.event_queue = []
        self.wait_queue = []
        self.done_event_queue = []

        self.cpu_running = False
        self.current_time = 0.0
        self.package_num = 0
        self.package_departored = 0

        self.total_system_time = 0.0
        self.average_system_time = 0.0
        self.average_package_num = 0.0

        for i in range(0, init_event_num) :
            self.create_new_event(i)

    def create_new_event(self, pid) :
        arrive_time = self.current_time + self.event_arrive_time()
        cpu_time = self.event_cpu_time()
        event = Event(pid, arrive_time, cpu_time)
        self.event_queue.append(event)
        self.event_queue.sort()

    def next(self) :
        event = self.event_queue.pop(0)

        pre_time = self.current_time
        if self.current_time < event.event_time :
            self.current_time = event.event_time

        # count average package number
        self.average_package_num += ((self.current_time - pre_time) * self.package_num) / self.current_time
        # print('average packet num={}'.format(self.average_package_num))

        if event.state == 'ARRIVE' :
            self.package_num += 1

            event.state = 'WAIT'
            # print('current_t={:06f}'.format(self.current_time), event)
            self.wait_queue.append(event)
            self.create_new_event(event.pid)

        elif event.state == 'DEPARTURE' :
            self.package_num -= 1
            self.package_departored += 1
            self.cpu_running = False
            # print('current_t={:06f}'.format(self.current_time), event)

            # count average system time ( departure - arrive )
            self.total_system_time += event.departure_time - event.arrive_time
            self.average_system_time = self.total_system_time / self.package_departored
            # print('average system time={}'.format(self.average_system_time))

        if len(self.wait_queue) > 0 and not self.cpu_running :
            event = self.wait_queue.pop(0)
            event.departure_time = self.current_time + event.cpu_time
            event.event_time = event.departure_time
            event.state = 'DEPARTURE'
            self.event_queue.append(event)
            self.cpu_running = True

class CaseABC (Simulate) :
    def __init__(self, num, gamma, mu) :
        self.gamma = gamma
        self.mu = mu
        Simulate.__init__(self, num)

    def event_arrive_time(self) :
        return exp(self.gamma)

    def event_cpu_time(self) :
        return exp(self.mu)

class CaseD (Simulate) :
    def __init__(self, num, gamma, mu) :
        self.gamma = gamma
        self.mu = mu
        Simulate.__init__(self, num)

    def event_arrive_time(self) :
        return exp(self.gamma)

    def event_cpu_time(self) :
        return self.mu

def main() :
    total_time = 10000

    for gamma in [0.01, 0.2, 0.6, 1.0, 1.4, 1.8] :
        mu = 10
        case = 'A'

        simulate = CaseABC(5, gamma, mu)
        while simulate.current_time < total_time :
            simulate.next()

        print("case {} [time, gamma, mu]=[{}, {:3.2f}, {}] -> average [package, system time]=[{}, {}]".format(\
                case, total_time, gamma, mu, simulate.average_package_num, simulate.average_system_time))

    for gamma in [0.02, 0.4, 1.2, 2.0, 2.8, 3.6] :
        mu = 20
        case = 'B'

        simulate = CaseABC(5, gamma, mu)
        while simulate.current_time < total_time :
            simulate.next()

        print("case {} [time, gamma, mu]=[{}, {:3.2f}, {}] -> average [package, system time]=[{}, {}]".format(\
                case, total_time, gamma, mu, simulate.average_package_num, simulate.average_system_time))

    for gamma in [0.05, 1.0, 3.0, 5.0, 7.0, 9.0] :
        mu = 50
        case = 'C'

        simulate = CaseABC(5, gamma, mu)
        while simulate.current_time < total_time :
            simulate.next()

        print("case {} [time, gamma, mu]=[{}, {:3.2f}, {}] -> average [package, system time]=[{}, {}]".format(\
                case, total_time, gamma, mu, simulate.average_package_num, simulate.average_system_time))

    for gamma in [0.05, 1.0, 3.0, 5.0, 7.0, 9.0] :
        mu = 0.02
        case = 'D'

        simulate = CaseD(5, gamma, mu)
        while simulate.current_time < total_time :
            simulate.next()

        print("case {} [time, gamma, static_mu]=[{}, {:3.2f}, {}] -> average [package, system time]=[{}, {}]".format(\
                case, total_time, gamma, mu, simulate.average_package_num, simulate.average_system_time))

def test() :
    for i in range(0, 100000) :
        print(exp(50))

if __name__ == '__main__' :
    test()
    #main()


# uncompyle6 version 3.7.4
# Python bytecode 2.6 (62161)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-i686/egg/coils/protocol/dav/workflow/versionsfolder.py
# Compiled at: 2012-10-12 07:02:39
import os
from coils.core import *
from coils.net import *
from bpmlobject import BPMLObject
from yamlobject import YAMLObject
from utility import route_versions, process_versions

class VersionsFolder(DAVFolder):

    def __init__(self, parent, name, **params):
        DAVFolder.__init__(self, parent, name, **params)

    def supports_PUT(self):
        return True

    def _load_contents(self):
        self.data = {}
        if isinstance(self.entity, Route):
            for edition in route_versions(self.entity):
                name = ('{0}.{1}.bpml').format(self.entity.name, edition)
                self.insert_child(name, BPMLObject(self, name, entity=self.entity, version=edition, context=self.context, request=self.request))

        elif isinstance(self.entity, Process):
            for edition in process_versions(self.entity):
                name = ('{0}.{1}.yaml').format(self.entity.object_id, edition)
                self.insert_child(name, YAMLObject(self, name, entity=self.entity, version=edition, context=self.context, request=self.request))

        else:
            return False
        return True

    def object_for_key(self, name, auto_load_enabled=True, is_webdav=False):
        if self.load_contents():
            if self.has_child(name):
                return self.get_child(name)
        raise self.no_such_path()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import List

def convert_to_absolute() -> float:
    nombre = float(input('Veuillez entrer un nombre: '))

    if nombre >= 0:
        return nombre
    else:
        return nombre*-1

def use_prefixes() -> List[str]:
    prefixes, suffixes = 'JKLMNOP', 'ack'

    i = 0
    chaine_noms = []

    while i < len(prefixes): # jusqu'au dernier caractere
        chaine_noms.append(prefixes[i] + suffixes)
        i+=1

    return chaine_noms

def prime_integer_summation() -> int:
    cpt_cent = 0
    nombre = 2
    somme_des_cent_premiers = 0
    nombre_est_premier = False

    while cpt_cent < 99:
        for i in range(2, nombre):
            if (nombre % i) == 0: # si ce n'est pas un nombre premier
                nombre_est_premier = False
                break
            else: # si c'est un nombre premier
                nombre_est_premier = True

        if nombre_est_premier:
            cpt_cent += 1
            somme_des_cent_premiers += nombre

        nombre += 1

    return somme_des_cent_premiers + 2

def factorial(number: int) -> int:
    factorielle = 1

    for i in range(1, number+1):
        factorielle = factorielle*i
    return factorielle

def use_continue() -> None:
    i = 1

    while i <= 10:
        if i == 5:  # ne pas afficher 5
            i += 1
            continue
        print(i, " ", end="")
        i+=1

def main() -> None:
    print(f"La valeur absolue du nombre est {convert_to_absolute()}")

    print(f"La liste des noms générés avec les préfixes est: {use_prefixes()}")

    print(f"La somme des nombres de 0 à 100 est: {prime_integer_summation()}")

    number = 10
    print(f"La factiorelle du nombre {number} est: {factorial(number)}")

    print(f"L'affichage de la boucle est:")
    use_continue()

if __name__ == '__main__':
    main()


from django.shortcuts import render
from django.http import HttpResponse
from .models import Transacao
from .form import TransacaoForm
import datetime

def home(request):
    data = {}
    data['transacoes'] = ['1','2','3']
    data['now'] = datetime.datetime.now()
    # html = str.format("It's now {0}", now)
    # return HttpResponse(html)
    return render(request, 'contas/home.html', data)
# Create your views here.

def listagem(request):
    data = {}
    data['transacoes'] = Transacao.objects.all()
    return render(request, 'contas/listagem.html', data)

def nova_transacao(request):
    data = {}
    form = TransacaoForm()
    form = []
    data['form'] = form
    return render(request, 'contas/form.html', data)


def Mensagem():

	x = 10
	y = 1
	x -= 1 #x=x-1
	y += 2 #y=y+2
	x = x-1
	y = y+2
	x = x-1
	y = y+2

	if x > y: # if = se

		return "X ficou maior que Y"

	elif x < y: #elif = senao se

		return "X ficou menor que Y"

	else: # else =senao

		return " X e Y ficaram iguais"

print(Mensagem())


#!/usr/bin/env python

# ENCODE DCC Cutadapt wrapper
# Author: Frankie James (fjames003)

import sys
import os
import re
import argparse
import multiprocessing
from encode_common_genomic import *

def parse_arguments():
    parser = argparse.ArgumentParser(prog='ENCODE DCC Cutadapt adapter trimmer.',
                                        description='')
    parser.add_argument('fastqs', nargs='+', type=str,
                        help='List of FASTQs (R1 and R2). \
                            FASTQs must be compressed with gzip (with .gz).')
    parser.add_argument('--paired-end', action="store_true",
                        help='Paired-end FASTQs.')
    parser.add_argument('--nth', type=int, default=1,
                        help='Number of threads to parallelize.')
    parser.add_argument('--out-dir', default='', type=str,
                            help='Output directory.')
    parser.add_argument('--log-level', default='INFO',
                        choices=['NOTSET','DEBUG','INFO',
                            'WARNING','CRITICAL','ERROR','CRITICAL'],
                        help='Log level')
    args = parser.parse_args()

    # check if fastqs have correct dimension
    if args.paired_end and len(args.fastqs)!=2:
        raise argparse.ArgumentTypeError('Need 2 fastqs for paired end.')
    if not args.paired_end and len(args.fastqs)!=1:
        raise argparse.ArgumentTypeError('Need 1 fastq for single end.')

    log.setLevel(args.log_level)
    log.info(sys.argv)
    return args

def cutadapt_se(fastq, nth, out_dir):
    basename = os.path.basename(strip_ext_fastq(fastq))
    prefix = os.path.join(out_dir, basename)
    fastq_out = "{}.trimmed.fastq.gz".format(prefix)

    cmd =  'cutadapt -j {} '
    cmd += '--length 36 --minimum-length 35 '
    cmd += '--trim-n -e 0.1 -q 30 '
    cmd += '-a GATCGGAAGAGCACACGTCTGAACTCCAGTCAC -A GATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT '
    cmd += '-o {} '
    cmd += '{}'
    cmd = cmd.format(nth, fastq_out, fastq1)

    run_shell_cmd(cmd)

    return fastq_out

def cutadapt_pe(fastq1, fastq2, nth, out_dir):
    basename1 = os.path.basename(strip_ext_fastq(fastq1))
    prefix1 = os.path.join(out_dir, basename1)
    fastq_out1 = "{}.trimmed.fastq.gz".format(prefix1)

    basename2 = os.path.basename(strip_ext_fastq(fastq2))
    prefix2 = os.path.join(out_dir, basename2)
    fastq_out2 = "{}.trimmed.fastq.gz".format(prefix2)

    cmd =  'cutadapt -j {} '
    cmd += '--length 36 --minimum-length 35 '
    cmd += '--trim-n -e 0.1 -q 30 '
    cmd += '-a GATCGGAAGAGCACACGTCTGAACTCCAGTCAC -A GATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT '
    cmd += '-o {} -p {} '
    cmd += '{} '
    cmd += '{}'
    cmd = cmd.format(nth, fastq_out1, fastq_out2, fastq1, fastq2)

    run_shell_cmd(cmd)

    return fastq_out1, fastq_out2

def main():
    # read params
    args = parse_arguments()

    log.info('Initializing and making output directory...')
    mkdir_p(args.out_dir)

    # declare temp arrays
    temp_files = [] # files to deleted later at the end

    # STAR
    log.info('Running Cutadapt...')
    if args.paired_end:
        fastq_out1, fastq_out2 = cutadapt_pe(args.fastqs[0], args.fastqs[1], args.nth, args.out_dir)
    else:
        fastq_out1 = cutadapt_se(args.fastqs[0], args.nth, args.out_dir)

    log.info('Removing temporary files...')
    rm_f(temp_files)

    log.info('List all files in output directory...')
    ls_l(args.out_dir)

    log.info('All done.')

if __name__=='__main__':
    main()


'''
2020Oct20
전체 대여소를 그룹으로 묶기. 한 그룹당 대여소 20여개.
상시 업데이트하는 용도의 파일이 아니라 회원 관리 쪽에 들어갈 데이터를 만들어두는 용도.
입력 파일 : station_info.csv
출력 파일 : area.csv
출력 형태 : 102 그룹. 한 row가 한 개의 그룹(20여개의 위경도 tuple)
'''
import pandas as pd

df = pd.read_csv( './station_info.csv', encoding = 'utf-8' )

lat_lst_temp = df['stationLatitude'].values.tolist()
lon_lst_temp = df['stationLongitude'].values.tolist()
lat_lon = [(lat_lst_temp[k], lon_lst_temp[k]) for k in range(len(lat_lst_temp))]
lat_lst = sorted(lat_lon, key = lambda x : x[0])
lon_lst = sorted(lat_lon, key = lambda x : x[1])

result = []
flag = False
while True:
    temp = []
    while True:
        temp.append(lat_lst.pop(0))
        temp.append(lon_lst.pop(0))
        if len(set(temp)) >= 20: break
        if len(lat_lst) < 20:
            temp.extend(lat_lst)
            flag = True
            break
        lst_int = list(set(lat_lst) & set(lon_lst))
        lat_lst = sorted(lst_int, key=lambda x: x[0])
        lon_lst = sorted(lst_int, key=lambda x: x[1])
    result.append(list(set(temp)))
    if flag: break

df_result = pd.DataFrame(result)
df_result.to_csv( 'area.csv', index = False )

print(df_result)


# Copyright 2018 Benjamin Bueno (bbueno5000) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Plot the data gathered from StarCraft II experiments.
"""
from collections import defaultdict
from dill import load as dill_load
from matplotlib import pyplot
from numpy import add as np_add
from numpy import array as np_array
from numpy import cumsum as np_cumsum
from numpy import digitize as np_digitize
from numpy import float32 as np_float32    # pylint: disable=E0611
from numpy import linspace as np_linspace
from numpy import where as np_where
from numpy import zeros as np_zeros
from pandas import DataFrame as pd_DataFrame
from pandas import Series as pd_Series
from seaborn import tsplot

MAX_TSTEPS = int(2e3)
NSAMPLES = 100

def main():
    with open("pysc2/data/results.pkl", 'rb') as file:
        results = dill_load(file)
    experiment_labels = {'starcraft-a': "Double Q Learning",
                         'starcraft-duel-a': "Dueling Double Q Learning",
                         'starcraft-prior-a': "Double Q Learning with Prioritized Replay",
                         'starcraft-prior-duel-a': "Dueling Double Q Learning with Prioritized Replay"}
    experiments = experiment_labels.keys()
    agent_data = defaultdict(lambda: defaultdict(lambda: []))
    for experiment in experiments:
        for name, data in results.items():
            if name.startswith(experiment):
                agent = data['agent_id']
                times = np_cumsum(data['episode_data']['episode_lengths'])
                rewards = np_array(data['episode_data']['episode_rewards'])
                rewards = rewards[times < MAX_TSTEPS]
                times = times[times < MAX_TSTEPS]
                agent_data[agent][experiment].append((times, rewards))
    experiments_to_plot = ['starcraft-a']
    plot_experiments(experiment_labels, experiments_to_plot, agent_data)

def plot_experiments(experiment_name, experiments_to_plot, agent_data, ncols=4):
    """
    Given a set of experiments, plot them in a line graph.
    experiments_to_plot: Chosen experiments to plot.
    """
    colors = ['red', 'green', 'blue', 'yellow', 'magenta', 'cyan']
    assert len(colors) >= len(experiments_to_plot)
    color_legend = dict(zip(experiments_to_plot, colors))
    # Print the legend
    for experiment, color in color_legend.items():
        print(color, ":", experiment_name[experiment])
    # Select relevant games for those experiments
    all_games = list(agent_data.keys())
    relevant_agents = [g for g in all_games if any(e in agent_data[g] for e in experiments_to_plot)]
    # Create the figure
    # TODO: fix figures columns and rows
    # ncols = min(ncols, len(relevant_agents))
    # nrows = (len(relevant_agents) + ncols - 1) // ncols
    ncols = 2
    nrows = 2
    _, axes = pyplot.subplots(nrows, ncols, figsize=(5 * ncols, 5 * nrows))
    if nrows == 1:
        axes = [axes]
    # Plot the data
    for index, agent in enumerate(sorted(relevant_agents)):
        ax = axes[index // ncols][index % ncols]
        ax.set_title(agent)
        for experiment_label, experiment_data in agent_data[agent].items():
            if experiment_label in experiments_to_plot:
                tsplot(ax=ax,
                       ci=[68, 95],
                       color=color_legend[experiment_label],
                       data=translate_episode_data(experiment_data),
                       time="Frame",
                       unit="run_id",
                       value="Average Episode Reward")
    pyplot.show()

def sample(bins, time, value):
    """
    Given value[i] was observed at time[i],
    group them into bins i.e.,
    *(bins[j], bins[j+1], ...)*

    Values for bin j are equal to the
    average of all value[k] and,
    bin[j] <= time[k] < bin[j+1].

    __Arguments__
    bins: _np.array_
        Endpoints of the bins.
        For n bins it shall be of length n + 1.
    t: _np.array_
        Times at which the values are observed.
    vt: _np.array_
        Values for those times.

    __Returns__
    x: _np.array_
        Endspoints of all the bins.
    y: _np.array_
        Average values in all bins.
    """
    bin_idx = np_digitize(time, bins) - 1
    value_sums = np_zeros(shape=len(bins) - 1, dtype=np_float32)
    value_cnts = np_zeros(shape=len(bins) - 1, dtype=np_float32)
    np_add.at(value_sums, bin_idx, value)
    np_add.at(value_cnts, bin_idx, 1)
    # ensure graph has no holes
    zeros = np_where(value_cnts == 0)
    assert value_cnts[0] > 0
    for z in zeros:
        value_sums[z] = value_sums[z - 1]
        value_cnts[z] = value_cnts[z - 1]
    return bins[1:], value_sums / value_cnts

def translate_episode_data(episode_data):
    """
    Convert episode data into data that
    can be used in a graph.

    Given data from multiple episodes make
    it such that it can be plotted by tsplot,
    i.e. the mean plus the confidence bounds.
    """
    times, units, values = [], [], []
    for index, (ep_len, ep_rew) in enumerate(episode_data):
        # Smooth out the data
        ep_rew = pd_Series(ep_rew).ewm(span=1000).mean()
        # sample for faster plotting
        x, y = sample(bins=np_linspace(0, MAX_TSTEPS, NSAMPLES + 1),
                      time=ep_len,
                      value=ep_rew)
        # Convert to tsplot format
        times.extend(x)
        values.extend(y)
        units.extend([index] * len(x))
    return pd_DataFrame({'Frame': times, 'run_id': units, 'Average Episode Reward': values})

if __name__ == "__main__":
    main()


import numpy as np
import control as co
import matplotlib.pyplot as plt
import cvxpy as cvx
import SLSsyn as Ss
import yaml
import os.path
from scipy.linalg import block_diag
import scipy.sparse as sparse

dT = 0.008
s = co.tf([1, 0], [1])

class OldControllers:
    """ Controllers that I designed sometime ago using different methods.
    """
    A1 = co.c2d(co.tf([1], [1, 6, 5]), dT)
    Alp = co.c2d(1.0 / 5 / (0.3 * s + 1) / (0.5 * s + 1)
                 * (0.032 * s + 1) * (0.0021 * s + 1), dT)
    Ainf = co.tf([0, 0.000234247581937, -
                  0.001519129809213, 0.004117723048895, -
                  0.005971926120458, 0.004887991561889, -
                  0.002140996863836, 0.000392090600785],
                 [1.0, - 7.692092610286219, 25.432665781511435, -
                  46.858394653166798, 51.963159172009036, -
                  34.686122493591625, 12.905678916635351, -
                  2.064894113111176], dT)

    Ac14 = co.tf([0, 0.000780043976221, -
                  0.001879759125377, 0.001518988906942, -
                  0.000411374804692, 0],
                 [1.0, -
                  2.915259796026691, 2.835076504158775, -
                  0.919776846642308, 0.000000000000039, 0], dT)

def plant(Larm=0.4, Hgain=20, Hdelay=0.01):
    """Nominal Model as defined in Oct02_SISO_model.m

    Return a linear model of the admittance control robot.
    The model has the following form:

    [d  ] = [P11 P12] [fH]
    [fHT]   [P21 P22] [qu]
    [mm ]   [P31 P32]

    d:   position of the end-effector
    fHT: force output, does not have physical meaning, only use to
    mm: effective torque measured,

    fH: force exerted by human,
    qu: control generated by the admittance controller,

    Consider a controller that maps from [mm] to [qu], the closed-loop
    response would be a mapping from [fH] -> [d, fHT].

    Check org_imgs/Sysdiagram0ax.pdf

    """
    s = co.tf([1, 0], [1])
    R1 = (-s + 55.56) / (s + 55.56) / (0.0437 * s + 1)
    # NOTE: the near last two terms is the first-order pade
    # approximation of the transport delay exp(-sHdelay).
    # NOTE: the last two terms: 10 / (10 + s) encodes the fact that
    # human is very bad at following anything faster than 10
    # rad/s. These terms essentially mean unit gain at low frequency
    # and quick drop afterward.
    H = Hgain * (1 - Hdelay * s) / (1 + Hdelay * s) * 10 / (10 + s)
    Se = 2 * np.pi * 73 / (s + 2 * np.pi * 73)
    R2 = 0.475 * s ** 2 / (s / 100 + 1) ** 2 * 35 / \
        (s + 35) * (-s + 66) / (s + 66)

    P = Ss.tf_blocks([[0, R1 * Larm],
                      [0, (R1 * Larm * H + R2)],
                      [Larm * Se, - (R1 * Larm * H + R2) * Se * Larm]])
    return P

def analysis(plant, controller, Mp=1.05, Tr=0.9, controller_name='noname',
             internal_data=None, m=0.5, b=10, k=80,
             freqs_bnd_yn=[1e-2, 255], mag_bnd_yn=[-10, -10],
             freqs_bnd_T=[1e-2, 357], mag_bnd_T=[6, 6]):
    """A basic analysis of a plant/controller pair.

    Simulate the system and draw several plots.

      1 |  3
    ----|----
      2 |  4

    1): input output 1
    2): input output 2
    3): frequency responses
    4): nyquist

    Args:
        plant: A (3 outputs, 2 inputs) discrete-time LTI system.
        controller: A (1 output, 1 input) discrete-time LTI system.
        internal_data: The internal responses {R, M, N, L, H} in that
                       order. Or can be None.
    """
    H = Ss.lft(plant, controller)
    w, q = np.linalg.eig(H.A)
    wmax = w[np.argmax(np.abs(w))]
    if np.abs(wmax) > 1:
        print(" -- Closed-loop system UNSTABLE. w_max={:}".format(wmax))
    else:
        print(" -- Closed-loop system STABLE. w_max={:}".format(wmax))

    # spectral analysis
    w_nyquist = np.pi / dT
    freqs = np.logspace(-2, np.log10(w_nyquist) - 1e-2, 100)
    mag, phase, omega = H.freqresp(freqs)
    # step and impulse response
    T, y_step = co.step_response(H, [0, 10])
    # NOTE1: if T = [0, 10], the algorithm would not compute the
    # impulse response, but the response to a linearly decreasing
    # input from 1 at time 0 to 0 at time 10. To address this issue,
    # input the whole time vector.

    # NOTE2: co.impulse is not identical to matlab impulse. The
    # difference is that co.impulse compute the reponse w.r.t to a
    # input of the form [1, 0, ...], while matlab returns the reponse
    # to [1 / Ts, 0, ...]. Matlab's convention would produce similar
    # impulse response for two corresponding c-time and d-time. co's
    # convention is more theoretical.

    T_step = np.arange(y_step.shape[1]) * dT  # get correct T
    dss = y_step[0, -1]
    # const-jerk input: accelerate to 5 N in 0.3 sec, then deccelerate to 1 in
    # 0.3 sec
    T_forced, F_forced = const_jerk_input(
        duration=10, accel_duration=0.6, f_max=4, f_ss=1.0, dT=dT)
    T_forced, Y_forced, _ = co.forced_response(H, T_forced, F_forced)

    # step response
    fig, axs = plt.subplots(2, 2, figsize=(10, 10))
    axs[0, 0].plot(T_step, y_step[0, :], label='Hd(t)*u(t)')
    axs[0, 0].plot(T_forced, Y_forced[0, :], label='resp to const-jerk')
    axs[0, 0].plot([0, Tr, Tr, 10], [0, 0, 0.98 *
                                     dss, 0.98 * dss], '--', c='gray')
    axs[0, 0].plot([0, 10], [Mp * dss, Mp * dss], '--',
                   c='gray', label='dss={:.5f}'.format(dss))
    axs[0, 0].legend(loc=1)  # upper right
    axs[0, 0].set_xlabel('Time(sec)')
    axs[0, 0].set_ylabel('y(m)')

    # impulse response, comparison with an ideal mass/spring/damper
    H_model = co.c2d(co.tf([1], [m, b, k]), dT)
    T_imp = np.arange(0, 10, 0.008)
    _, y_imp = co.impulse_response(H, T_imp)
    _, y_imp_model = co.impulse_response(H_model, T_imp)

    axs[1, 0].plot(T_imp, y_imp[0, :], label='H[n]')
    axs[1, 0].plot(T_imp, y_imp_model[0, :], label='ref-model')
    axs[1, 0].legend()
    axs[1, 0].text(5, 0.0003, 'model(m={:},b={:},k={:})'.format(
        m, b, k), horizontalalignment='center')

    # frequency responses
    mag_yn = 20 * np.log10(mag[0, 0])
    mag_T = 20 * np.log10(mag[1, 0])
    # bounds on H_yn and H_T
    if internal_data is not None:
        T = internal_data['internal responses'][0].shape[0]
    else:
        T = 256
    omegas = np.arange(int(T / 2)) * 2 * np.pi / T / 0.008
    omegas[0] = 1e-2
    wS_inv = np.ones(T) * 100  # infinity
    wS_inv[:int(T / 2)] = np.power(10, np.interp(np.log10(omegas),
                                                 np.log10(freqs_bnd_yn), mag_bnd_yn) / 20)
    mag_wS = 20 * np.log10(wS_inv)
    axs[0, 1].scatter(omegas[:int(T / 2)],
                      mag_wS[:int(T / 2)], label='1/wN', c='C2')
    axs[0, 1].plot(freqs, mag_yn, label='H_yn(z)', c='C0')
    axs[0, 1].plot(freqs, mag_T, label='T(z)', c='C1')
    axs[0, 1].plot([w_nyquist, w_nyquist], [
                   np.min(mag_yn), np.max(mag_yn)], '--', c='red')
    axs[0, 1].plot(freqs_bnd_yn, mag_bnd_yn, 'x--', c='C0', label='1/wN')
    axs[0, 1].plot(freqs_bnd_T, mag_bnd_T, 'x--', c='C1', label='1/wT')
    axs[0, 1].set_xscale('log')
    axs[0, 1].set_ylabel('Mag(dB)')
    axs[0, 1].set_xlabel('Freq(rad/s)')
    axs[0, 1].legend()

    # nyquist plot of H_yn (noise to output)
    H_yn = mag[0, 0] * np.exp(1j * phase[0, 0])
    axs[1, 1].plot(H_yn.real, H_yn.imag, 'o-')
    axs[1, 1].set_title("Nyquist plot of H_yn(s)")

    for i in [0, 30, 40, 50, 60, 63, 65, 69, 73, 77, 80, 99]:
        axs[1, 1].text(H_yn[i].real, H_yn[i].imag,
                       "{:.3f} rad/s".format(freqs[i]))

    fig.suptitle('Analysis plots: {:}'.format(controller_name))
    plt.show()

    if internal_data is not None:
        fig, axs = plt.subplots(2, 1)
        (Rval, Nval, Mval, Lval) = internal_data['internal responses']
        T = Rval.shape[0]
        T_Half = int(T / 2)
        Rdft = np.fft.fft(Rval[:, 0, 0], axis=0)
        axs[0].vlines(np.arange(T_Half) * 2 * np.pi /
                      T, 0, np.abs(Rdft[:T_Half]))
        axs[0].set_title('DFT{{R[0, 0]}} T={:d}'.format(T))
        axs[1].plot(internal_data['L'].flatten(), label='L[n]')
        axs[1].plot(internal_data['MB2'].flatten(), label='MB2[n]')
        axs[1].legend()
        plt.show()

def const_jerk_input(
        duration=10,
        accel_duration=0.6,
        f_max=4,
        f_ss=1.0,
        dT=dT):
    """
    """
    t_arr = np.arange(0, duration, dT)
    f_arr = []
    for t in t_arr:
        if t < accel_duration / 2:
            f_arr.append(t * f_max / (accel_duration / 2))
        elif t < accel_duration:
            f_arr.append(f_max - (t - accel_duration / 2) *
                         (f_max - f_ss) / (accel_duration / 2))
        else:
            f_arr.append(f_ss)
    return t_arr, np.array(f_arr)

def SLS_synthesis_p1(Pssd, T, regularization=-1, test_signal='step',
                     Mp=1.01, m=0.5, b=10, k=80,
                     freqs_bnd_yn=[1e-2, 255], mag_bnd_yn=[-10, -10],
                     freqs_bnd_T=[1e-2, 357], mag_bnd_T=[6, 6], T_delay=11):
    """Synthesize a controller using SLS.

    Procedure p1

        Constraints
        - 20c, 20a, 20b (achievability constraints),
        - lower bound on impulse response to prevent negative response,
        - steady-state displacement given constant acting force;
        - noise attenuation: upper bound on the mapping from noise to displacement;
        - robust stability: upper bound on the complementary sensitivity transfer function;

        Objectives
        - regularization using scaled l1 norm on the impulse responses L, MB2
        - distance to a desired mass/spring/damper model (m,b,k)
    """
    print("-- Starting SLS_synthesis_p1")
    # parameters
    nu = 1  # 1 dof controller
    ny = 1

    # form response matrices
    R, N, M, L, H, constraints = Ss.SLS.form_SLS_response_matrices(
        Pssd, nu, ny, T)

    # # constants
    nx = Pssd.states
    A, B1, B2, C1, C2, D11, D12, D21, D22 = Ss.get_partitioned_mats(
        Pssd, nu, ny)

    # select component of H that correspond to the mapping from acting
    # force (and noise) to actual robot displacement (H_yn) and the
    # mapping that corresponds to the complementary transfer function T.
    H_yn = H[0::2, :]
    H_T = H[1::2, :]

    # objective: match the impulse response of a given system
    sys_model = co.c2d(co.tf([1], [m, b, k]), dT)
    _, imp_model = co.impulse_response(sys_model, np.arange(T) * dT)

    # NOTE: have to use norm, sum_of_squares does not work. The reason
    # is the magnitude of the objective function must not be too
    # small. The optimizer seems to get confuse and simply stop
    # working.
    imp_diff = H_yn[T_delay:, 0] - imp_model[0, :T - T_delay]
    weight = np.diag(1 + 2 * (1.0 / T) * np.arange(T - T_delay))
    objective = 1e6 * cvx.norm(weight * imp_diff)

    # try some regularization
    if regularization > 0:
        reg = regularization * (cvx.norm1(H_yn))
    else:
        reg = cvx.abs(cvx.Variable())

    # constraint in frequency-domain, if specified
    W_dft = Ss.dft_matrix(T)
    Hz_yn = W_dft * H_yn
    Hz_T = W_dft * H_T
    omegas = np.arange(int(T / 2)) * 2 * np.pi / T / dT
    omegas[0] = 1e-2

    # upper bound for noise attenuation
    wN_inv = np.ones((T, 1)) * 100  # infinity
    wN_inv[:int(T / 2), 0] = np.power(10, np.interp(np.log10(omegas),
                                                    np.log10(freqs_bnd_yn), mag_bnd_yn) / 20)

    # upper bound for complementary sensitivity transfer function
    wT_inv = np.ones((T, 1)) * 100  # infinity
    wT_inv[:int(T / 2), 0] = np.power(
        10, np.interp(np.log10(omegas), np.log10(freqs_bnd_T), mag_bnd_T) / 20)

    # add both frequency-domian constraints
    constraints.append(cvx.abs(Hz_yn) <= wN_inv)
    constraints.append(cvx.abs(Hz_T) <= wT_inv)

    # optimize
    obj = cvx.Minimize(objective + reg)
    prob = cvx.Problem(obj, constraints)
    print("-- [SLS_synthesis_p1] Preparing problem with cvxpy!")
    prob.solve(verbose=True, solver=cvx.MOSEK)
    print("-- [SLS_synthesis_p1] optimization status: {:}".format(prob.status))
    print(
        "-- [SLS_synthesis_p1] obj = {:}, reg = {:}".format(objective.value, reg.value))

    if prob.status != "optimal":
        return None, None

    print("-- [SLS_synthesis_p1] Forming controllers!")
    # form controllers (Structure 1, Figure 4b, Wang 2018)
    L_value = np.array(L.value).reshape(ny, nu, -1)
    MB2_value = np.array((M * B2).value).reshape(nu, nu, -1)

    # since ny=nu=1, we have
    fir_den = [1] + [0 for n in range(T - 1)]
    MB2_tf = co.tf(MB2_value[0, 0], fir_den, dT)
    L_tf = co.tf(L_value[0, 0], fir_den, dT)
    K = co.feedback(1, MB2_tf, sign=-1) * L_tf
    K = Ss.tf2ss(K, minreal=True)

    # response mapping
    Rval = np.array(
        [R[n * nx: (n + 1) * nx, :].value for n in range(T)]).reshape(-1, nx, nx)
    Nval = np.array(
        [N[n * nx: (n + 1) * nx, :].value for n in range(T)]).reshape(-1, nx, ny)
    Mval = np.array(
        [M[n * nu: (n + 1) * nu, :].value for n in range(T)]).reshape(-1, nu, nx)
    Lval = np.array(
        [L[n * nu: (n + 1) * nu, :].value for n in range(T)]).reshape(-1, nu, ny)
    Hval_yn = np.array(H_yn.value)
    Hval_T = np.array(H_T.value)

    return K, {'internal responses': (Rval, Nval, Mval, Lval),
               'output impulse': (Hval_yn, Hval_T),
               'L': L_value, 'MB2': MB2_value}

def main():
    Ptf_design = plant(Hdelay=0.05, Hgain=50)
    Pss_design = Ss.tf2ss(Ptf_design, minreal=True)
    Pssd_design = co.c2d(Pss_design, dT)

    # synthesize controller
    freqs_bnd_T = [1e-2, 2.3, 7.3, 25, 357]
    mag_bnd_T = [-3, -3, -3, -10, -40]
    # freqs_bnd_yn = [1e-2, 3.0, 30, 80, 255]  # rad
    # mag_bnd_yn = [-10, -10, -20, -74, -100]  # db
    freqs_bnd_yn = [1e-2, 3.0, 20, 50, 255]  # rad
    mag_bnd_yn = [-20, -20, -20, -94, -130]  # db
    Asls, internal_data = SLS_synthesis_p1(Pssd_design, 256, regularization=1,
                                           freqs_bnd_T=freqs_bnd_T, mag_bnd_T=mag_bnd_T,
                                           freqs_bnd_yn=freqs_bnd_yn, mag_bnd_yn=mag_bnd_yn,
                                           m=1.5, b=24, k=60, T_delay=7)

    # # test/analysis
    Ptf_test = plant(Hgain=50, Hdelay=0.05)
    Pssd_test = co.c2d(Ss.tf2ss(Ptf_test, minreal=True), dT)
    if Asls is not None:
        analysis(Pssd_test, Asls,
                 internal_data=internal_data, Tr=1.0, controller_name='SLS',
                 freqs_bnd_T=freqs_bnd_T, mag_bnd_T=mag_bnd_T, freqs_bnd_yn=freqs_bnd_yn,
                 mag_bnd_yn=mag_bnd_yn, m=1.5, b=24, k=60)

    analysis(Pssd_test, OldControllers.A1, Tr=1.0, controller_name='admittance',
             freqs_bnd_T=freqs_bnd_T, mag_bnd_T=mag_bnd_T,
             freqs_bnd_yn=freqs_bnd_yn, mag_bnd_yn=mag_bnd_yn,
             m=1.5, b=28, k=65)
    analysis(Pssd_test, OldControllers.Ac14, Tr=1.0, controller_name='Hinf',
             freqs_bnd_T=freqs_bnd_T, mag_bnd_T=mag_bnd_T,
             freqs_bnd_yn=freqs_bnd_yn, mag_bnd_yn=mag_bnd_yn,
             m=1.5, b=28, k=65)

    # to print controller
    Ss.SLS.print_controller(internal_data['L'], internal_data['MB2'])

    import IPython
    if IPython.get_ipython() is None:
        IPython.embed()

if __name__ == '__main__':
    main()


from settings import cms_detect_api

import requests

def cms_detect(domain, port):
    if not cms_detect_api:
        print("[-]Нет ключа `cms_detect_api` (в settings.py)!")
        return
    payload = {'key': cms_detect_api, 'url': domain}
    cms_url = "https://whatcms.org/APIEndpoint/Detect"
    response = requests.get(cms_url, params=payload)
    cms_data = response.json()
    cms_info = cms_data['result']
    if cms_info['code'] == 200:
        print(f'Detected CMS     : {cms_info["name"]}')
        print(f'Detected Version : {cms_info["version"]}')
        print(f'Confidence       : {cms_info["confidence"]}')
    else:
        print(cms_info['msg'])
        print(f'Detected CMS : {cms_info["name"]}')
        print(f'Detected Version : {cms_info["version"]}')


#!/usr/bin/python3

import cgi
import subprocess
print("Content-Type: text/html\n")
form = cgi.FieldStorage(environ={'REQUEST_METHOD':'POST'})
fname = form.getvalue("fname")
lname = form.getvalue("lname")
email = form.getvalue("email")
subject = form.getvalue("subject")
message = form.getvalue("message")
mail = [ 'mail', '-s', subject, '-r', email, '--', 'joebert@kenchlightyear.com']
body = [ 'printf', 'Message from: ' + fname + ' ' + lname + '\n\n' + message ]
bodyproc = subprocess.Popen(body, stdout=subprocess.PIPE)
mailproc = subprocess.Popen(mail, stdin=bodyproc.stdout)
confirmation = "Thank you for contacting us. We have received your message. We will get back to you soon."
signature = "Regards,\nJoebert Jacaba\nCEO, Kench Lightyear\n+63 919 999 2056"
mail = [ 'mail', '-s', "Confirmation", '-r', 'joebert@kenchlightyear.com', '--', email ]
body = [ 'printf', 'Hello ' + fname + ',\n\n' + confirmation + '\n\n' + signature]
bodyproc = subprocess.Popen(body, stdout=subprocess.PIPE)
mailproc = subprocess.Popen(mail, stdin=bodyproc.stdout)
print(confirmation)
print('
Close
')