import requests
import json
import re
from xml.dom.minidom import parse
import xmltodict
from fontTools.ttLib import TTFont
from bs4 import BeautifulSoup
heard={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36',

}

def mapping(xmlFile=None):
    if xmlFile is None:
        xmlFile="auto.xml"
    xmldoc = parse(xmlFile)
    text = json.dumps(xmltodict.parse(xmldoc.toxml()), indent=4) #xml 转json
    text_json = json.loads(text)
    list = []
    list1 = []
    for k, v in text_json.get('ttFont').items():
        if k == 'cmap':
            list = v.get('cmap_format_4')
        if k == 'glyf':
            list1 = v.get('TTGlyph')
    ysbm = {}
    for i in list:
        if i['@platEncID'] == '3':
            for ii in i['map']:
                ysbm[ii['@name']] = ii['@code'][1:]

    temp1={}
    for i in list1[1:]:
        for k, v in i.items():
            ybm = ''
            data1=[]
            if k == 'contour':
                if type(v)==dict:
                    for ii in v.get('pt'):
                        ybm = ybm+json.dumps(ii)
                        data1.append(ii)
                else:
                    for ii in v:
                        for ii in ii.get('pt'):
                            ybm = ybm+json.dumps(ii)
                            data1.append(ii)
                temp1[i['@name']]=data1

    data2={}
    j = ['三', '十', '坏', '九', '六', '远', '近', '大', '右', '长', '二', '下', '小', '是', '一', '八', '了', '左', '七', '和', '上', '得', '不', '好', '少', '五', '的', '低', '更', '矮', '着', '多', '短', '地', '呢', '四', '高', '很']

    if xmlFile=="auto.xml": #已知映射关系
        numb = 0
        for k, v in ysbm.items():
            data2[j[numb]] = temp1[k]
            numb = numb + 1
    else:
        for k,v in ysbm.items():
            data2[v]=temp1[k]
    return data2

def mapRelation(s,ss):
    '''
    :param s: 目标文件映射关系
    :param ss:  已知映射关系
    :return: 新的映射关系
    '''
    data={}
    for k,v in s.items():
        aa = [x["@on"] for x in v]
        for i in v:
            for k1,v1 in ss.items():
                bb = [y["@on"] for y in v1]
                if len(aa) % 2 == 0:
                    aaS = aa[:(len(aa) // 2) - 1]
                    aaE = aa[(len(aa) // 2) + 1:]
                else:
                    aaS = aa[:len(aa) // 2]
                    aaE = aa[(len(aa) // 2) + 1:]
                if len(bb) % 2 == 0:
                    bbS = bb[:(len(bb) // 2) - 1]
                    bbE = bb[(len(bb) // 2) + 1:]
                else:
                    bbS = bb[:len(bb) // 2]
                    bbE = bb[(len(bb) // 2) + 1:]
                if aaE == bbE or aaS == bbS:
                    data[k] = k1
                    break
                for ii in v1:
                    if i==ii:
                        data[k]=k1
                        break
    return data

def getContent(url):
    html = requests.get(url,headers=heard).text
    ttf = re.search("format\('embedded-opentype'\),url\('(//k3.autoimg.cn/g1/.*?\.ttf)",html).group(1)

    ttflink = 'http:' + ttf
    r = requests.get(ttflink)
    with open('../autoHome/auto1.ttf', "wb") as f:
        f.write(r.content)
    f.close()
    font1 = TTFont('auto1.ttf')  # 读取woff文件
    font1.saveXML('auto1.xml')  # 转成xml
    data = mapRelation(mapping('auto1.xml'), mapping())
    for k, v in data.items():
        html = html.replace("&#" + k + ";", v)

    htmltxet = BeautifulSoup(html, "html.parser")
    contents=htmltxet.find_all("div",{"class":"clearfix contstxt outer-section"})
    for c in contents[1:]:
        ct=c.find("div",{"class":"x-reply font14"}).get_text().strip()
        if "本楼已被删除" not in ct:
            pubTime=c.find("span",{"xname":"date"}).get_text().strip()
            print("评论："+ct)
            print("发布时间："+pubTime)
            print("=======")

if __name__ == '__main__':
    getContent("https://club.autohome.com.cn/bbs/thread/1f05b4da4448439b/76044817-2.html")

#     dict=["的","是","上","近","小","高","不","着","八","十","右","短","三","少",
#           "二","七","九","更","呢","得","低","一","很","大","多","左","好","长",
#           "了","坏","五","地","和","远","下","四","六","矮"]
#     uniDict=["uniED79","uniECC6","uniED18","uniEC64","uniECB6","uniEDF7","uniED43","uniED95","uniECE2","uniEC2E",
#              "uniEC80","uniEDC1","uniEC1F","uniED5F","uniECAC","uniECFE","uniEC4A","uniED8B","uniEDDD","uniED29","uniED7B",
#              "uniECC8","uniEE08","uniEC66","uniEDA7","uniECF3","uniED45","uniEC92","uniECE4","uniEC30","uniED71",
#              "uniEDC3","uniED0F","uniEC5C","uniECAE","uniEDEE","uniEC4C","uniED8D"]


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

import os
import time
import logging
import numpy as np
import jieba
from gensim.models import KeyedVectors
import sys

file_root = os.path.dirname(__file__)
sys.path.append(file_root)
from get_file import get_file

pwd_path = os.path.abspath(os.path.dirname(__file__))
USER_DATA_DIR = pwd_path
os.makedirs(USER_DATA_DIR, exist_ok=True)

def load_stopwords(file_path):
    stopwords = set()
    if file_path and os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                stopwords.add(line)
    return stopwords

class Tokenizer(object):
    def __init__(self, dict_path='', custom_word_freq_dict=None):
        self.model = jieba
        self.model.default_logger.setLevel(logging.ERROR)
        # 初始化大词典
        if os.path.exists(dict_path):
            self.model.set_dictionary(dict_path)
        # 加载用户自定义词典
        if custom_word_freq_dict:
            for w, f in custom_word_freq_dict.items():
                self.model.add_word(w, freq=f)

    def tokenize(self, sentence, cut_all=False, HMM=True):
        """
        切词并返回切词位置
        :param sentence: 句子
        :param cut_all: 全模式，默认关闭
        :param HMM: 是否打开NER识别，默认打开
        :return:  A list of strings.
        """
        return self.model.lcut(sentence, cut_all=cut_all, HMM=HMM)

class Word2Vec(object):
    """Pre-trained word2vec embedding"""
    model_key_map = {
        # 腾讯词向量, 6.78G
        'w2v-tencent-chinese': {
            'tar_filename': 'Tencent_AILab_ChineseEmbedding.tar.gz',
            'url': 'https://ai.tencent.com/ailab/nlp/data/Tencent_AILab_ChineseEmbedding.tar.gz',
            'binary': False,
            'untar_filename': 'Tencent_AILab_ChineseEmbedding.txt'},
        # 轻量版腾讯词向量，二进制，111MB
        'w2v-light-tencent-chinese': {
            'tar_filename': 'light_Tencent_AILab_ChineseEmbedding.bin',
            'url': 'http://42.193.145.218/light_Tencent_AILab_ChineseEmbedding.bin',
            'binary': True,
            'untar_filename': 'light_Tencent_AILab_ChineseEmbedding.bin'},
    }

    def __init__(self, model_name_or_path='w2v-light-tencent-chinese',
                 w2v_kwargs={},
                 stopwords_file=os.path.join(pwd_path, 'data/stopwords.txt'),
                 cache_folder=USER_DATA_DIR):
        """
        Init word2vec model

        Args:
            model_name_or_path: word2vec file path
            w2v_kwargs: params pass to the ``load_word2vec_format()`` function of ``gensim.models.KeyedVectors`` -
                https://radimrehurek.com/gensim/models/keyedvectors.html#module-gensim.models.keyedvectors
            stopwords_file: str, stopwords
            cache_folder: str, save model
        """
        self.w2v_kwargs = w2v_kwargs
        if model_name_or_path and os.path.exists(model_name_or_path):
            model_path = model_name_or_path
        else:
            model_dict = self.model_key_map.get(model_name_or_path, self.model_key_map['w2v-light-tencent-chinese'])
            tar_filename = model_dict.get('tar_filename')
            self.w2v_kwargs.update({'binary': model_dict.get('binary')})
            url = model_dict.get('url')
            untar_filename = model_dict.get('untar_filename')
            model_path = os.path.join(cache_folder, untar_filename)
            if not os.path.exists(model_path):
                get_file(tar_filename, url, extract=True,
                         cache_dir=USER_DATA_DIR,
                         cache_subdir=USER_DATA_DIR,
                         verbose=1)
        t0 = time.time()
        w2v = KeyedVectors.load_word2vec_format(model_path, **self.w2v_kwargs)
        # w2v.init_sims(replace=True)
        logging.debug('Load w2v from {}, spend {:.2f} sec'.format(model_name_or_path, time.time() - t0))
        self.stopwords = load_stopwords(stopwords_file)
        self.w2v = w2v
        self.tokenizer = Tokenizer()
        logging.debug('Word count: {}, emb size: {}'.format(len(w2v.index2word), w2v.vector_size))
        logging.debug('Set stopwords: {}, count: {}'.format(sorted(list(self.stopwords))[:10], len(self.stopwords)))

    def encode(self, sentences, dims=200):
        """
        Encode embed sentences

        Args:
            sentences: Sentence list to embed
        Returns:
            vectorized sentence list
        """
        if self.w2v is None:
            raise ValueError('need to build model for embed sentence')

        input_is_string = False
        if isinstance(sentences, str) or not hasattr(sentences, '__len__'):
            sentences = [sentences]
            input_is_string = True

        all_embeddings = []
        for sentence in sentences:
            emb = []
            count = 0
            for word in sentence:
                # 过滤停用词
                if word in self.stopwords:
                    continue
                # 调用词向量
                if word in self.w2v.index2word:
                    emb.append(self.w2v.get_vector(word))
                    count += 1
                else:
                    if len(word) == 1:
                        continue
                    # 再切分，eg 特价机票
                    ws = self.tokenizer.tokenize(word, cut_all=True)
                    for w in ws:
                        if w in self.w2v.index2word:
                            emb.append(self.w2v.get_vector(w))
                            count += 1
            tensor_x = np.array(emb).sum(axis=0)  # 纵轴相加
            if count > 0:
                avg_tensor_x = np.divide(tensor_x, count)
            else:
                avg_tensor_x = np.zeros(dims, dtype=np.float32)
            all_embeddings.append(avg_tensor_x)
        all_embeddings = np.array(all_embeddings)
        if input_is_string:
            all_embeddings = all_embeddings[0]

        return all_embeddings

if __name__ == '__main__':
    w2v = Word2Vec(model_name_or_path=os.path.join(file_root, '../../transformers/word2vec/light_Tencent_AILab_ChineseEmbedding.bin'),
                   w2v_kwargs={"binary":True})


#!/usr/bin/env python

# importing the required library
from confluent_kafka import Producer
from confluent_kafka.serialization import StringSerializer

import confluent_kafka
import requests
import os, sys, time
import argparse
import json
import socket
import datetime
import random

def gen_custom_data(namespace, userId, region, meter):
    now = int(time.time())
    time_stamp = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(now))
    flag = str(1)
    flag_node = str(random.randint(0, 2))
    data = []
    for i in range(random.randint(10, 20)):
        item = [{
            "namespace": namespace,
            "region": region,
            "source": u"AIP",
            "group_id": "group-test",
            "resource_id": "i-instance-" + flag,
            "resource_name": "name" + flag,
            "resource_type": "test-kafka",
            "meter": meter,
            "value": random.randint(0, 98),
            "value_type": "raw",
            "time_stamp": time_stamp,
            "user_id": userId,
            "tags": "name=node" + flag_node + ",id=id" + flag_node,
            "root_user_id": userId,
        }]
        data.append(item)

    return item

def delivery_report(err, msg):
    if err is not None:
        print("Key Type                     : ", type(key))
        print('Message delivery failed      : {}'.format(err))
    else:
        print('Message delivered to         : {} [{}]'.format(msg.topic(), msg.partition()))

def write_to_kafka(bootstrap_servers, topic_name, data):
    print("Kafka Version                : ", confluent_kafka.version(), confluent_kafka.libversion())

    conf = {'bootstrap.servers': bootstrap_servers,
            'client.id': socket.gethostname(),
            'on_delivery': delivery_report
            }

    producer = Producer(conf)

    key = datetime.date.today().strftime("%Y-%m-%d-%H")
    message = json.dumps(data)

    print("Key Type                     : ", type(key))
    print("Value Data                   : ", message)

    producer.produce(topic=topic_name, key=key, value=message)
    producer.flush()

if __name__ == "__main__":

    bootstrap_servers = "10.12.10.20:19092,10.12.10.20:19093,10.12.10.20:19094 "

    topic_name = "custom_meter_data"

    # api-endpoint
    namespace = "test-kafka"
    userId = "test-kafka"
    region = "staging"
    meter = "cpu_use"

    # generate monitor data
    data = gen_custom_data(namespace, userId, region, meter)

    # write data to kafka
    if data is not None:
        write_to_kafka(bootstrap_servers, topic_name, data)

    while True:
        # generate monitor data
        data = gen_custom_data(namespace, userId, region, meter)

        # write data to kafka
        if data is not None:
            write_to_kafka(bootstrap_servers, topic_name, data)

        time.sleep(1)

    sys.exit()


# Write a Python program to count the number of characters (character frequency) in a string.
from collections import Counter
m = 'google.com'
count = Counter(m)
print(count)

#Prgram to reverse words the string
def reverse_string_words(text):
    for line in text.split('\n'):
        return(' '.join(line.split()[::-1]))
print(reverse_string_words("The quick brown fox jumps over the lazy dog."))
print(reverse_string_words("Python Exercises."))


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

"""The setup script."""

from setuptools import setup, find_packages
import os

import versioneer

HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.md"), "r", encoding="utf8") as fh:
    README = fh.read()
with open(os.path.join(HERE, "requirements.txt"), "r") as fh:
    REQUIRES = [line.strip() for line in fh]

setup(
    version=versioneer.get_version(),
    cmdclass=versioneer.get_cmdclass(),
    author="Jacob Tomlinson",
    author_email="jacob@tomlinson.email",
    classifiers=[
        "Development Status :: 2 - Pre-Alpha",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Natural Language :: English",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
    ],
    description="Home Assistant support for opsdroid",
    install_requires=REQUIRES,
    license="Apache Software License 2.0",
    long_description=README,
    long_description_content_type="text/markdown",
    include_package_data=True,
    keywords="Opsdroid Home Assistant",
    name="opsdroid-homeassistant",
    packages=["opsdroid_homeassistant"],
    entry_points={
        "opsdroid_connectors": ["homeassistant = opsdroid_homeassistant.connector"]
    },
    url="https://github.com/opsdroid/opsdroid-homeassistant",
    zip_safe=False,
)


#library imports
import re
import json

#my script imports
import website_parser

import textual_feature_extracter
import information_retrieval_feature_extractor

import textual_feature_transformer
import link_feature_transformer

def main(url):
    #Check if the inputted Url is valid using Regex
    if url_validation_tool(url):

        #Create Parser Object
        my_parser = website_parser.WebsiteParser(url)

        # Parses the website are returns a json object with:
        # a sentence map key being paragraph_index.sentence_in_paragraph_index
        # a list of all the outlinks from the webpage
        # a list of all the links to social media sites from the webpage
        # all the text in a 'bag of words' format for tfidf
        # The url slug - as this usually contains the article title / Seo Keywords
        # If the links is broken will return an error
        json_payload = json.loads(my_parser.get_payload())

        if "error" in json_payload.keys():
            #Handle Error
            pass

        else:
            # Proceed with the pipeline

            # Feature Extraction
            my_textual_feature_extractor = textual_feature_extracter.TextualFeatureExtractor(json_payload)
            my_information_retrieval_extractor = information_retrieval_feature_extractor.InformationRetrievalFeatureExtractor()

            textual_feature_map = my_textual_feature_extractor.process_sentence_map()

            # Feature Transformation

            my_textual_feature_transformer = textual_feature_transformer.TextualFeatureTransformer()
            my_link_feature_transformer = link_feature_transformer.LinkFeatureTransformer()

            # Classification

    else:
        print("The inputted URL invalid")

def url_validation_tool(url):
    regex = re.compile(r"[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)")
    match = regex.fullmatch(url)
    return bool(match)

if __name__ == '__main__':
    main()


import numpy as np

def hyperbolic_departure(mu_sun, mu, R1, R2, rp):

    term1 = np.sqrt(mu_sun/R1)
    term2 = np.sqrt(2*R2/(R1+R2))-1
    v_infinity = term1 * term2
    eh = 1+rp*v_infinity**2/mu
    h = rp*np.sqrt(v_infinity**2+2*mu/rp)
    v1 = np.sqrt(mu/rp)
    v2 = h/rp
    delta_v = v2-v1
    beta = np.arccos(1/eh)
    return delta_v, beta

M_mars = 0.642*1e24
M_earth = 5.97*1e24
M_sun = 1.89*1e30
G = 6.67*1e-11
R1 = 228*1e9
R2 = 149.6*1e9

mars_tilt = 25.19

radius_of_mars = 3389.5*1e3

mu_sun = G*M_sun
mu_earth = G*M_earth
mu_mars = G*M_mars

rp = radius_of_mars+400e3

delta_v, beta = hyperbolic_departure(mu_sun, mu_mars, R1, R2, rp)

print(delta_v, beta*180/np.pi)

#https://www.physicsforums.com/threads/solving-for-time-in-a-hyperbolic-trajectory.1020874/

#velocity value for gmat


import requests
import bs4 as bs
import pandas as pd
import pickle
import sys
from datetime import datetime
import math

# # Puxa o nome dos 1965 ativos que vieram do site da uol e estao no arquivo chamado ativos
# with open('ativos', 'rb') as f:
#     ativos = pickle.load(f)
# ########

# Lista de acoes que o programa vai puxar
acoes = ['PETR4.SA', 'ABEV3.SA', 'B3SA3.SA', 'BBAS3.SA', 'BBDC3.SA', 'BBSE3.SA', 'VALE3.SA',
         'WEGE3.SA', 'USIM5.SA', 'TAEE11.SA', 'ITUB4.SA', 'MGLU3.SA', 'KROT3.SA', 'FLRY3.SA',
         'EGIE3.SA', 'CVCB3.SA', 'CIEL3.SA', 'BRFS3.SA', 'ITSA4.SA', 'LAME4.SA']
#########

# Nome base das colunas, na hora o codigo ja adiciona o ticker da acao no final
columns = ['data', 'cotacao', 'min', 'max', 'variacao', 'variacao_percent', 'volume']
#########

diainicial = input('Digite o dia de ínicio de sua série: ')
mesinicial = input('Digite o mês de ínicio de sua série: ')
anoinicial = input('Digite o ano de ínicio de sua série: ')
diafinal = input('Digite o dia do fim de sua série: ')
mesfinal= input('Digite o mês do fim de sua série: ')
anofinal = input('Digite o ano do fim de sua série: ')

# URL que vai puxar o payload base. Se for mudar as datas tem que mudar aqui
url = 'http://cotacoes.economia.uol.com.br/acao/cotacoes-historicas.html'
base_payload = {'codigo': '', 'beginDay': diainicial,
           'beginMonth': mesinicial, 'beginYear': anoinicial,
           'endDay': diafinal, 'endMonth': mesfinal,
           'endYear': anofinal, 'page': 1, 'size': 200}
#########

# Funcao que recebe um payload e retorna um dataframe com os
# dados da acao passado no codigo do payload
def get_data(payload):
    global url
    global columns
    stock_columns = [x + '_' + payload['codigo'][:-3] for x in columns]
    df = pd.DataFrame(columns=stock_columns)
    print('Pegando dados da acao ' + payload['codigo'] + ' (', end='', flush=True)
    while True:
        html = requests.get(url, params=payload)
        soup = bs.BeautifulSoup(html.text, 'html5lib')
        tables = soup.findAll('table', {'id': 'tblInterday', 'class': 'tblCotacoes'})

        if len(tables) == 0:
            if payload['page'] == 1:
                print('Acao nao encontrada')
            break

        for table in tables:
            table_values = table.findChildren('tbody')
            trs = table_values[0].findAll('tr')
            for tr in trs:
                values = [td.text for td in tr.findAll('td')]
                df.loc[len(df)] = values
        print('.', end='', flush=True)
        payload['page'] += 1
    print(') DONE')
    return df

# Rodando a funcao para todas as acoes da lista acoes e guarndando os resultados em dfs
dfs = []
for i in acoes:
    base_payload['codigo'] = i
    base_payload['page'] = 1
    a = get_data(base_payload)
    dfs.append(a)

# concatenando todos os dataframes em dfs e alvando em um arquivo chamado dataframe_acoes
result = pd.concat(dfs, axis=1)
print(result.head())
result.to_pickle('dataframe_acoes')

# O arquivo foi salvo no formato pickle pois nesse formato a leitura e escrita eh mais rapida
# se achar melhor pode salvar um csv tambem

# Pra ler do arquivo pickle basta usar
df = pd.read_pickle('dataframe_acoes')

# print(df)

#Ajeitar a base de dados já importadada
#Tirar as pontos dos milhares e colocamos os pontos nas casas decimais
for column in df:
    df[column] = df[column].str.replace(".","")

for column in df:
    df[column] = df[column].str.replace(",",".")
# print(df.head())

#Colocando a data como index
lista = list(df.ix[:,0])
lista = lista[0:-1]
lista1 = []
for i in range(0,len(lista)):
    lista1.append(datetime.strptime(lista[i], '%d/%m/%Y'))

#Aqui nós tiramos o último valor, pois dia 01/01/2017 é feriado e não tinham valores
df = df[:-1]

df['index']=lista1
df=df.set_index('index')                                      #colocando a data ajustada como index
df.sort_values(by=['index'], inplace=True, ascending=True)     #ordenando do menor para o maior
print(df.head())

#Transformando em números
df = df.apply(pd.to_numeric,errors='coerce')

#Retirando as demais colunas de datas
for column in df:
    if column.startswith('data'):
        df.drop([column],axis=1,inplace=True)
print(df)

#Transformar o tempo em contínuo
datainicial_aux= diainicial+'/'+mesinicial+'/'+anoinicial
datainicial = datetime.strptime(datainicial_aux, '%d/%m/%Y')

datafinal_aux=diafinal+'/'+mesfinal+'/'+anofinal
datafinal = datetime.strptime(datafinal_aux, '%d/%m/%Y')
delta =  (datafinal - datainicial).days

df1 = pd.DataFrame(index=pd.date_range(datainicial, periods=delta),columns=[c for c in df])
print(df1.head(20))

#Funcão para transformar a nova matriz para a data contínua
def dfajust(df_old, df_new):
    for i in range(len(df_old)):
        for j in range(len(df_new)):
            if (df_new.index[j]==df_old.index[i]):
                df_new.iloc[j]=df_old.iloc[i]

    for j in range (len(df_new)):
        if math.isnan(df_new.iloc[j][0]):
            df_new.iloc[j]=df_new.iloc[j-1]
    return df_new

df1 = dfajust(df,df1)
print(df1.head(15))


import sys

si = sys.stdin.readline
n, m, k = map(int, si().split())
diag = [[False for i in range(m+1)] for _ in range(n+1)]
MOD = 1000000007
for _ in range(k):
    r, c = map(int, si().split())
    diag[r-1][c-1] = True

dy = [[0 for _ in range(m+1)] for _ in range(n+1)] # dy[r][c] := r행 c열인 직사각형을 최단거리로 이동하는 경우의 수
dy[n][0] = 1

# 각 대각선을 사용하지 않는 경우
for r in range(n, -1, -1):
    for c in range(0, m+1):
        print(r, c)
        if r == n and c == 0:
            continue

        if c == 0 or r == n:
            dy[r][c] = 1

        else:
            dy[r][c] = (dy[r + 1][c] + dy[r][c-1]) % MOD

print(dy)
ans = 0
for r in range(n):
    for c in range(m):
        if not diag[r][c]:
            break

        # 대각선을 찾으면
        # 내가 최단거리로 이동하는 경우의 수를 누적해줌

        # 대각선을 오른쪽 아래로 이동하는 경우
        ans += (dy[n-r-1][c] * dy[r+1][m-c-1]) % MOD

        # 대각선을 왼쪽 위로 이동하는 경우
        ans += (dy[n-r-1][c+1] * dy[r][m-c]) % MOD

print(ans)

'''
2 2 2
1 2
2 1
=> 12가 나와야하는데 6이 나온다 ㅠ
'''


#!/usr/bin/python3
import json
import os

class FileStorage:
    __file_path = '../../file.json'
    __objects = {}

    def all(self):
        return FileStorage.__objects

    def new(self, obj):
        key = "{}.{}".format(type(obj).__name__, obj.id)

        FileStorage.__objects[key] = obj

        '''
    def save(self):
        serialized = {}

        with open(self.__file_path, 'w') as content:
            data = {key:obj.to_dict() for (key, obj) in self.__objects.items()}
            json.dump(data, content)
        for key, obj in FileStorage.__objects.items():
            serialized[key] = obj.to_dict()

        with open(self.__file_path, "a") as f:
            json.dump(serialized, f, indent=4)
        '''
    def save(self):
        obj_dict = {}
        for key, obj in self.__objects.items():
            obj_dict[key] = obj.to_dict()
        existing_data = {}
        if os.path.exists(self.__file_path):
            with open(self.__file_path, "r", encoding="utf-8") as f:
                existing_data = json.load(f)

        existing_data.update(obj_dict)

        with open(self.__file_path, "w", encoding="utf-8") as f:
            json.dump(existing_data, f, indent=4)

    def reload(self):
        if os.path.exists(FileStorage.__file_path):
            with open(FileStorage.__file_path, 'r', encoding='utf-8') as content:
                file = json.load(content)

                for key, value in file.items():
                    class_, obj_id = key.split(".")
                    cls = globals().get(class_)
                    if cls:
                        obj = cls(**value)
                        FileStorage.new(obj)
                FileStorage.__objects = file


import numpy as np

import matplotlib.pyplot as plt
import matplotlib.patches as patches

def plot_tree(tree):
    ax = plt.gca()
    ax.set_axis_off()

    build_tree(tree, 0.25, 0.25)

    ax.set_xlim(-1, 2)
    ax.set_ylim(-2, 1)

    plt.show()

def build_tree(tree, left, bottom, depth=0, ax=plt.gca()):
    height = width = 0.5
    right = left + width
    top = bottom + height

    p = patches.Rectangle((left, bottom), width, height, fill=False)
    ax.add_artist(p)

    if isinstance(tree, dict):
        ax.text(
            0.5*(left+right),
            0.5*(bottom+top+0.1),
            'X[{0}] < {1}'.format(tree["feature"], tree["value"]),
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=8
        )

        ax.text(
            0.5*(left+right),
            0.5*(bottom+top-0.1),
            '{0}'.format(tree["sample"]),
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=8
        )

        xy1 = (0.5*(left+right), bottom)

        ha = 0.2
        y2 = bottom-ha

        ax.annotate("", xy=xy1, xytext=(left, y2), arrowprops=dict(arrowstyle="<-"))
        ax.annotate("", xy=xy1, xytext=(right, y2), arrowprops=dict(arrowstyle="<-"))

        bottom = bottom - height - ha
        build_tree(tree["left"], left - 0.6*width, bottom)
        build_tree(tree["right"], right - 0.4*width, bottom)
    else:
        ax.text(
            0.5*(left+right),
            0.5*(bottom+top),
            '{0}'.format(tree),
            horizontalalignment='center',
            verticalalignment='center',
            fontsize=8
        )

def plot_learning_curve(data, clf, start_size=1, end_size=None, num_sample=20):
    _data = np.concatenate((
                np.copy(data[0].astype(np.float64)),
                np.copy(data[1])[np.newaxis, :].T
                ), axis=1
            )

    accuracies = list()

    if not end_size:
        end_size = len(_data)-1

    for size in range(start_size, end_size):
        mean = 0
        for i in range(num_sample):
            np.random.shuffle(_data)
            train, train_labels = np.copy(_data[:size+1, :-1]), np.copy(_data[:size+1, -1])
            test, test_labels = np.copy(_data[size+1:, :-1]), np.copy(_data[size+1:, -1])

            clf.train(train, train_labels)

            count = 0
            for index in range(len(test_labels)):
                if clf.predict(test[index]) == test_labels[index]:
                    count += 1

            mean += count / len(test_labels)
        mean /= num_sample
        accuracies.append(mean)

    plt.plot(range(start_size, end_size), accuracies)

    plt.xlabel("Training set size")
    plt.ylabel("Proportion correct on test set")

    plt.show()

def courbeApprentissageNN(dataset, sizes_dataset, init_weights, learning_rate, nb_iter, step):
    import NeuralNet

    data_ = np.concatenate((np.copy(dataset[0].astype(np.float64)), np.copy(dataset[1])[np.newaxis, :].T), axis=1)

    accuracies = list()
    for size in range(1, len(data_)-1, step):
        print(size)
        mean = 0
        for i in range(20):
            np.random.shuffle(data_)
            train, train_labels = np.copy(data_[:size+1, :-1]), np.copy(data_[:size+1, -1])
            test, test_labels = np.copy(data_[size+1:, :-1]), np.copy(data_[size+1:, -1])

            # print(train_labels)

            NNet = NeuralNet.NeuralNet(sizes_dataset,init_weights)
            NNet.train(train, train_labels, learning_rate, nb_iter)
            # print(dT.tree)

            count = 0
            for index in range(len(test_labels)):
                if NNet.predict(test[index]) == test_labels[index]:
                    count += 1

            mean += count / len(test_labels)
        mean /= 20
        accuracies.append(mean)

    plt.plot(range(1, len(data_)-1, step), accuracies)
    plt.xlabel('Training set size')
    plt.ylabel('Proportion correct on test set')
    plt.show()


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

# %%

import os
import pickle
import sys
import pandas as pd

from RASLPhysio import Features
from datetime import datetime, timedelta, date

# %%

# %%

def nearest(items, pivot):
    return min(items, key=lambda x: abs(x - pivot))

# %%

subjects = [ "S" + str(i) for i in range(2, 18) if i != 12]
subject =  sys.argv[1]

window_size = int(sys.argv[2])
window_size_features = int(sys.argv[3])

# %%

path = 'Data/WESAD/GeneratedData/{0}_Seconds_{1}.pkl'.format(subject, window_size)
with open(path, 'rb') as file:
    data = pickle.load(file, encoding='latin1')

# %%

params = Features.Features_Params()
params['rfft'] = False

# %%

all_features = {}
date = data.index[0]
while date + timedelta(seconds=window_size_features) <= data.index[-1]:
    end = nearest(data.index, date + timedelta(seconds=window_size_features))
    if date == end:
        ind = data.index.tolist().index(date) + 1
        date = data.index[ind]
        end = nearest(data.index, date + timedelta(seconds=window_size_features))
    window = data.loc[date:end,:]
    label = window['Label'][-1]
    features = {}
    for key in window.keys():
        if key == 'Label' or key == 'EDA': continue
        feats = Features.Extract_Features(window[key].values, params)
        for key_specific in feats.keys():
            features[ "{0}_{1}".format(key, key_specific)] = feats[key_specific]
    features['Label'] = label
    all_features[date] = features
    date = end
    print(date)

# features_to_keep = [
#     "SCL_mean",
#     "SCR_mean",
#     "SCL_std",
#     "SCR_std",
#     "BVP_std",
#     "ACC_X_mean",
#     "ACC_Y_mean",
#     "ACC_Z_mean",
# ]

Features_df = pd.DataFrame(all_features).T
# Features_df = Features_df[Features_df.columns.intersection(features_to_keep)]

pickle.dump( all_features, open( "Data/WESAD/GeneratedData/features_wesad_{0}_{1}.p".format(subject, window_size_features), "wb" ) )

# %%

# %%


import time
from urlparse import urlparse

import boto
from scrapy.exceptions import NotConfigured
from twisted.internet.threads import deferToThread

class S3Pipeline(object):

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.settings)

    def __init__(self, settings):
        self.time_str = time.strftime('%Y%m%d%H%M%S')
        self.root, self.bucket = self.get_root_and_bucket(self.uri, settings)

    def store(self, keyname, data):
        return deferToThread(self._store, keyname, data)

    def _store(self, keyname, data):
        key = self.bucket.new_key(keyname)
        key.set_contents_from_string(data)
        key.set_acl('public-read')
        key.close()
        url = key.generate_url(expires_in=0, query_auth=False)
        return url

    def get_root_and_bucket(self, uri, settings):
        u = urlparse(self.uri)
        bucketname = u.hostname
        access_key = u.username or settings['AWS_ACCESS_KEY_ID']
        secret_key = u.password or settings['AWS_SECRET_ACCESS_KEY']
        if not access_key or not secret_key:
            raise NotConfigured('No AWS_ACCESS_KEY_ID or '
                                'AWS_SECRET_ACCESS_KEY set in settings.py')
        conn = boto.connect_s3(access_key, secret_key)
        return u.path, conn.get_bucket(bucketname, validate=False)


from django.db.models import Sum
import math

from rest_framework import serializers
from rest_framework.reverse import reverse as api_reverse

from tickets.models import Ticket, Visit
from customerorders.api.serializers import CustomerOrderSerializer
from customerprojects.api.serializers import CustomerProjectSerializer
from assignProject.api.serializers import SalesManagerSerializer, EngineerSerializer

class TicketSerializer(serializers.ModelSerializer):

    class Meta:
        model = Ticket
        fields=[
            'id',
            'project',
            'order',
            'ticket_id',
            'request_type',
            'source',
            'sales_manager',
            'engineer',
            'comments',
            'status',
            'scheduled_date',
            'start_date',
            'stop_date',
            'updated',
            'timestamp',
        ]

class TicketReadSerializer(serializers.ModelSerializer):

    project           = CustomerProjectSerializer(read_only=True)
    order             = CustomerOrderSerializer(read_only=True)
    sales_manager     = SalesManagerSerializer(read_only=True)
    engineer          = EngineerSerializer(read_only=True)
    t_expense         = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Ticket
        fields=[
            'id',
            'project',
            'order',
            'ticket_id',
            'request_type',
            'source',
            'sales_manager',
            'engineer',
            'comments',
            'status',
            't_expense',
            'scheduled_date',
            'start_date',
            'stop_date',
            'updated',
            'timestamp',
        ]
        read_only_fields = ['project', 'order']

    def get_t_expense(self, obj):
        ticket  = obj.id
        total = 0

        if ticket is None:
            return total
        try:
            visits = Visit.objects.filter(ticket=ticket)
            print(visits)
            for vit in visits:
                total += vit.expense
            formatted_total  = format(total, '.2f')
            return formatted_total
        except Exception:
            return ticket

class VisitSerializer(serializers.ModelSerializer):

    class Meta:
        model = Visit
        fields=[
            'id',
            'ticket',
            'comments',
            'expense',
            'updated',
            'timestamp',
        ]


import rclpy
import rclpy.node
import rclpy.qos
from geometry_msgs.msg import Point

class ROS2Sub(rclpy.node.Node):
    def __init__(self, *args):
        super(ROS2Sub, self).__init__("ROS2Sub")
        self.create_subscription(
            Point, "points", self.points_callback, rclpy.qos.qos_profile_sensor_data)

    def points_callback(self, msg):
        self.get_logger().info("Recieved a point with x of %s" % msg.x)

def main():
    rclpy.init()
    node = ROS2Sub()
    rclpy.spin(node)
    rclpy.shutdown()

if __name__ == '__main__':
    main()


#!/home/knielbo/virtenvs/ndhl/bin/python
"""
Build signal(s) from information dynamics in model

@author: kln@cas.au.dk
"""
import os
import numpy as np
from numpy.matlib import repmat
import scipy as sp
from util import load_pcl

# vis and test
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams.update({"text.usetex": False,
                    "font.family": "Times New Roman",
                    "font.serif": "cmr10",
                    "mathtext.fontset": "cm",
                    "axes.unicode_minus": False
                    })

def kld(p, q):
    """ KL-divergence for two probability distributions
    """
    p = np.asarray(p, dtype=np.float)
    q = np.asarray(q, dtype=np.float)

    return np.sum(np.where(p != 0, (p-q) * np.log10(p / q), 0))

def jsd(p, q, base=np.e):
    '''Pairwise Jensen-Shannon Divergence for two probability distributions
        - use to avoid division by zero when q = 0
    '''
    ## convert to np.array
    p, q = np.asarray(p), np.asarray(q)
    ## normalize p, q to probabilities
    p, q = p/p.sum(), q/q.sum()
    m = 1./2*(p + q)
    return sp.stats.entropy(p,m, base=base)/2. +  sp.stats.entropy(q, m, base=base)/2.

def normalize(x, lower=-1, upper=1):
    """ transform x to x_ab in range [a, b]
    """
    x_norm = (upper - lower)*((x - np.min(x)) / (np.max(x) - np.min(x))) + lower
    return x_norm
"""
def build_signals(X, w=3):

    m = len(X)
    # Novelty
    N_hat = np.zeros(m)
    N_sd = np.zeros(m)
    for i, x in enumerate(X):
        submat = X[(i-w):i, ]
        tmp = np.zeros(submat.shape)
        for ii, xx in enumerate(submat):
            tmp[ii] = kld(xx, x)
        N_hat[i] = np.mean(tmp)
        N_sd[i] = np.std(tmp)
    # Transience
    T_hat = np.zeros(m)
    T_sd = np.zeros(m)
    for i, x in enumerate(X):
        submat = X[i:(i+w), ]
        tmp = np.zeros(submat.shape)
        for ii, xx in enumerate(submat):
            tmp[ii] = kld(xx, x)
        T_hat[i] = np.mean(tmp)
        T_sd[i] = np.std(tmp)
    # Resonance
    R = N_hat - T_hat
    R_sd = (N_sd + T_sd)/2

    return [N_hat, N_sd], [T_hat, T_sd], [R, R_sd]
"""

def main():
    bow_mdl = load_pcl(os.path.join("..","mdl","bow_lda.pcl"))
    X = bow_mdl["theta"]
    #fname = os.path.join("..", "dat", "target.pcl")
    #db = load_pcl(fname)
    #content = db["content"]N_hat[i] = np.mean(tmp)
    #metadata = db["metadata"]
    #print(metadata.head(25))

    # ASSERT: X is matrix

    # parameters P of function
    window = 25# abstract time window because the data are not sampled on regular intervals (in sample)
    m = X.shape[0]
    weight = 0.0# parameter to set initial window for novelty and final window for transience
    impute = True
    rescale = True#-1:1 scaling

    # ASSERT: win < m

    # novelty
    N_hat = np.zeros(m)
    N_sd = np.zeros(m)

    for i, x in enumerate(X):#TODO: remove w+1 limit
        submat = X[(i-window):i,]
        tmp = np.zeros(submat.shape[0])
        if submat.any():
            for ii, xx in enumerate(submat):
                tmp[ii] = jsd(x, xx)
        else:
            tmp = np.zeros([window]) + weight# Comment: set initial windows to 0.0

        N_hat[i] = np.mean(tmp)
        N_sd[i] = np.std(tmp)
    #print(N_hat)

    # Transience
    T_hat = np.zeros(m)
    T_sd = np.zeros(m)

    for i, x in enumerate(X):#TODO: remove w+1 limit
        submat = X[i+1:(i+window+1),]
        tmp = np.zeros(submat.shape[0])
        #print(i, x)
        if submat.any():

            for ii, xx in enumerate(submat):
                #print(ii, xx)
                #print(ii, kld(xx,x))
                tmp[ii] = jsd(x, xx)
                #print(tmp)
            #print("*"*10)
        else:
            tmp = np.zeros([window])
            #print(tmp)

        T_hat[i] = np.mean(tmp)
        T_sd[i] = np.std(tmp)

    #print(T_hat)
    #T_hat[i] = np.mean(tmp)
    #T_sd[i] = np.std(tmp)
    #print(T_hat)
    #novelty, transience, resonance = build_signals(X, w=w)
    # Resonance
    R = N_hat - T_hat
    R_sd = (N_sd + T_sd)/2
    #print(novelty)

    T_hat[-window:] = np.zeros([window]) + weight
    R[:window] = np.zeros([window]) + weight
    R[-window:] = np.zeros([window]) + weight

    if rescale:
        print("rescaling")
        R = normalize(R)
        N_hat = normalize(N_hat, lower=0)
        T_hat = normalize(T_hat, lower=0)

    N_hat[:window] = np.zeros([window]) + np.mean(N_hat[window:])
    #T_hat[-window:] = np.zeros([window]) + weight
    T_hat[-window:] = np.zeros([window]) + np.mean(T_hat[:-window])
    #R[:window] = np.zeros([window]) + weight
    #R[-window:] = np.zeros([window]) + weight
    R[:window] = np.zeros([window]) + np.mean(R[window:-window])
    R[-window:] = np.zeros([window]) + np.mean(R[window:-window])

    if impute:
        print("imputation initiated")

    fig, ax = plt.subplots(1,3,figsize=(14,3))
    ax[0].plot(N_hat,c="k")
    ax[0].axhline(np.mean(N_hat[window:]),c="r",linestyle=":")
    ax[1].plot(T_hat,c="k")
    ax[1].axhline(np.mean(T_hat[:-window]),c="r",linestyle=":")
    ax[2].plot(R,c="k")
    ax[2].axhline(np.mean(R[window:-window]),c="r",linestyle=":")
    #ax[2].axhline(0.,c="g",linestyle=":")
    plt.tight_layout()
    plt.savefig("../fig/signal.png")
    plt.close()
if __name__ == "__main__":
    main()


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

from math import pi
from math import sqrt
from math import radians
from math import cos

from weblib.pubsub import Publisher

class ACSSessionCreator(Publisher):
    def perform(self, push_adapter):
        """Log into the Appcelerator Cloud services and return the created
        session.

        On success, an 'acs_session_created' message will be published,
        together with the session ID;  on failure, an 'acs_session_not_created'
        will be sent back to subscribers.
        """
        (session_id, error) = push_adapter.login()
        if error:
            self.publish('acs_session_not_created', error)
        else:
            self.publish('acs_session_created', session_id)

class ACSUserIdsNotifier(Publisher):
    def perform(self, push_adapter, session_id, channel, user_ids, payload):
        """Invoke the ``notify`` method of the push notifications adapter
        and then publish result messages accordingly.

        On success, a 'acs_user_ids_notified' message is published, while
        if something bad happens, a 'acs_user_ids_not_notified' message will be
        sent back to subscribers.
        """
        (_, error) = push_adapter.notify(session_id, channel, user_ids, payload)
        if error:
            self.publish('acs_user_ids_not_notified', error)
        else:
            self.publish('acs_user_ids_notified')

class ACSPayloadsForUserIdNotifier(Publisher):
    def perform(self, push_adapter, session_id, channel, tuples):
        errors = []
        for (user_id, payload) in tuples:
            (_, error) = push_adapter.notify(session_id, channel,
                                             [user_id], payload)
            if error:
                errors += [error]
        if errors:
            self.publish('acs_user_ids_not_notified', errors)
        else:
            self.publish('acs_user_ids_notified')

class PayloadsByUserCreator(Publisher):
    def perform(self, payload_factory, users):
        self.publish('payloads_created',
                     [payload_factory(u) for u in users])

EARTH_RADIUS = 6371.009
KM_PER_DEG_LAT = 2 * pi * EARTH_RADIUS / 360.0

def distance(lat1, lon1, lat2, lon2):
    km_per_deg_lon = KM_PER_DEG_LAT * cos(radians(lat1))
    return sqrt((KM_PER_DEG_LAT * (lat1 - lat2)) ** 2 +
                (km_per_deg_lon * (lon1 - lon2)) ** 2)

class DistanceCalculator(Publisher):
    def perform(self, lat1, lon1, lat2, lon2):
        self.publish('distance_calculated', distance(lat1, lon1, lat2, lon2))

def serialize_date(date):
    if date is None:
        return None
    return date.strftime('%Y-%m-%dT%H:%M:%SZ')


from django.db import models
from datetime import datetime

class ShowManager(models.Manager):
    def basic_validator(self, postData):
        errors = {}
        if len(postData['title']) < 3:
            errors['title'] = 'Title should be at least 2 characters.'
        if Show.objects.filter(title=postData['title']):
            errors['title_exists'] = "There's already a show with that title."
        if len(postData['network']) < 3:
            errors['network'] = 'Network should be at least 3 characters.'
        if postData['date']:
            input_date = datetime.strptime(postData['date'], "%Y-%m-%d")
        if not postData['date'] or input_date.date() > datetime.now().date():
            errors['date'] = 'Please enter a valid date.'
        if len(postData['desc']) > 0 and len(postData['desc']) < 11:
            errors['desc'] = 'Description should be at least 10 characters.'
        return errors

class Show(models.Model):
    title = models.CharField(max_length=255, unique=True)
    network = models.CharField(max_length=255)
    date = models.DateField()
    desc = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = ShowManager()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('fantaapp', '0015_auto_20150807_1532'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='incontrocalendario',
            name='allenatorecasa',
        ),
        migrations.RemoveField(
            model_name='incontrocalendario',
            name='allenatoretrasferta',
        ),
        migrations.RemoveField(
            model_name='incontrocalendario',
            name='lega',
        ),
        migrations.AddField(
            model_name='incontrolega',
            name='disputato',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='incontrolega',
            name='golcasa',
            field=models.PositiveSmallIntegerField(null=True, blank=True),
        ),
        migrations.AddField(
            model_name='incontrolega',
            name='goltrasferta',
            field=models.PositiveSmallIntegerField(null=True, blank=True),
        ),
        migrations.AlterUniqueTogether(
            name='allenatore',
            unique_together=set([('utente', 'lega')]),
        ),
        migrations.DeleteModel(
            name='IncontroCalendario',
        ),
    ]


import os
import time
import base64
from PIL import Image
from io import BytesIO

import torch
from torch.autograd import Variable
from torchvision.utils import save_image

from models import TransformerNet
from utils import *

from flask import *
from flask_cors import CORS

app = Flask(__name__, )
# r'/*' 是通配符，让本服务器所有的URL 都允许跨域请求
CORS(app, resources=r'/*')

# 上传文件
@app.route("/nst/", methods=['POST'])
def uploadFile():
    result_text = {"statusCode": 200}

    if not request.form:  # 检测是否有数据
        result_text['rc'] = 'fail'
    else:
        table = {
            '0': '/home/www/flask/nst/model/van_gogh.pth',
            '1': '/home/www/flask/nst/model/line_geometry.pth',
            '2': '/home/www/flask/nst/model/mona_lisa.pth',
            '3': '/home/www/flask/nst/model/rain_princess.pth',
            '4': '/home/www/flask/nst/model/starry_night.pth',
            '5': '/home/www/flask/nst/model/wave.pth',
            '6': '/home/www/flask/nst/model/plaid_portrait.pth',
            '7': '/home/www/flask/nst/model/obama_hope.pth',
            '8': '/home/www/flask/nst/model/sunday_afternoon.pth',
            '9': '/home/www/flask/nst/model/the_scream.pth',
        }
        ind = request.form.get('style')
        img64 = request.form.get('img')

        checkpoint_model = table[ind]

        byte_data = base64.b64decode(img64)
        image_data = BytesIO(byte_data)
        img = Image.open(image_data)

        device = torch.device("cpu")

        transform = style_transform()

        # Define model and load model checkpoint
        transformer = TransformerNet().to(device)
        transformer.load_state_dict(torch.load(checkpoint_model, map_location=torch.device('cpu')))
        transformer.eval()

        # Prepare input
        image_tensor = Variable(transform(img)).to(device)
        image_tensor = image_tensor.unsqueeze(0)

        # Stylize image
        with torch.no_grad():
            stylized_image = denormalize(transformer(image_tensor)).cpu()

        t = f"/home/www/flask/nst/tmp/{str(time.time())}.png"

        save_image(stylized_image, t)
        with open(t, "rb") as f:
            base64_str = base64.b64encode(f.read())

        os.remove(t)

        result_text['rc'] = base64_str.decode()

    response = make_response(jsonify(result_text))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,HEAD,GET,POST'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with'
    return response

if __name__ == '__main__':
    app.run(port=2306)


p = [["E", "C", "A", "F"]]
b = 0
for i in range(int(input())):
    s = input().split()
    if s == p[-1]:
        b += 1
        p.pop()
    else:
        p.append(s[::-1])

    if not p:
        p.append(["E", "C", "A", "F"])

print(b)


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

import enum
from django.utils.translation import ugettext_lazy as _

class NotifyLevel(enum.IntEnum):
    involved = 1
    all = 2
    none = 3

NOTIFY_LEVEL_CHOICES = (
    (NotifyLevel.involved, _("Involved")),
    (NotifyLevel.all, _("All")),
    (NotifyLevel.none, _("None")),
)

class WebNotificationType(enum.IntEnum):
    assigned = 1
    mentioned = 2
    added_as_watcher = 3
    added_as_member = 4
    comment = 5
    mentioned_in_comment = 6

WEB_NOTIFICATION_TYPE_CHOICES = (
    (WebNotificationType.assigned, _("Assigned")),
    (WebNotificationType.mentioned, _("Mentioned")),
    (WebNotificationType.added_as_watcher, _("Added as watcher")),
    (WebNotificationType.added_as_member, _("Added as member")),
    (WebNotificationType.comment, _("Comment")),
    (WebNotificationType.mentioned_in_comment, _("Mentioned in comment")),
)


from audioop import mul
import math
import os
import json
import re
from tokenize import Double
from urllib import response

from qgis.PyQt import QtWidgets, uic

from qgis.PyQt.QtCore import pyqtSignal, Qt
from qgis.utils import iface
from qgis.core import QgsRectangle
from qgis.core import (
    QgsProject,
)
from qgis.core import QgsRectangle, QgsMapLayer
from qgis.gui import QgsVertexMarker, QgsMapTool
from .api import endpoints
from .utils import readSetting, get_epsg_from_tm3_zone, get_layer_config, sdo_to_layer
from .maptools import MapTool

FORM_CLASS, _ = uic.loadUiType(
    os.path.join(os.path.dirname(__file__), "../ui/download_persil_sekitarnya.ui")
)

class DownloadPersilSekitar(QtWidgets.QDialog, FORM_CLASS):
    """Dialog for Peta Bidang"""

    closingPlugin = pyqtSignal()

    def __init__(self, parent=iface.mainWindow()):
        super(DownloadPersilSekitar, self).__init__(parent)
        self.iface = iface
        self.canvas = iface.mapCanvas()
        self.setupUi(self)

        self.srid_code = [
            23830,
            23831,
            23832,
            23833,
            23834,
            23835,
            23836,
            23837,
            23838,
            23839,
            23840,
            23841,
            23842,
            23843,
            23844,
            23845,
        ]

        self.list_vm = []

        self.cmb_propinsi.currentIndexChanged.connect(
            self._cmb_propinsi_selected_index_changed
        )
        self.cmb_kabupaten.currentIndexChanged.connect(
            self._cmb_kabupaten_selected_index_changed
        )
        self.cmb_kecamatan.currentIndexChanged.connect(
            self._cmb_kecamatan_selected_index_changed
        )
        self.radius.setText("100")
        self.btn_titik_tengah.clicked.connect(self.btnDownload_Click)

        self.setup_workpanel()

    def setup_workpanel(self):
        kantor = readSetting("kantorterpilih", {})
        if not kantor:
            QtWidgets.QMessageBox.warning(
                None, "GeoKKP", "Pilih lokasi kantor lebih dahulu"
            )
            return

        self._kantor_id = kantor["kantorID"]
        self._tipe_kantor_id = str(kantor["tipeKantorId"])

        self._set_cmb_propinsi()

        self.cmb_coordinate_system.clear()
        self.cmb_coordinate_system.addItem("TM3-46.2",84.5)
        self.cmb_coordinate_system.addItem("TM3-47.1",87.5)
        self.cmb_coordinate_system.addItem("TM3-47.2",90.5)
        self.cmb_coordinate_system.addItem("TM3-48.1",93.5)
        self.cmb_coordinate_system.addItem("TM3-48.2",96.5)
        self.cmb_coordinate_system.addItem("TM3-49.1",99.5)
        self.cmb_coordinate_system.addItem("TM3-49.2",112.5)
        self.cmb_coordinate_system.addItem("TM3-50.1",115.5)
        self.cmb_coordinate_system.addItem("TM3-50.2",118.5)
        self.cmb_coordinate_system.addItem("TM3-51.1",121.5)
        self.cmb_coordinate_system.addItem("TM3-51.2",124.5)
        self.cmb_coordinate_system.addItem("TM3-52.1",127.5)
        self.cmb_coordinate_system.addItem("TM3-52.2",130.5)
        self.cmb_coordinate_system.addItem("TM3-53.1",133.5)
        self.cmb_coordinate_system.addItem("TM3-53.2",136.5)
        self.cmb_coordinate_system.addItem("TM3-54.1",139.5)

        self.cmb_coordinate_system.setCurrentIndex(7)

    def _cmb_propinsi_selected_index_changed(self, index):
        self._set_cmb_kabupaten()

    def _cmb_kabupaten_selected_index_changed(self, index):
        self._set_cmb_kecamatan()

    def _cmb_kecamatan_selected_index_changed(self, index):
        self._set_cmb_desa()

    def _set_cmb_propinsi(self):
        response = endpoints.get_provinsi_by_kantor(
            self._kantor_id, self._tipe_kantor_id
        )
        prop_dataset = json.loads(response.content)

        self.cmb_propinsi.clear()
        for prop in prop_dataset["PROPINSI"]:
            self.cmb_propinsi.addItem(prop["PROPNAMA"], prop["PROPINSIID"])

    def _set_cmb_kabupaten(self):
        selected_prov = self.cmb_propinsi.currentData()
        response = endpoints.get_kabupaten_by_kantor(
            self._kantor_id, self._tipe_kantor_id, selected_prov
        )
        kabu_dataset = json.loads(response.content)

        self.cmb_kabupaten.clear()
        for kab in kabu_dataset["KABUPATEN"]:
            self.cmb_kabupaten.addItem(kab["KABUNAMA"], kab["KABUPATENID"])

    def _set_cmb_kecamatan(self):
        selected_kab = self.cmb_kabupaten.currentData()
        response = endpoints.get_kecamatan_by_kantor(
            self._kantor_id, self._tipe_kantor_id, selected_kab
        )
        keca_dataset = json.loads(response.content)

        self.cmb_kecamatan.clear()
        for kec in keca_dataset["KECAMATAN"]:
            self.cmb_kecamatan.addItem(kec["KECANAMA"], kec["KECAMATANID"])

    def _set_cmb_desa(self):
        selected_kec = self.cmb_kecamatan.currentData()
        response = endpoints.get_desa_by_kantor(
            self._kantor_id, self._tipe_kantor_id, selected_kec
        )
        desa_dataset = json.loads(response.content)

        self.cmb_desa.clear()
        for des in desa_dataset["DESA"]:
            self.cmb_desa.addItem(des["DESANAMA"], des["DESAID"])

    def create_vertex_marker(self, type="CROSS"):
        vm = QgsVertexMarker(self.canvas)

        vm.setPenWidth(3)
        vm.setIconSize(7)
        return vm

    def btnDownload_Click(self):
        self.active = False
        QgsMapTool.__init__(self, self.canvas)

        self.vm_1 = self.create_vertex_marker()
        self.point_tool_1 = MapTool(self.canvas, self.vm_1)
        self.point_tool_1.map_clicked.connect(self.update_titik_1)
        self.canvas.setCursor(Qt.CrossCursor)
        self.canvas.setMapTool(self.point_tool_1)

    def update_titik_1(self, x, y):
        layers = self.canvas.layers()
        w = self.canvas.mapUnitsPerPixel() * 3
        rect = QgsRectangle(x - w, y - w, x + w, y + w)

        srid = self.cmb_coordinate_system.currentIndex()
        srs = str(self.srid_code[srid])
        lintang = self.cmb_coordinate_system.currentData()

        nilaiRadius = float(self.radius.text())
        # print(nilaiRadius)
        hitungBawah = 0
        hitungAtas = 0

        for layer in layers:
            if layer.type() == QgsMapLayer.RasterLayer:
                continue
            lRect = self.canvas.mapSettings().mapToLayerCoordinates(layer, rect)
            # layer.selectByRect(lRect, False)
            layer.selectByRect(lRect)
            features = layer.selectedFeatures()
            if(features != []):
                koordinatX = features[0].geometry().centroid().asPoint().x()
                koordinatY = features[0].geometry().centroid().asPoint().y()
                hitungBawah = self.worldCoordinate(6378137,0.0033528106646687913,0.9999,200000,1500000,lintang,0,koordinatX-nilaiRadius,koordinatY-nilaiRadius)
                hitungAtas = self.worldCoordinate(6378137,0.0033528106646687913,0.9999,200000,1500000,lintang,0,koordinatX+nilaiRadius,koordinatY+nilaiRadius)

        if(hitungBawah == 0):
            hitungBawah = self.worldCoordinate(6378137,0.0033528106646687913,0.9999,200000,1500000,lintang,0,x-nilaiRadius,y-nilaiRadius)
            hitungAtas = self.worldCoordinate(6378137,0.0033528106646687913,0.9999,200000,1500000,lintang,0,x+nilaiRadius,y+nilaiRadius)

        self.canvas.scene().removeItem(self.vm_1)
        self.point_tool_1.deactivate()
        self.canvas.unsetMapTool(self.point_tool_1)

        response = endpoints.parcel_window_sdo(str(hitungBawah["x"]),str(hitungBawah["y"]),str(hitungAtas["x"]),str(hitungAtas["y"]),str(srs))
        persil = json.loads(response.content)
        for index,persilFeature in enumerate(persil["persils"]):
            persil["persils"][index]["label"] = persilFeature["nomor"]
        self._draw(persil)

    def _draw(self, upr):
        # print(upr)
        crs = self.cmb_coordinate_system.currentText()
        zone = crs.replace("TM3-", "")
        epsg = get_epsg_from_tm3_zone(zone)

        if upr["persils"]:
            if upr["persils"]:
                layer_config = get_layer_config("020100")
                # print(layer_config)
                layer = sdo_to_layer(
                    upr["persils"],
                    name=layer_config["Nama Layer"],
                    symbol=layer_config["Style Path"],
                    crs=epsg,
                    coords_field="boundary",
                )

    def worldCoordinate(self,a,flat,k0,fe,fn,LonOri,LatOri,E,N):
        fecc = 2*flat - math.pow(flat,2)
        secc = fecc / (1 - fecc)

        m0 = self.CalculateM(a,fecc,LatOri)
        m1 = m0 + (N - fn) / k0
        Mu1 = m1 / (a*(1-fecc/4 - 3*math.pow(fecc,2)/64 - 5*math.pow(fecc,3)/256))
        e1 = (1 - math.pow((1-fecc),0.5))/(1+math.pow((1-fecc),0.5))

        lat1 = Mu1 + (3*e1/2 - 27*math.pow(e1,3)/32)*math.sin(2*Mu1) + (21*math.pow(e1,2)/16 - 55*math.pow(e1,4)/32)*math.sin(4*Mu1)+(151*math.pow(e1,3)/96)*math.sin(6*Mu1)+(1097*math.pow(e1,4)/512)*math.sin(8*Mu1)
        rho1 = a * (1 - fecc)/math.pow(1-fecc*math.pow(math.sin(lat1),2),1.5)
        v1 = a / math.pow(1-fecc*math.pow(math.sin(lat1),2),0.5)

        t1 = math.pow(math.tan(lat1),2)
        c1 = secc*math.pow(math.cos(lat1),2)
        d = (E - fe ) / (v1 * k0)

        lat = lat1 - (v1*math.tan(lat1)/rho1)*(math.pow(d,2)/2 - (5+3*t1+10*c1-4*math.pow(c1,2)-9*secc)*math.pow(d,4)/24+(61+90*t1+298*c1+45*math.pow(t1,2)-25*secc-3*math.pow(c1,2))*math.pow(d,6)/720)
        lon = self.convertRadian(LonOri) + (d - (1+2*t1)*math.pow(d,3)/6+(5-2*c1+28*t1-3*math.pow(c1,2)+8*secc+24*math.pow(t1,2))*math.pow(d,5)/120)/math.cos(lat1)

        koordinat = {
            "x":lon*180/math.pi,
            "y":lat*180/math.pi
        }

        return koordinat

    def convertRadian(self,angle):
        rad = angle*math.pi/180
        return rad

    def CalculateM(self,a,fecc,LatOri):
        w = (1 - fecc/4 - 3*math.pow(fecc,2)/64 - 5*math.pow(fecc,3)/256)*self.convertRadian(LatOri)
        x = (3*fecc/8 + 3*math.pow(fecc,2)/32 + 45*math.pow(fecc,3)/1024)*math.sin(2*self.convertRadian(LatOri))
        y = (15*math.pow(fecc,2)/256 + 45*math.pow(fecc,3)/1024) * math.sin(4*self.convertRadian(LatOri))
        z = (35*math.pow(fecc,3)/3072)* math.sin(6*self.convertRadian(LatOri))
        m = a * (w-x+y-z)
        return m


for t in range(int(input())) :
    n = [ i for i in input()]
    case = [int(''.join(n))]

    for i in range(len(n)):
        for j in range(i):
            temp = n.copy()
            temp[i], temp[j] = temp[j], temp[i]

            if (temp not in case) and (temp[0] != '0') : case.append(int(''.join(temp)))
            else : continue

    print(f'#{t+1} {min(case)} {max(case)}')


import sys

AVG_WINDOW = 50
TIMES_LARGER = 4
interesting_dates = []
first_bit = []

moving_avg = 0
counter = 0
with open(sys.argv[1], "r") as dates_in:
    dates = dates_in.readlines()
    for date in dates:
        counter +=1
        stuff = date.lstrip().split(" ")
        count = int(stuff[0])
        date = stuff[1].strip()

        if counter < AVG_WINDOW:
            first_bit.append((count,date))
        elif counter == AVG_WINDOW:
            start_avg = 0
            for count,date in first_bit:
               start_avg += int(count)
            moving_avg = start_avg
            start_avg /= AVG_WINDOW
            for count,date in first_bit:
                if int(count) > start_avg*TIMES_LARGER:
                    interesting_dates.append((count, start_avg, date))
        else:
            shiz = first_bit.pop(0)
            moving_avg -= shiz[0]
            first_bit.append((count,date))
            moving_avg += count
            test = moving_avg/AVG_WINDOW
            if count > (test)*TIMES_LARGER:
                interesting_dates.append((count,test,date))

for count, avg, date in interesting_dates:
    print(date)
#print(interesting_dates)


# 0708
# def 연습
z = 3
def func_1 (a, b):
    y = a + b
    return y

func_1 (2, 3)
print()

# 리스트
lst = list(range(1, 5))
print('lst = ', lst)
lst[0]

lst = [[1, 2, 3, 4], [5, 6, 7, 8]]
lst

# 4까지 더하기
sum = 0
for num in range(5) :
    sum += num
print ("~ 4 =", sum)

# 10까지 더하기
sum = 0
for num in range(11) :              # range(start, end-1, step)
    sum += num
print ("~ 10 =", sum)

# n까지 더하는 함수 만들기_1
def calcsum (n) :
    sum = 0
    for num in range (n + 1):
        sum += num
    return sum

print ("~ 4 = ", calcsum(4))
print ("~ 10 = ", calcsum(10))

# n까지 더하는 함수 만들기_2
def printsum(n) :
    sum = 0
    for num in range(n + 1):
        sum += num
    print ("~", n, "=", sum)

printsum(4)
printsum(10)

#0709
# 실습 1
h = int(input("height : "))
for i in range(1, h+1):
    for j in range(i) :
        print('*', end='')
    print()
def Counter (n) :
    sum = 0
    for num in range(n+1) :
        sum += num
    return sum
print ("star 개수 : ", Counter(h))

# 실습 1 다른 풀이
def star(x) :
    i = 0
    for stage in range(1, x+1) :
        if stage <=x :
            print('*' * stage)
            i += stage
    return i
star_count = star(3)
print("star 개수 : ", star_count)

# 연습
price = 500
print("궁금하면 " + str(price) + "원!")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb  5 13:44:09 2017

@author: fransebas
"""
from vectors import *

class Matrix():

    @staticmethod
    def I(n):
        return Matrix([ [1 if i is j else 0 for j in range(n) ] for i in range(n) ])

    @staticmethod
    def toVector(M):
        if M.m is 1:
            return M[0]
        else:
            """ Should rise an exception """
            print ("The matrix is not a vector")

    def __init__(self, vectors):
        if type(vectors[0]) is type(Vector([0])):
            self.vectors = vectors
            self.n = vectors[0].dim() # columns
            self.m = len(vectors) # rows
        else:
            self.vectors = [ Vector(v) for v in (vectors) ]
            self.n = len(vectors[0]) # columns
            self.m = len(vectors) # rows

    def copy(self):
        l = []
        for v in self.vectors:
            l.append( list(v.components) )
        return Matrix( l )

    '''@staticmethod
    def T(A):
        B = A.copy()
        # Debuggin ****************
        print (B)
        return B.T()'''

    def T(self):
        """ transpose of a matrix """

        vectors = [ [ 0 for i in range(self.m) ] for j in range(self.n) ]

        for i in range( len( self.vectors ) ): #rows
            for j in range( self.vectors[0].dim() ): #colums
                vectors[j][i] = self.vectors[i][j]

        return Matrix(vectors)

    def __mul__(self, B):
        """ Multiply matrix A*B """
        C = B.T()
        vectors = []
        i = 0
        if self.n is B.m:
            for r in self.vectors:
                vectors.append([])
                for c in C.vectors:
                    vectors[i].append(r*c)

                i += 1

            return Matrix(vectors)
        else:
            """should rise exception """
            print ("error no posible mutiplication")

    def __str__(self):
        s = ""
        for v in self.vectors:
            s += str(v) + '\n'
        return s

    def p(self, r1, r2):
        vAux = self[r2].copy()
        self[r2] = self[r1]
        self[r1] = vAux

    def r(self, r1, r2, c):
        """ sum row 2 by a multiple c of row 1  """
        self[r2] = self[r2] + ( c*self[r1] )

    def __getitem__(self, i):
        return self.vectors[i]

    def __setitem__(self, i, value):
        self.vectors[i] = value

    def solve(self,B):
        """ Solve a square matrix given a set of solutions B,
        B should be nx1 (most cases B.T())"""
        return (self**-1)*B

    def GaussJordan(self,Aug):
        print("this is the sol")
        print (Aug)
        print (self**-1)
        return (self**-1)*Aug
        """if self.n is self.m:
            A = self.copy()

            for i in range ( len( A.vectors ) ):
                 #select the pivot
                j = A.findNonZero(i)

                if j is None:
                    print ("Non invertible matrix")
                    return

                if j is not i:
                    A.p  (i, j)
                    Aug.p(i, j)

                #1 divide row to get 1

                (Aug[i]) /= A[i][i]
                A[i] /= A[i][i]

                for k in range(0, len( A.vectors )):
                    if k is i:
                        continue
                        #eros below and over the diagonal

                        c = -A.vectors[k][i]

                        A.r  (i, k, c)
                        Aug.r(i, k, c)

                return (A,Aug)

        else:
            print ("No square matrix")"""

    def findNonZero(self, i):
        for j in range( i, self.n ):
            if self[j][i] is not 0:
                return j
        return None

    def simplify(self, precision=16):
        for i in range ( len ( self.vectors ) ):
            for j in range ( self.vectors[i].dim() ):
                ( m,e ) = math.frexp( self[i][j] )

                if e <= -15:
                    self[i][j] = 0
                    continue

                """ It's not the best, I should check for all Natruals and not
                only 1"""
                if self[i][j] > 0.9999999 and self[i][j] < 1:
                    self[i][j] = 1
                    continue

    def __pow__(self, e):

        if self.n is self.m:
            if e is -1:
                # self.GaussJordan(Inv = Matrix.I(self.n))
                A = self.copy()
                Inv = Matrix.I(self.n)

                for i in range ( len( A.vectors ) ):
                    """ select the pivot """
                    j = A.findNonZero(i)

                    if j is None:
                        print ("Non invertible matrix")
                        return

                    if j is not i:
                        A.p  (i, j)
                        Inv.p(i, j)

                    """ 1 divide row to get 1 """

                    (Inv[i]) /= A[i][i]
                    A[i] /= A[i][i]

                    for k in range(0, len( A.vectors )):
                        if k is i:
                            continue
                        """ zeros below and over the diagonal """

                        c = -A.vectors[k][i]

                        A.r  (i, k, c)
                        Inv.r(i, k, c)

                return Inv

        else:
            print ("No square matrix")


"""
The core idea of the data interface is to separate the PRM model from the relational data soucre. The module :mod:`.datainterface` contains a collection of methods to access the relational data that are used by different algorithms (e.g. CPD learners, inference methods, EM algorithm). Another advantage of this approach is that the data is not required to be in a fixed database format.
"""

'''
The singular DataInterface instance contains a collection of methods that are used
by different algorithms (e.g. CPD learners, EM algorithm, Inference). The description
of a function should give examples of algorithms that use that method.

-At this point there is no error testing, e.g. the statements that will query
the data are derived from the names of the entities/relationships etc in the
prm. In the future one could envision some sort of mapping that is also passed
on as part of the specification of a prm

There will be different ways a prm (e.g. a learner or inference class), can
access the data. For large datasets that have to be queried multiple times
, there will be an MySQL interface. A similar interface for SQLite will be
implemented first. SQLite allows the data to be loaded into the memory.
Then it can be accessed faster in the usual way. Of course both MySQL and
SQLite use the SQL language interchangeably.
'''

'''
Analytics
    by adding the decorator @time_analysis before any
    function we collect runtime information
'''

import logging

from analytics.performance import time_analysis

name = 'UnNamed'
"""The name of the data interface
"""

DSI = None
"""List that contains all :class:`~data.datainterface.DataSetInterface` instances that connect to the data
"""

diType = 'UnSpecified'
"""The type of dataset used, e.g. `crossvalidation` or `testtraining`
"""

trainingSets = {}
"""Dictionary that maps a crossvalidation test set (one `DataSetInterface` in `datainterface.DSI`) with the corresponding training set (all other `DataSetInterfaces` in `datainterface.DSI`)"""

def configure(prm):
    '''
    A method that allows us to configure a dataset interface based on information from the instantiated PRM.
    '''

    # When dealing with aggregation, we want to create VIEWS to facilitate the sql queries.
    # If a dependency has a 1:n or m:n relationship, then aggregation is required.

    # print "\tConfiguring DataInterface '%s' with PRM '%s'"%(self.name,prm.name)

    # View currently disabled as we don't use them
    #
    # for dep in prm.dependencies.values():
    #     if dep.aggregator is not None:
    #         for dsi in self.DSI:
    #             print '\t Creating VIEW for %s'%dep.name
    #             dsi.createView(dep)

def computeTrainingSets():
    '''
    Returns a dictionary mapping a crossvalidation test set with the corresponding training set { datasetinstance : [datasetinstance1,datasetinstance2,....]}. Every :class:`!DataSetInterface` in `datainterface.DSI` is a key in `datainterface.trainingSets`, the value is a list of all other :class:`!DataSetInterface` instances in `datainterface.DSI`
    '''

    for dsi in DSI:
        ts = []
        for tdsi in DSI:
            if tdsi!=dsi:
                ts.append(tdsi)
        trainingSets[dsi]=ts

def datasetinterfaceFactory(path,ditype):
    '''
    Creates a connection to a database. There are possibly multiple dataset connections to do crossvalidation.

    :arg path: The path to the database
    :arg ditype: Type of database, e.g. `SQLite`
    :returns: A :class:`.DataSetInterface` instance
    '''
    logging.info('\tDataSet: %s (%s)'%(path.split('/')[-1],ditype))

    if ditype == 'SQLite':
        from data.sqliteinterface import SQLiteDI
        return SQLiteDI( path)
    elif ditype == 'MySQL':
        raise Exception("MySQL not yet implemented")
    elif ditype == 'XML':
        raise Exception("XML not yet implemented")
    else:
        raise Exception("unknown data interface type")

class DataSetInterface:
    '''
    An instance of the class connects a PRM with the relational data base that it models. This is an abstract class, sublclasses have to implement the required methdos for different database systems. E.g. :class:`data.sqliteinterface.SQLiteDI` is for SQLite.

    There data is queried by the parameter learning algorithm, e.g. :class:`learners.cpdlearners`, as well as by the inference methods; the inference :mod:`engine` is unrolling the Ground Bayesian Network.
    '''

    def __init__(self,dsiType):
        '''
        Shouldn't be executed since the class is abstract.
        '''
        self.dsiType = dsiType

    def __repr__(self):
        ''' String representation of the data interface'''
        raise Exception("method __repr__() is not implemented in the DataSetInterface")


# -*- coding: utf-8 -*-
import re

import scrapy

from ..custom_setting import inspect_settings
from ..items import InspectItem

class InspectSpider(scrapy.Spider):
    custom_settings = inspect_settings

    name = 'inspect'
    allowed_domains = ['jib.xywy.com']
    start_urls = []

    base_url = 'http://jib.xywy.com'

    # 生成字母a-z，并组合为链接
    char = list(map(chr, range(ord('a'), ord('z') + 1)))
    for c in char:
        start_urls.append(base_url + '/html/' + c + '.html')

    def parse(self, response):
        path = response.xpath('//ul[@class="ks-zm-list clearfix mt10"]/li/a/@href').extract()
        for p in path:

            title = response.xpath('//a[@href="' + p + '"]/text()').extract()[0].strip()
            if '...' in title:
                title = '###'
            item = dict()
            item['entity1'] = title

            p = re.sub('/il_sii_', '/il_sii/inspect/', p)
            yield scrapy.Request(self.base_url + p, meta={'item': item}, callback=self.parse_inspect)

    def parse_inspect(self, response):
        items = response.meta['item']
        if items['entity1'] == '###':
            items['entity1'] = response.xpath('//div[@class="jb-name fYaHei gre"]/text()').extract()[0]
        # print(title)
        检查项目s = response.xpath('//div[@class="more-zk pr"]//ul[@class="clearfix jib-check "]/li['
                               '@class="check-item"]/a/@href').extract()

        if len(检查项目s) != 0:
            for j in 检查项目s:

                title = response.xpath('//ul[@class="clearfix jib-check "]/li[@class="check-item"]/a[@href="' + j + '"]/text()').extract()[0].strip()
                if '...' in title:
                    title = '###'

                item = InspectItem()
                item['entity1'] = items['entity1']
                item['entity2'] = title
                item['relation'] = '相关检查'

                yield scrapy.Request(j, meta={'item': item}, callback=self.parse_next, dont_filter=True)

    def parse_next(self, response):
        item = response.meta['item']
        if item['entity2'] == '###':
            item['entity2'] = response.xpath('//div[@class="baby-weeks"]/div[@class="clearfix"]/strong/text()').extract()[0]
        return item


"""This class performs database queries for the physiological_annotation_parameter table"""

__license__ = "GPLv3"

class PhysiologicalAnnotationParameter:

    def __init__(self, db, verbose):
        """
        Constructor method for the PhysiologicalAnnotationParameter class.

        :param db                 : Database class object
         :type db                 : object
        :param verbose            : whether to be verbose
         :type verbose            : bool
        """

        self.db = db
        self.table = 'physiological_annotation_parameter'
        self.verbose = verbose

    def insert(self, annotation_file_id, description, sources, author):
        """
        Inserts a new entry in the physiological_annotation_parameter table.

        :param annotation_file_id : annotation file's ID
         :type annotation_file_id : int

        :param description        : Description of the annotations
         :type description        : string

        :param sources            : Description of the file(s) used to make the annotations
         :type sources            : string

        :param author             : Annotation's author
         :type author             : string
        """

        self.db.insert(
            table_name   = self.table,
            column_names = ('AnnotationFileID', 'Description', 'Sources', 'Author'),
            values       = (annotation_file_id, description, sources, author)
        )

    def grep_id_from_physiological_file_id(self, physiological_file_id):
        """
        Gets the AnnotationParameterID given a physiological_file_id

        :param physiological_file_id : Physiological file's ID
         :type physiological_file_id : int

        :return                      : id of the row if found or None
         :rtype                      : int
        """

        paramID = self.db.pselect(
            query="SELECT AnnotationParameterID "
            "FROM " + self.table + " p "
            "JOIN physiological_annotation_file f ON f.AnnotationFileID = p.AnnotationFileID "
            "WHERE f.PhysiologicalFileID = %s "
            "LIMIT 1",
            args=(physiological_file_id,)
        )

        return paramID[0]['AnnotationParameterID'] if paramID else None


import tensorflow as tf
import json

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif

from tensorflow.python.keras import models
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.layers import Dropout

# Vectorization parameters
# Range (inclusive) of n-gram sizes for tokenizing text.
NGRAM_RANGE = (1, 3)

# Limit on the number of features. We use the top 20K features.
TOP_K = 20000

# Whether text should be split into word or character n-grams.
# One of 'word', 'char'.
TOKEN_MODE = 'word'

# Minimum document/corpus frequency below which a token will be discarded.
MIN_DOCUMENT_FREQUENCY = 2

# Limit on the length of text sequences. Sequences longer than this
# will be truncated.
MAX_SEQUENCE_LENGTH = 500

def ngram_vectorize(train_texts, train_labels, val_texts):
    """Vectorizes texts as ngram vectors.
    1 text = 1 tf-idf vector the length of vocabulary of uni-grams + bi-grams.
    # Arguments
        train_texts: list, training text strings.
        train_labels: np.ndarray, training labels.
        val_texts: list, validation text strings.
    # Returns
        x_train, x_val: vectorized training and validation texts
    """
    # Create keyword arguments to pass to the 'tf-idf' vectorizer.
    kwargs = {
            'ngram_range': NGRAM_RANGE,  # Use 1-grams + 2-grams.
            'dtype': 'int32',
            'strip_accents': 'unicode',
            'decode_error': 'replace',
            'analyzer': TOKEN_MODE,  # Split text into word tokens.
            'stop_words' : 'english',
            'min_df': MIN_DOCUMENT_FREQUENCY
            #'max_df': 0.9
    }
    vectorizer = TfidfVectorizer(**kwargs)

    # Learn vocabulary from training texts and vectorize training texts.
    x_train = vectorizer.fit_transform(train_texts)
    print(x_train.shape)
    print(x_train)
    # Vectorize validation texts.
    x_val = vectorizer.transform(val_texts)
    # Select top 'k' of the vectorized features.
    selector = SelectKBest(f_classif, k=min(TOP_K, x_train.shape[1]))
    selector.fit(x_train, train_labels)
    x_train = selector.transform(x_train)
    x_val = selector.transform(x_val)

    x_train = x_train.astype('float32')
    x_val = x_val.astype('float32')
    return x_train, x_val

def get_num_classes(labels):
    """Gets the total number of classes.

    # Arguments
        labels: list, label values.
            There should be at lease one sample for values in the
            range (0, num_classes -1)

    # Returns
        int, total number of classes.

    # Raises
        ValueError: if any label value in the range(0, num_classes - 1)
            is missing or if number of classes is <= 1.
    """
    num_classes = max(labels) + 1
    missing_classes = [i for i in range(num_classes) if i not in labels]
    if len(missing_classes):
        raise ValueError('Missing samples with label value(s) '
                         '{missing_classes}. Please make sure you have '
                         'at least one sample for every label value '
                         'in the range(0, {max_class})'.format(
                            missing_classes=missing_classes,
                            max_class=num_classes - 1))

    if num_classes <= 1:
        raise ValueError('Invalid number of labels: {num_classes}.'
                         'Please make sure there are at least two classes '
                         'of samples'.format(num_classes=num_classes))
    return num_classes

def _get_last_layer_units_and_activation(num_classes):
    """Gets the # units and activation function for the last network layer.

    # Arguments
        num_classes: int, number of classes.

    # Returns
        units, activation values.
    """
    if num_classes == 2:
        activation = 'sigmoid'
        units = 1
    else:
        activation = 'softmax'
        units = num_classes
    return units, activation

def mlp_model(layers, units, dropout_rate, input_shape, num_classes):
    """Creates an instance of a multi-layer perceptron model.

    # Arguments
        layers: int, number of `Dense` layers in the model.
        units: int, output dimension of the layers.
        dropout_rate: float, percentage of input to drop at Dropout layers.
        input_shape: tuple, shape of input to the model.
        num_classes: int, number of output classes.

    # Returns
        An MLP model instance.
    """
    op_units, op_activation = _get_last_layer_units_and_activation(num_classes)
    model = models.Sequential()
    model.add(Dropout(rate=dropout_rate, input_shape=input_shape))
    for _ in range(layers-1):
        model.add(Dense(units=units, activation='relu'))
        model.add(Dropout(rate=dropout_rate))
    model.add(Dense(units=op_units, activation=op_activation))
    print(model.summary())
    return model

def train_ngram_model(data,
                      learning_rate=1e-3,
                      epochs=1000,
                      batch_size=32,
                      layers=2,
                      units=128,
                      dropout_rate=0.2):
    """Trains n-gram model on the given dataset.

    # Arguments
        data: tuples of training and test texts and labels.
        learning_rate: float, learning rate for training model.
        epochs: int, number of epochs.
        batch_size: int, number of samples per batch.
        layers: int, number of `Dense` layers in the model.
        units: int, output dimension of Dense layers in the model.
        dropout_rate: float: percentage of input to drop at Dropout layers.

    # Raises
        ValueError: If validation data has label values which were not seen
            in the training data.
    """
    # Get the data.
    (train_texts, train_labels), (val_texts, val_labels) = data

    # Verify that validation labels are in the same range as training labels.
    #num_classes = 4
    num_classes = get_num_classes(train_labels)
    unexpected_labels = [v for v in val_labels if v not in range(num_classes)]
    if len(unexpected_labels):
        raise ValueError('Unexpected label values found in the validation set:'
                         ' {unexpected_labels}. Please make sure that the '
                         'labels in the validation set are in the same range '
                         'as training labels.'.format(
                             unexpected_labels=unexpected_labels))

    # Vectorize texts.
    x_train, x_val = ngram_vectorize(train_texts, train_labels, val_texts)

    # Create model instance.
    print(x_train.shape)
    print(x_val.shape)
    model = mlp_model(  layers=layers,
                        units=units,
                        dropout_rate=dropout_rate,
                        input_shape=x_train.shape[1:],
                        num_classes=num_classes)

    # Compile model with learning parameters.
    if num_classes == 2:
        loss = 'binary_crossentropy'
    else:
        loss = 'sparse_categorical_crossentropy'
        #loss = 'categorical_crossentropy'

    optimizer = tf.keras.optimizers.Adam(lr=learning_rate)
    #optimizer = tf.keras.optimizers.SGD()
    #optimizer = tf.keras.optimizers.RMSprop()
    #optimizer = tf.keras.optimizers.Adamax()
    model.compile(optimizer=optimizer, loss=loss, metrics=['acc'])

    # Create callback for early stopping on validation loss. If the loss does
    # not decrease in two consecutive tries, stop training.
    callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)]

    # Train and validate model.
    history = model.fit(
            x_train,
            train_labels,
            epochs=epochs,
            callbacks=callbacks,
            validation_data=(x_val, val_labels),
            verbose=2,  # Logs once per epoch.
            batch_size=batch_size)

    # Print results.
    history = history.history
    print('Validation accuracy: {acc}, loss: {loss}'.format(
            acc=history['val_acc'][-1], loss=history['val_loss'][-1]))

    # Save model.
    # Creates a HDF5 file 'my_model.h5'
    model.save('MLPClassifier.h5')


from collections import OrderedDict
from rest_framework import serializers

from products.serializers import ProductSerializer
from .models import Sales

class SalesSerializer(serializers.ModelSerializer):
	active = serializers.BooleanField(default=True)
	product = ProductSerializer()

	class Meta:
		model = Sales
		fields = ('id','product','user','number','date','userid','location','active',)

	def to_representation(self, instance):
		data = super().to_representation(instance)
		if data['active']:
			return data

		return OrderedDict()


import cv2
import os
import face_recognition
import pyaudio
import speech_recognition as sr
from playsound import playsound
import time
import pyttsx3

 # --------------------------------Declaring Variables ------------------------
engine = pyttsx3.init()
engine.setProperty('rate',145)
knownfaces_names = []
knownfaces_encodingslist = []
location_for_frame= 0
encoding_for_frame = 0
knownfaces_locations = 0
match = []
img_counter = 0
TOLERANCE = 0.5
MODEL = "cnn"
Matchingsystem = True

# ---------------------------------Getting face encodings for each image in my knownfaces_jpegs list ----------------
cap= cv2.VideoCapture(0)
print ("camera started")

for img in os.listdir("C:/Users/noosu/Documents/python projects/PeopleIknow"):
	if img.endswith(".jpg"):
		knownface= face_recognition.load_image_file("C:/Users/noosu/Documents/python projects/PeopleIknow/" + img)
		knownface = cv2.cvtColor(knownface,cv2.COLOR_BGR2RGB)
		knownfaceencoding = face_recognition.face_encodings(knownface)[0]
		knownfaces_encodingslist.append(knownfaceencoding)
		name, ext = img.split('.')
		knownfaces_names.append(name)

print("encodings collected")

 # ----------------------------- Starting up the camera  ------------------------------------------ ---------

while True:
	ret,frame = cap.read()
	print("frame read")
	frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

	location_for_frame = face_recognition.face_locations(frame)
	encoding_for_frame = face_recognition.face_encodings(frame,location_for_frame)
	print("frame encoded")
	match.clear()
	for face_encoding, face_location in zip (encoding_for_frame,location_for_frame):
		comparison = face_recognition.compare_faces(knownfaces_encodingslist, face_encoding,TOLERANCE)
		if any(comparison):
			k= knownfaces_names[comparison.index(True)]
			match.append(k)
	print("done comparing")

	if len(location_for_frame) == 0 :
		print ("no one")

	else:
		if match:
			print ("match found :",match)
			seperator = " and "
			messagematchtrue = seperator.join(match) + " is at the door"
			Matchingsystem = True

		else:
			print ("no match")
			Matchingsystem = False
			messagematchfalse = "The person detected is not someone in your immediate family"

		engine.say("There is someone at the door")
		engine.runAndWait()
		w= sr.Recognizer()
		with sr.Microphone() as source:
			audio = w.listen(source)
			try:
				text1 = w.recognize_google(audio)
				print (text1)
				if text1 == "Who is it" or text1 == "who is it" or text1 == "Okay who is it" or text1 == "okay who is it" or text1 == "okay who's there" or text1 == "who"or text1 == "okay who":
					if Matchingsystem == True:
						engine.say(messagematchtrue)
						engine.runAndWait()
						time.sleep(25)
					elif Matchingsystem == False:
						engine.say(messagematchfalse)
						engine.say(" Do you want to save this face")
						engine.runAndWait()

						with sr.Microphone() as source:
							audio = w.listen(source)
							text4 = w.recognize_google(audio)
						if  text4 == "yes" or text4 == "Yes" or text4== "ya" or text4 == "Ya" or text4 == "okay":
							engine.say("Okay shall I take the image")
							engine.runAndWait()
							with sr.Microphone() as source:
								audio = w.listen(source)
								text3 = w.recognize_google(audio)
								if text3 == "yes" or text3 == "Yes" or text3== "ya" or text3 == "Ya" or text3 == "okay":
									engine.say("Okay what is the person's name")
									engine.runAndWait()
									with sr.Microphone() as source:
										audio = w.listen(source)
										text2 = w.recognize_google(audio)
										print ("saving image")
										frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
										img = "{}.jpg".format(text2)
										path = "C:/Users/noosu/Documents/python projects/PeopleIknow"
										cv2.imwrite(os.path.join(path , img), frame)

								time.sleep(25)
						else:
							engine.say("Okay. I'll go back to my routine checking")
							engine.runAndWait()
							time.sleep(25)

				elif text1 == "help" or text1 == "I do not know what to do" or text1 == "what are the instructions" or text1 == "what do I do" or text1 == "how does this work" or text1 == "what do I have to do" or text1 == "can you help me" :
					engine.say("Welcome to the instruction section. I am a J Jcube. A wifi camera. I am here to assist you with detecting the people who are outside your door. Let’s first start by reviewing the basic commands. When I detect someone, I will let you know by saying there is someone at the door. To know who is outside, all you have to do is say the command “who is it”.  Second. If I detect someone you do not know, I will tell you that the person outside is not someone in your immediate family. I will also ask you if you would like me to remember that face. You can either accept or deny. I hope I didn’t bore you. Don’t worry we are almost done. If you need any help and want to revisit the instructions section, you just have to say “I do not know what to do” or say “help”. Finally, if I don’t see anyone outside, I’ll just remain quiet.")
					engine.runAndWait()
				elif text1 == "Stop" or text1 == "stop":
					print("exiting")
					break

			except:
				print("ERROR")
				time.sleep(5)

cv2.destroyAllWindows()
cap.release()


from os import environ, path
from pocketsphinx.pocketsphinx import *
from sphinxbase.sphinxbase import *

MODEL_DIR = "pocketsphinx/model"
DATA_DIR = "pocketsphinx/test/data"

config = Decoder.default_config()
config.set_string('-hmm', path.join(MODEL_DIR, 'hmm/en-us/hub4wsj_sc_8k'))
config.set_string('-lm', path.join(MODEL_DIR, 'lm/en-us/hub4.5000.DMP'))
config.set_string('-dict', path.join(MODEL_DIR, 'lm/en-us/cmu07a.dic'))
decoder = Decoder(config)
decoder.start_utt()
stream = open(path.join(DATA_DIR, 'goforward.raw'), 'rb')
while True:
    buf = stream.read(1024)
    if buf:
        decoder.process_raw(buf, False, False)
    else:
        break
decoder.end_utt()
print ('Best hypothesis segments: ', [seg.word for seg in decoder.seg()])


N = int(input())
budget = list(map(int,input().split()))
totalBudget = int(input())
totalAsk = sum(budget)
if totalBudget >= totalAsk:
    print(max(budget))
else:
    start,end = 0,max(budget)
    while start <= end:
        tmpBudget = totalBudget
        mid = (start + end) // 2
        for b in budget:
            if b <= mid:
                tmpBudget -= b
            else:
                tmpBudget -= mid
        if tmpBudget < 0:
            end = mid - 1
        else:
            start = mid + 1
    print(end)


import json
import math
from itertools import groupby
import pygal

# 将数据加载到一个列表中
filename = 'btc_close_2017_requests.json'
with open(filename) as f:
    btc_data = json.load(f)

# 创建5个列表，分别存储日期和收盘价
dates = []
months = []
weeks = []
weekdays = []
close = []
# 每一天信息
for btc_dict in btc_data:
    dates.append(btc_dict['date'])
    months.append(int(btc_dict['month']))
    weeks.append(int(btc_dict['week']))
    weekdays.append(btc_dict['weekday'])
    close.append(int(float(btc_dict['close'])))

# 绘制折线图
line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
line_chart.title = '收盘价（¥）'
line_chart.x_labels = dates
N = 20  # x 轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
line_chart.add('收盘价', close)
line_chart.render_to_file('收盘价折线图.svg')

line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
line_chart.title = '收盘价对数变换（¥）：'
line_chart.x_labels = dates
N = 20
line_chart.x_labels_major = dates[::20]
close_log = [math.log10(_) for _ in close]
line_chart.add('log收盘价', close_log)
line_chart.render_to_file('收盘价对数变换折线图.svg')

def draw_line(x_date, y_date, title, y_legend):
    xy_map = []
    for key, group in groupby(sorted(zip(x_date, y_date)), key=lambda _: _[0]):
        y_list = [v for _, v in group]
        xy_map.append([key, sum(y_list) / len(y_list)])

    x_unique, y_mean = [*zip(*xy_map)]
    chart = pygal.Line()
    chart.title = title
    chart.x_labels = x_unique
    chart.add(y_legend, y_mean)
    chart.render_to_file(title + '.svg')
    return chart

idx_month = dates.index('2017-12-01')
draw_line(months[:idx_month], close[:idx_month], '收盘价月日均值', '月日均值')

idx_week = dates.index('2017-12-11')
line_chart_week = draw_line(
    weeks[1:idx_week], close[1:idx_week], '收盘价周日均值', '周日均值')

wd = ['Monday', 'Tuesday', 'Wednesday',
      'Thursday', 'Friday', 'Saturday', 'Sunday']
weekdays_int = [wd.index(w) + 1 for w in weekdays[1:idx_week]]
line_chart_weekday = draw_line(
    weekdays_int, close[1:idx_week], '收盘价星期均值', '星期均值')

line_chart_weekday.x_labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
line_chart_weekday.render_to_file('收盘价星期均值.svg')

with open('Dashboard.html', 'w', encoding='utf8') as html_file:
    html_file.write(
        '<title>Dashboard</title><meta charset="utf-8">\n')
    for svg in ['收盘价折线图.svg', '收盘价对数变换折线图.svg', '收盘价月日均值.svg', '收盘价周日均值.svg', '收盘价星期均值.svg']:
        html_file.write(
            '    <object type="image/svg+xml" data="{0}" height=500></object>\n'.format(svg))
    html_file.write('')


import sys
import os

PREFIX = "/"

def searchFile(root, result):
    for file in os.listdir(root):
        fullpath = os.path.join(root, file)

        if os.path.isdir(fullpath):
            searchFile(fullpath, result)

        if file.split('.')[-1] == "ttf":
            result.append(fullpath)
    return result

def main():
    root = sys.argv[1]
    root = os.path.join(root, "resource")
    files = searchFile(root, [])
    qrc = os.path.join(root, r"fontResource.qrc")
    fw = open(qrc, 'w')
    fw.write('<RCC>\n')
    fw.write('  <qresource prefix="%s">\n' % PREFIX)
    for file in files:
        print(file)
        file = file.replace(root, './')
        fw.write('    <file>%s</file>\n' % file)
    fw.write('  </qresource>\n')
    fw.write('</RCC>\n')
    print(fw)

if __name__ == '__main__':
    main()