# -*- coding: utf-8 -*-
import re
import lxml
import json
import traceback
import scrapy
from datetime import datetime
from taobao_suk import items
from scrapy_redis.spiders import RedisSpider

class GoodsGrab(RedisSpider):
    name = "goods_grab"
    redis_key = 'dummy_goods_grab:start_urls'
    allowed_domains = ["taobao.com", "tmall.hk", "tmall.com"]

    custom_settings = {
        'SCHEDULER': 'scrapy_redis.scheduler.Scheduler',
        'SCHEDULER_PERSIST': True,
        'SCHEDULER_QUEUE_CLASS': 'scrapy_redis.queue.SpiderPriorityQueue',
        'DUPEFILTER_CLASS': 'taobao_suk.my_dupefilter.RFPDupeFilter',
        # 'ITEM_PIPELINES': {
        #                     'scrapy_redis.pipelines.RedisPipeline': 300,
        #                     }

    }

    def parse(self, response):

        if 'taobao' in response.url:
            # 淘宝
            url_, goods_info = self.toaobao_goods_pag(response)
            headers = {'accept': '*/*',
                         'accept-encoding': 'gzip, deflate, br',
                         'accept-language': 'zh-CN,zh;q=0.8',
                         'authority': 'detailskip.taobao.com',
                         # 'referer': 'https://item.taobao.com/item.htm?spm=a219r.lm5644.14.11.70b3a555eCfx0A&id=541986659658&ns=1&abbucket=18',
                         'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
            # self.logger.debug(goods_info)
            yield scrapy.Request(url_, callback=self.get_sell, meta={'data': goods_info}, headers=headers, priority=10)

        elif 'tmall' in response.url:
            # 天猫
            goods_info = self.tianmao_m_pag(response)
            yield items.TaobaoSukItem(detail={'goods_info': goods_info})

        else:
            self.logger.error('未知url：{}'.format(response.url))

    def toaobao_goods_pag(self, response):

        xpath_item = {
            'shop_name': '//div[@class="tb-shop-name"]//a/text()',  # 店铺名称
            'name': '//h3[@class="tb-main-title"]/text()',  # 宝贝名称
            'original_price': '//strong[@id="J_StrPrice"]/em[@class="tb-rmb-num"]/text()',  # 原价

            'market_time': '//ul[@class="attributes-list"]//li[contains(text(),"上市时间")]/@title',  # i上市时间
            'category': '//ul[@class="attributes-list"]//li[contains(text(),"面膜分类")]/@title',  # 面膜分类
            'suitable_skin': '//ul[@class="attributes-list"]//li[contains(text(),"适合肤质")]/@title',  # 适合肤质
            'effect': '//ul[@class="attributes-list"]//li[contains(text(),"功效")]/@title',  # 功效
            'shelf_life': '//ul[@class="attributes-list"]//li[contains(text(),"保质期")]/@title',  # 保质期

            'goods_name': '//ul[@class="attributes-list"]//li[contains(text(),"品名")]/@title',  # 品名
            'brand': '//ul[@class="attributes-list"]//li[contains(text(),"品牌")]/@title',  # 品牌
            'origin_place': '//ul[@class="attributes-list"]//li[contains(text(),"产地")]/@title',  # 产地
            'color_type': '//ul[@class="attributes-list"]//li[contains(text(),"颜色分类")]/@title',  # 颜色分类
            'rule_type': '//ul[@class="attributes-list"]//li[contains(text(),"规格类型")]/@title',  # 规格类型
            'month': '//ul[@class="attributes-list"]//li[contains(text(),"月份")]/@title',  # 月份
            'is_special': '//ul[@class="attributes-list"]//li[contains(text(),"是否为特殊用途化妆品")]/@title',
            'use_date_range': '//ul[@class="attributes-list"]//li[contains(text(),"限期使用日期范围")]/@title',
            'net_content': '//ul[@class="attributes-list"]//li[contains(text(),"化妆品净含量")]/@title',
            'single_product': '//ul[@class="attributes-list"]//li[contains(text(),"面膜单品")]/@title',
        }
        tree = lxml.etree.HTML(response.text)
        result = {}
        for key in xpath_item:
            result[key] = ''.join(tree.xpath(xpath_item[key])).strip()

        url = "https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm?itemId={}&modules=dynStock," \
              "qrcode,viewer,price,duty,xmpPromotion,delivery,activity,fqg,zjys,couponActivity,soldQuantity,original" \
              "Price,tradeContract"

        goods_id = re.search(r'id=(\d*)', response.url).group(1)
        result['goods_id'] = int(goods_id)
        url_ = url.format(goods_id)

        return url_, result

    def get_sell(self, response):
        item = {}
        text = response.text
        data = json.loads(text.strip('onSibRequestSuccess(').strip(');')).get('data', {})
        item['price'] = data.get('promotion', {}).get('promoData', {}).get('def', [{}])[0].get('price', 0) \
                        or data.get('price', 0)

        item['month_sold_quantity'] = data.get('soldQuantity', {}).get('confirmGoodsCount', 0)  # 月销量
        item['inventory'] = data.get('dynStock', {}).get('sellableQuantity', 0)  # 库存
        item['deliveryAddress'] = data.get('deliveryFee', {}).get('data', {}).get('sendCity', '')  # 发货地

        price = str(item['price']).split('-')
        if len(price) >= 2:
            # 30天销售额
            item['month_sold_amount'] = str(item['month_sold_quantity'] * float(price[0])) + '-' + \
                                  str(item['month_sold_quantity'] * float(price[-1]))
        else:
            item['month_sold_amount'] = item['month_sold_quantity'] * float(price[0])

        base_info = response.meta['data']
        base_info.update(item)
        base_info['shop_type'] = '淘宝'
        base_info['modified'] = datetime.now()
        now_today = datetime.today()
        base_info['date'] = datetime.fromordinal(now_today.toordinal())

        price = str(base_info['price']).split('-')
        if len(price) >= 2:
            # 30天销售额
            base_info['price_min'] = float(price[0])
            base_info['price_max'] = float(price[-1])
        else:
            base_info['price_min'] = base_info['price_max'] = float(price[0])

        # add original_price_min original_price_max
        original_price = str(base_info['original_price']).split('-')

        if len(original_price) >= 2:
            base_info['original_price_min'] = float(original_price[0])
            base_info['original_price_max'] = float(original_price[-1])
        else:
            try:
                base_info['original_price_min'] = base_info['original_price_max'] = float(original_price[0])
            except:
                self.logger.error(traceback.format_exc())
                self.logger.error(base_info['price'])

        yield items.TaobaoSukItem(detail={'goods_info': base_info})

    def tianmao_m_pag(self, response):
        xpath_item = {
            'shop_name': '//div[@class="shop-name"]/text()',  # 店铺名称
            'name': '//div[@class="main"]/text()',  # 宝贝名称
            'original_price': '//span[@class="price"]/text()',  # 原价格
        }
        tree = lxml.etree.HTML(response.text)

        item = {'category': '',
                'goods_name': '',
                'color_type': '',
                'rule_type': '',
                'is_special': '',
                'use_date_range': '',
                'net_content': '',
                'single_product': ''}
        # category  goods_name color_type rule_type is_special use_date_range net_content single_product

        for key in xpath_item:
            item[key] = ''.join(tree.xpath(xpath_item[key])).replace('\n', '').strip()

        if not item['name']:
            item['name'] = ''.join(tree.xpath('//div[@class="main"]/h1/text()'))

        if not item['original_price']:
            item['original_price'] = ''.join(tree.xpath('//span[@class="mui-price-integer"]/text()'))

        if not item['shop_name']:
            item['shop_name'] = ''.join(tree.xpath('//div[@class="shop-t"]/text()'))

        try:
            item['goods_id'] = int(re.search(r'id=(\d*)', response.url).group(1))
        except Exception as e:
            self.logger.error('tianmao get goods id error,{}:{}'.format(response.url, e))

        products = ''.join(tree.xpath('//div[@class="mui-standardItemProps mdv-standardItemProps"]/@mdv-cfg'))
        try:
            props = json.loads(products).get('data', {}).get('props', [])
        except Exception as e:
            props = []
            self.logger.error(e)

        key_item = {
            '品牌': 'brand',
            '产地': 'origin_place',
            '上市时间': 'market_time',
            '功效': 'effect',
            '月份': 'month',
            '保质期': 'shelf_life',
            '适合肤质': 'suitable_skin'}
        for data in props:
            key = data.get('ptext', '')
            if key in key_item:
                item[key_item[key]] = ''.join(data.get('vtexts', ''))
        if not props:
            for k, v in key_item.items():
                item[v] = ''

        text = response.text

        item['price'] = ''
        item['month_sold_quantity'] = int(self.regular_expression_match(r'"sellCount":(\d*?)\,', text, 0))  # 销量
        item['deliveryAddress'] = self.regular_expression_match(r'"deliveryAddress":(.*?),', text, '')

        item['rate_counts'] = self.regular_expression_match(r'"commentCount":(\d+?),', text, 0)  # 累计评价
        item['inventory'] = int(self.regular_expression_match(r'"totalQuantity":(\d*?)\,', text, '0'))  # 库存

        text = tree.xpath('//script[contains(text(), "_DATA_Mdskip")]/text()')
        text = text[0] if text else '{}'
        json_text = text.replace('var _DATA_Mdskip =  ', '').replace('\n', '').strip()

        # json_text = self.regular_expression_match(r'var _DATA_Mdskip =([\s\S]*) </script>', text, '{}')
        # if not json_text:
        #     json_text = self.regular_expression_match(r'var _DATA_Mdskip =\s({.*?})\s</script>', text, '{}')
        if not item['inventory']:
            item['inventory'] = self.regular_expression_match(r'"quantity":(\d+)', json_text, 0)
        try:
            json_item = json.loads(json_text)
        except Exception as e:
            self.logger.error(e)
            json_item = {}

        if 'defaultModel' in json_item:
            item['price'] = json_item.get('defaultModel', {}).get('newJhsDO', {}).get('activityPrice', 0)
            if not item['price']:
                item['price'] = json_item.get('defaultModel', {}).get('itemPriceResultDO', {}).get('priceInfo', {}).get('def', {}).get('promotionList', [{}])[0].get('price', 0)

        if 'delivery' in json_item:
            if not item['deliveryAddress']:
                item['deliveryAddress'] = json_item.get('delivery', {}).get('from', '')

        if 'price' in json_item:
            if not item['original_price']:
                item['original_price'] = json_item.get('price').get('extraPrices', [{}])[0].get('priceText', '')
            item['price'] = json_item.get('price').get('price', {}).get('priceText', 0)

        if not item['price']:
            item['price'] = self.regular_expression_match(r'(.*?)', text, 0) # 价格

        self.logger.info('tianmao regular match: {}'.format(item))
        price = str(item['price']).split('-')
        if len(price) >= 2:
            # 30天销售额
            item['month_sold_amount'] = str(item['month_sold_quantity'] * float(price[0])) + '-' + str(item['month_sold_quantity'] * float(price[-1]))
            item['price_min'] = float(price[0])
            item['price_max'] = float(price[-1])
        else:
            item['month_sold_amount'] = item['month_sold_quantity'] * float(price[0])
            item['price_min'] = item['price_max'] = float(price[0])

        # add original_price_min original_price_max
        original_price = str(item['original_price']).split('-')

        if len(original_price) >= 2:
            item['original_price_min'] = float(original_price[0])
            item['original_price_max'] = float(original_price[-1])
        else:
            item['original_price_min'] = item['original_price_max'] = float(original_price[0])

        item['shop_type'] = '天猫'
        item['modified'] = datetime.now()
        now_today = datetime.today()
        item['date'] = datetime.fromordinal(now_today.toordinal())
        return item

    def regular_expression_match(self, regular, text, default=''):
        try:
            result = re.search(regular, text)
            result = result.group(1) if result else default
            return result
        except Exception as e:
            self.logger.error(e)
            return default


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

import tensorflow as tf
import numpy as np

# READING PARAM FILES FROM PRE-TRAINED POTSDAM NETWORK
def load_param(name):
    path='mat2numpy/'+name+'.npy'
    out=np.load(path)
    return out
# Layer 1 Parameters (convolutional, 7x7, 5->64)
f1=load_param('l1f')
b1=load_param('l1b')
# Layer 2 Parameters (batch normalization)
m2=load_param('l2m')
b2=load_param('l2b')
x2=load_param('l2x')
# Layer 6 Parameters (convolutional, 5x5, 64->64)
f6=load_param('l6f')
b6=load_param('l6b')
# Layer 7 Parameters (batch normalization)
m7=load_param('l7m')
b7=load_param('l7b')
x7=load_param('l7x')
# Layer 11 Parameters (convolutional, 3x3, 64->128)
f11=load_param('l11f')
b11=load_param('l11b')
# Layer 12 Parameters (batch normalization)
m12=load_param('l12m')
b12=load_param('l12b')
x12=load_param('l12x')
# Layer 16 Parameters (convolutional, 3x3, 128->256)
f16=load_param('l16f')
b16=load_param('l16b')
# Layer 17 Parameters (batch normalization)
m17=load_param('l17m')
b17=load_param('l17b')
x17=load_param('l17x')
# Layer 20 Parameters (deconvolutional, 3x3, 256->512, [2,2] upsampling)
f20=load_param('l20f')
b20=load_param('l20b')
# Layer 21 Parameters (batch normalization)
m21=load_param('l21m')
b21=load_param('l21b')
x21=load_param('l21x')
# Layer 24 Parameters (deconvolutional, 3x3, 512->512, [2,2] upsampling)
f24=load_param('l24f')
b24=load_param('l24b')
# Layer 25 Parameters (batch normalization)
m25=load_param('l25m')
b25=load_param('l25b')
x25=load_param('l25x')
# Layer 28 Parameters (deconvolutional, 3x3, 512->512, [2,2] upsampling)
f28=load_param('l28f')
b28=load_param('l28b')
# Layer 29 Parameters (batch normalization)
m29=load_param('l29m')
b29=load_param('l29b')
x29=load_param('l29x')
# Layer 32 Parameters (convolutional, 1x1, 512->6)
f32=load_param('l32f')
b32=load_param('l32b')

# CNN MODEL
def conv_net(images):

    # input image should be reshaped

    # I need to know, respectively, the batch size and number of channels of the input

    #images = tf.reshape(images, shape=[batch_size, 65, 65, channels])

    # 1st layer: convolution 7x7 5->64

    conv1=tf.nn.conv2d(images,f1,strides=[1,1,1,1],padding='SAME')
    conv1=tf.nn.bias_add(conv1,b1)

    # 2nd layer: batch normalization
    banorm1=tf.nn.batch_normalization(conv1,m2,x2,b2,variance_epsilon=1.0e-04)

    # 3rd layer: ReLU
    # UNSURE if leaky_relu preserves the input tensor's shape of [batch,heigth,width,channels]
    relu1=tf.nn.leaky_relu(banorm1,alpha=0.2,name=None)
#
    # 4th layer: pooling
    pool1=tf.nn.max_pool(relu1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],padding='SAME')

#   UNSURE if I should implement the dropout

#    # 5th layer: drop out
#    # Probability to keep each value is 0.75
#    # keep_prob array must have same size as input
#    keep_prob=np.copy(pool1)
#    keep_prob.fill(1)
#    keep_prob=0.75*keep_prob
#
#    pool1=tf.nn.dropout(pool1,keep_prob)

    # 6th layer: convolution 5x5 64->64

    conv2=tf.nn.conv2d(pool1,f6,strides=[1,1,1,1],padding='SAME')
    conv2=tf.nn.bias_add(conv2,b6)

    # 7th layer: batch normalization
    banorm2=tf.nn.batch_normalization(conv2,m7,x7,b7,variance_epsilon=1.0e-04)

    # 8th layer: ReLU
    relu2=tf.nn.leaky_relu(banorm2,alpha=0.1,name=None)

    # 9th layer: pooling
    pool2=tf.nn.max_pool(relu2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],padding='SAME')

    #  UNSURE if I should include the dropout
    # for implementation, see layer 5

    # 11th layer: convolution 3x3 64->128
    conv3=tf.nn.conv2d(pool2,f11,strides=[1,1,1,1],padding='SAME')
    conv3=tf.nn.bias_add(conv3,b11)

    # 12th layer: batch normalization
    banorm3=tf.nn.batch_normalization(conv3,m12,x12,b12,variance_epsilon=1.0e-04)

    # 13th layer: ReLU
    relu3=tf.nn.leaky_relu(banorm3,alpha=0.1,name=None)

    # 14th layer: pooling
    pool3=tf.nn.max_pool(relu3, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],padding='SAME')

    #  UNSURE if I should include the dropout
    # for implementation, see layer 5

    # 16th layer: convolution 3x3 128->256
    conv4=tf.nn.conv2d(pool3,f16,strides=[1,1,1,1],padding='SAME')
    conv4=tf.nn.bias_add(conv4,b16)

    # 17th layer: batch normalization
    banorm4=tf.nn.batch_normalization(conv4,m17,x17,b17,variance_epsilon=1.0e-04)

    # 18th layer: ReLU
    relu4=tf.nn.leaky_relu(banorm4,alpha=0.1,name=None)

    # RECAP:
    # at this point I should have 256 feature maps of size 1/8*initial patch size (which is 65x65)-->it should be 9x9
    # (due to the 3 maxpooling layers with stride 2)

    #  UNSURE if I should include the dropout
    # for implementation, see layer 5

    # 20th layer: deconvolution 3x3 256->512
    deconv_heigth = 2*relu4.shape[1] #since I have an upsampling of factor 2
    deconv_width  = 2*relu4.shape[2]
    # I need to know the batch size, here I set it to -1 as a placeholder
    convt5=tf.nn.conv2d_transpose(relu4,f20,[-1,deconv_heigth,deconv_width,512],strides=[1,1,1,1],padding="SAME")
    convt5=tf.nn.bias_add(convt5,b20)

    # 21st layer: batch normalization
    banorm5=tf.nn.batch_normalization(convt5,m21,x21,b21,variance_epsilon=1.0e-04)

    # 22nd layer: ReLU
    relu5=tf.nn.leaky_relu(banorm5,alpha=0.1,name=None)

    #  UNSURE if I should include the dropout
    # for implementation, see layer 5

    # 24th layer: deconvolution 3x3 512->512
    deconv_heigth = 2*deconv_heigth #since I have an upsampling of factor 2
    deconv_width  = 2*deconv_width
    convt6=tf.nn.conv2d_transpose(relu5,f24,[-1,deconv_heigth,deconv_width,512],strides=[1,1,1,1],padding="SAME")
    convt6=tf.nn.bias_add(convt6,b24)

    # 25th layer: batch normalization
    banorm6=tf.nn.batch_normalization(convt6,m25,x25,b25,variance_epsilon=1.0e-04)

    # 26th layer: ReLU
    relu6=tf.nn.leaky_relu(banorm6,alpha=0.1,name=None)

    #  UNSURE if I should include the dropout
    # for implementation, see layer 5

    # 28th layer: deconvolution 3x3 512->512
    deconv_heigth = 2*deconv_heigth #since I have an upsampling of factor 2
    deconv_width  = 2*deconv_width
    convt7=tf.nn.conv2d_transpose(relu6,f28,[-1,deconv_heigth,deconv_width,512],strides=[1,1,1,1],padding="SAME")
    convt7=tf.nn.bias_add(convt7,b28)

    # 29th layer: batch normalization
    banorm7=tf.nn.batch_normalization(convt7,m29,x29,b29,variance_epsilon=1.0e-04)

    #30th layer: ReLU
    relu7=tf.nn.leaky_relu(banorm7,alpha=0.1,name=None)

    #  UNSURE if I should include the dropout
    # for implementation, see layer 5

    #32nd layer: convolution 1x1 512->6
    conv8=tf.nn.conv2d(relu7,f32,strides=[1,1,1,1],padding='SAME')
    conv8=tf.nn.bias_add(conv8,b32)

    # RECAP: I should now have in output a tensor of shape [batch_size,65,65,6]
    # 6 is the number of classes, and the vector represents a 6-dimension matrix of class scores

# I still need to download the dataset in order to give something as input and get the predictions

#logits=conv_net(images)
#prediction=tf.nn.softmax(logits)


from decimal import Decimal, getcontext
import os

# Set the precision of decimal arithmetic.
PRECISION = 10000
getcontext().prec = PRECISION

# Set the size of the cmd window.
if os.name == 'nt':
    os.system("mode con cols=200 lines=53")

print(f'Current precision: {PRECISION} digit(s)')
print('More terms would have a more accurate result.')

num_terms = int(input("Input the number of terms to use in the approximation: "))

exponent = Decimal('1') / Decimal('2')
approximation = Decimal('0')  # Initial approximation.
triangle_area = Decimal('3') ** Decimal('0.5') / Decimal('8')  # Area of a 30-60-90 triangle in the unit circle.
binomial_coeff = Decimal('2') / Decimal('3')  # Initial value for binomial coefficient.
factorial = Decimal('1')  # Initial value for factorial.
prev_pi = Decimal('0')

for term_index in range(num_terms):
    # Calculate the next term in the approximation using the binomial theorem.
    binomial_coeff *= exponent - term_index + 1

    # Update the factorial for the term.
    if term_index != 0:
        factorial *= term_index

    # Determine the sign of the term.
    if term_index % 2 == 0:
        term_sign = 1
    else:
        term_sign = -1

    # Calculate the denominator of the term, which is an odd number.
    term_denominator = 2 * term_index + 1

    # Calculate the final value of the term and add it to the approximation.
    term_value = term_sign * binomial_coeff / (factorial * term_denominator * 2 ** term_denominator)
    approximation += term_value

    # Print the current approximation to pi.
    pi = Decimal('12') * (approximation - triangle_area)

    if pi == prev_pi:
        print('\nReached same value of pi as previous iteration. Terminating loop.')
        break

    print(f'\r{term_index}  {pi}', end='', flush=True)

    prev_pi = pi

# Pause the program before exiting.
input('Press Enter to exit...')


# Only Red color detection

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # Red color
    low_red = np.array([161, 155, 84]) # lowest hue would be - 161,155,84( how do i found this i tested before and found this)
    high_red = np.array([179, 255, 255])
    #mask = cv2.inRange(hsv_frame, low_red, high_red)

    red_mask = cv2.inRange(hsv_frame, low_red, high_red) #we create maskk on hsv frame and then low red or high red
    red = cv2.bitwise_and(frame, frame, mask=red_mask)

    cv2.imshow("Frame", frame)
    #cv2.imshow('Red mask', mask)
    cv2.imshow('Red', red)

    key = cv2.waitKey(1)
    if key ==27:
        break


import time
from typing import Optional, List
import warnings

# IBM Qiskit imports
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit_ibm_provider.job.exceptions import (
    IBMJobApiError,
    IBMJobInvalidStateError,
    IBMJobFailureError,
    IBMJobTimeoutError,
)
from qiskit.circuit import Parameter

from .devices import DeviceQiskit
from .gates_qiskit import QiskitGateApplicator
from openqaoa.backends.basebackend import (
    QAOABaseBackendShotBased,
    QAOABaseBackendCloud,
    QAOABaseBackendParametric,
)
from openqaoa.qaoa_components import QAOADescriptor
from openqaoa.qaoa_components.variational_parameters.variational_baseparams import (
    QAOAVariationalBaseParams,
)
from openqaoa.utilities import flip_counts

class QAOAQiskitQPUBackend(
    QAOABaseBackendParametric, QAOABaseBackendCloud, QAOABaseBackendShotBased
):
    """
    A QAOA simulator as well as for real QPU using qiskit as the backend

    Parameters
    ----------
    device: `DeviceQiskit`
        An object of the class ``DeviceQiskit`` which contains the credentials
        for accessing the QPU via cloud and the name of the device.
    qaoa_descriptor: `QAOADescriptor`
        An object of the class ``QAOADescriptor`` which contains information on
        circuit construction and depth of the circuit.
    n_shots: `int`
        The number of shots to be taken for each circuit.
    prepend_state: `QuantumCircuit`
        The state prepended to the circuit.
    append_state: `QuantumCircuit`
        The state appended to the circuit.
    init_hadamard: `bool`
        Whether to apply a Hadamard gate to the beginning of the
        QAOA part of the circuit.
    cvar_alpha: `float`
        The value of alpha for the CVaR method.
    """

    def __init__(
        self,
        qaoa_descriptor: QAOADescriptor,
        device: DeviceQiskit,
        n_shots: int,
        prepend_state: Optional[QuantumCircuit],
        append_state: Optional[QuantumCircuit],
        init_hadamard: bool,
        initial_qubit_mapping: Optional[List[int]] = None,
        qiskit_optimization_level: int = 1,
        cvar_alpha: float = 1,
    ):
        QAOABaseBackendShotBased.__init__(
            self,
            qaoa_descriptor,
            n_shots,
            prepend_state,
            append_state,
            init_hadamard,
            cvar_alpha,
        )
        QAOABaseBackendCloud.__init__(self, device)

        self.qureg = QuantumRegister(self.n_qubits)
        self.problem_reg = self.qureg[0 : self.problem_qubits]
        self.creg = ClassicalRegister(len(self.problem_reg))

        if qiskit_optimization_level in [0, 1, 2, 3]:
            self.qiskit_optimziation_level = qiskit_optimization_level
        else:
            raise ValueError(
                f"qiskit_optimization_level cannot be {qiskit_optimization_level}. Choose between 0 to 3"
            )
        self.gate_applicator = QiskitGateApplicator()

        if self.initial_qubit_mapping is None:
            self.initial_qubit_mapping = (
                initial_qubit_mapping
                if initial_qubit_mapping is not None
                else list(range(self.n_qubits))
            )
        else:
            if isinstance(initial_qubit_mapping, list):
                warnings.warn(
                    "Ignoring the initial_qubit_mapping since the routing algorithm chose one"
                )

        if self.prepend_state:
            assert self.n_qubits >= len(prepend_state.qubits), (
                "Cannot attach a bigger circuit" "to the QAOA routine"
            )

        # if self.device.provider_connected and self.device.qpu_connected:
        #     self.backend_qpu = self.device.backend_device
        if self.device.provider_connected and self.device.qpu_connected in [
            False,
            None,
        ]:
            raise Exception(
                "Connection to {} was made. Error connecting to the specified backend.".format(
                    self.device.device_location.upper()
                )
            )

        elif not (self.device.provider_connected and self.device.qpu_connected):
            raise Exception(
                "Error connecting to {}.".format(self.device.device_location.upper())
            )

        if self.device.n_qubits < self.n_qubits:
            raise Exception(
                "There are lesser qubits on the device than the number of qubits required for the circuit."
            )
        # For parametric circuits
        self.parametric_circuit = self.parametric_qaoa_circuit

    def qaoa_circuit(self, params: QAOAVariationalBaseParams) -> QuantumCircuit:
        """
        The final QAOA circuit to be executed on the QPU.

        Parameters
        ----------
        params: `QAOAVariationalBaseParams`

        Returns
        -------
        qaoa_circuit: `QuantumCircuit`
            The final QAOA circuit after binding angles from variational parameters.
        """
        angles_list = self.obtain_angles_for_pauli_list(self.abstract_circuit, params)
        memory_map = dict(zip(self.qiskit_parameter_list, angles_list))
        circuit_with_angles = self.parametric_circuit.bind_parameters(memory_map)

        if self.append_state:
            circuit_with_angles = circuit_with_angles.compose(self.append_state)

        # only measure the problem qubits
        if self.final_mapping is None:
            circuit_with_angles.measure(self.problem_reg, self.creg)
        else:
            for idx, qubit in enumerate(self.final_mapping[0 : len(self.problem_reg)]):
                cbit = self.creg[idx]
                circuit_with_angles.measure(qubit, cbit)

        if self.qaoa_descriptor.routed is True:
            transpiled_circuit = transpile(
                circuit_with_angles,
                self.device.backend_device,
                initial_layout=self.initial_qubit_mapping,
                optimization_level=self.qiskit_optimziation_level,
                routing_method="none",
            )
        else:
            transpiled_circuit = transpile(
                circuit_with_angles,
                self.device.backend_device,
                initial_layout=self.initial_qubit_mapping,
                optimization_level=self.qiskit_optimziation_level,
            )

        return transpiled_circuit

    @property
    def parametric_qaoa_circuit(self) -> QuantumCircuit:
        """
        Creates a parametric QAOA circuit, given the qubit pairs, single qubits with biases,
        and a set of circuit angles. Note that this function does not actually run
        the circuit. To do this, you will need to subsequently execute the command self.eng.flush().

        Parameters
        ----------
            params:
                Object of type QAOAVariationalBaseParams
        """
        # self.reset_circuit()
        parametric_circuit = QuantumCircuit(self.qureg, self.creg)

        if self.prepend_state:
            parametric_circuit = parametric_circuit.compose(self.prepend_state)
        # Initial state is all |+>
        if self.init_hadamard:
            parametric_circuit.h(self.problem_reg)

        self.qiskit_parameter_list = []
        for each_gate in self.abstract_circuit:
            # if gate is of type mixer or cost gate, assign parameter to it
            if each_gate.gate_label.type.value in ["MIXER", "COST"]:
                angle_param = Parameter(each_gate.gate_label.__repr__())
                self.qiskit_parameter_list.append(angle_param)
                each_gate.angle_value = angle_param
            decomposition = each_gate.decomposition("standard")
            # using the list above, construct the circuit
            for each_tuple in decomposition:
                gate = each_tuple[0](self.gate_applicator, *each_tuple[1])
                gate.apply_gate(parametric_circuit)

        return parametric_circuit

    def get_counts(self, params: QAOAVariationalBaseParams, n_shots=None) -> dict:
        """
        Execute the circuit and obtain the counts

        Parameters
        ----------
        params: QAOAVariationalBaseParams
            The QAOA parameters - an object of one of the parameter classes, containing
            variable parameters.
        n_shots: int
            The number of times to run the circuit. If None, n_shots is set to the default: self.n_shots

        Returns
        -------
            A dictionary with the bitstring as the key and the number of counts
            as its value.
        """

        n_shots = self.n_shots if n_shots is None else n_shots

        circuit = self.qaoa_circuit(params)

        job_state = False
        no_of_job_retries = 0
        max_job_retries = 5

        while job_state is False:
            # initial_layout only passed if not azure device
            # if type(self.device).__name__ == "DeviceAzure":
            # job = self.backend_qpu.run(circuit, **input_items)
            job = self.device.backend_device.run(circuit, shots=n_shots)

            api_contact = False
            no_of_api_retries = 0
            max_api_retries = 5

            while api_contact is False:
                try:
                    self.job_id = job.job_id()
                    counts = job.result().get_counts()
                    api_contact = True
                    job_state = True
                except (IBMJobApiError, IBMJobTimeoutError):
                    print("There was an error when trying to contact the IBMQ API.")
                    job_state = True
                    no_of_api_retries += 1
                    time.sleep(5)
                except (IBMJobFailureError, IBMJobInvalidStateError):
                    print("There was an error with the state of the Job in IBMQ.")
                    no_of_job_retries += 1
                    break

                if no_of_api_retries >= max_api_retries:
                    raise ConnectionError(
                        "Number of API Retries exceeded Maximum allowed."
                    )

            if no_of_job_retries >= max_job_retries:
                raise ConnectionError("An Error Occurred with the Job(s) sent to IBMQ.")

        # Expose counts
        final_counts = flip_counts(counts)
        self.measurement_outcomes = final_counts
        return final_counts

    def circuit_to_qasm(self, params: QAOAVariationalBaseParams) -> str:
        """
        A method to convert the entire QAOA `QuantumCircuit` object into
        a OpenQASM string
        """
        raise NotImplementedError()
        # qasm_string = self.qaoa_circuit(params).qasm(formatted=True)
        # return qasm_string

    def reset_circuit(self):
        """
        Reset self.circuit after performing a computation
        """
        raise NotImplementedError()


# -*- coding: utf-8 -*-
"""
Created on Tue May  9 22:08:34 2017

@author: hyj
"""

import numpy as np

from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
# ############## 3d tranform lib  ######################
#            几何变换的一些函数，欧拉角，　旋转矩阵等
##############################################

def Rx(phi):
    return np.array([[1, 0, 0],
                     [0, np.cos(phi), np.sin(phi)],
                     [0, -np.sin(phi), np.cos(phi)]])

def Ry(theta):
    return np.array([[np.cos(theta), 0, -np.sin(theta)],
                     [0, 1, 0],
                     [np.sin(theta), 0, np.cos(theta)]])

def Rz(psi):
    return np.array([[np.cos(psi), np.sin(psi), 0],
                     [-np.sin(psi), np.cos(psi), 0],
                     [0, 0, 1]])

def euler2Rbn(eulerAngles):
    ''' navigation frame to body frame '''
    return Rx(eulerAngles[0]).dot(   Ry(eulerAngles[1]).dot( Rz(eulerAngles[2]) )  )

def euler2Rnb(eulerAngles):
    """ body frame to navigation frame ,
        euler2Rnb = euler2Rnb^t """
    return Rz(-eulerAngles[2]).dot( Ry(-eulerAngles[1]).dot( Rx(-eulerAngles[0]) )  )

# Checks if a matrix is a valid rotation matrix.
def isRotationMatrix(R) :
    Rt = np.transpose(R)
    shouldBeIdentity = np.dot(Rt, R)
    I = np.identity(3, dtype = R.dtype)
    n = np.linalg.norm(I - shouldBeIdentity)
    return n < 1e-6

# Calculates rotation matrix to euler angles
# The result is the same as MATLAB except the order
# of the euler angles ( x and z are swapped ).
def rotationMatrixToEulerAngles(R) :

    assert(isRotationMatrix(R))

    sy = np.sqrt(R[0,0] * R[0,0] +  R[1,0] * R[1,0])
    singular = sy < 1e-6

    if  not singular :
        x = np.atan2(R[2,1] , R[2,2])
        y = np.atan2(-R[2,0], sy)
        z = np.atan2(R[1,0], R[0,0])
    else :
        x = np.atan2(-R[1,2], R[1,1])
        y = np.atan2(-R[2,0], sy)
        z = 0

    return np.array([x, y, z])

def Transfrome(eulerAngles, t, point):
    ''' eulerAngles = np.array([roll, pitch, yaw] ) , t = np.array( [tx, ty, tz]) ,  point = np.array( [px, py, pz])'''
    return euler2Rnb(eulerAngles).dot(point) + t

# ############## 3d draw lib  ######################
#            some function used to draw 3d arrows
##############################################

# draw 3d arrow
class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

def drawCoordinateFrame( ax, rpy, t):

    # define origin
    o = np.array([0,0,0])
    # define ox0y0z0 axes
    x0 = np.array([1,0,0])
    y0 = np.array([0,1,0])
    z0 = np.array([0,0,1])

    R = euler2Rnb(rpy)

    # transfrom b0 frame to the new bi frame
    o1 = R.dot(o) + t
    x1 = R.dot(x0) + t
    y1 = R.dot(y0) + t
    z1 = R.dot(z0) + t

    x = Arrow3D(   [o1[0], x1[0]],    [o1[1], x1[1]],     [o1[2], x1[2]] ,  mutation_scale=20, arrowstyle='-|>', color='r')
    y = Arrow3D(   [o1[0], y1[0]],    [o1[1], y1[1]],     [o1[2], y1[2]] ,  mutation_scale=20, arrowstyle='-|>', color='b')
    z = Arrow3D(   [o1[0], z1[0]],    [o1[1], z1[1]],     [o1[2], z1[2]] ,  mutation_scale=20, arrowstyle='-|>', color='g')

   # draw
    ax.add_artist( x)
    ax.add_artist( y )
    ax.add_artist( z )


import io
import logging
from asyncio import AbstractEventLoop
from typing import Optional

import socketio
from aiohttp import web
from aiologger import Logger
from aiologger.formatters.base import Formatter
from aiologger.handlers.streams import AsyncStreamHandler
from aiologger.levels import LogLevel, check_level
from aiologger.records import LogRecord

import hello
from redirect_stdout import stdout_redirector

formatter = Formatter(
    fmt='[{name}] {asctime} {levelname}: {message}',
    datefmt='%m/%d/%Y %H:%M:%S',
    style='{'
)

logger_server = Logger(name='server', level=LogLevel.DEBUG)
logger_stdout = Logger(name="s4l", level=LogLevel.DEBUG)

sio = socketio.AsyncServer(async_mode='aiohttp')
app = web.Application()
sio.attach(app)

class SocketIOLogRedirect(AsyncStreamHandler):
    async def emit(self, record: LogRecord):
        await sio.emit('log', f"[{record.name}] {record.asctime} {record.levelname}: {record.get_message()}")

logger_stdout.add_handler(SocketIOLogRedirect())
logger_server.add_handler(SocketIOLogRedirect())

class LoggerSink(io.BytesIO):
    def __init__(self, logger):
        self.logger = logger

    def write(self, buf):
        msg = buf.decode('utf-8').rstrip('\n')
        self.logger.debug(f"Message from C {msg}")

f = LoggerSink(logger_stdout)

async def background_task():
    count = 0
    while True:
        await sio.sleep(1)
        count += 1
        await logger_server.debug(f'This is log number {count} from server')

async def background_ctask():
    count = 0
    while True:
        with stdout_redirector(f):
            hello.stdout("Foo")
            hello.stderr("Bar")

        await sio.sleep(1.0)

@sio.event
async def on_connect(sid, environ):
    await logger_server.debug(f'connect {sid}')
    await sio.emit('my_message', "asdfasdf")

@sio.event
async def disconnect(sid):
    print(sid, type(sid))
    await logger_server.debug(f'disconnect {sid}')

if __name__ == '__main__':
    sio.start_background_task(background_task)
    sio.start_background_task(background_ctask)
    web.run_app(app)


def solution(progresses, speeds): #처음 풀이
    answer = []
    progresses = progresses[::-1]
    stack_speed = speeds[::-1]
    while True:
        stack = 0
        for i in range(len(progresses)):
            progresses[i] += stack_speed[i] #비효율적인 반복문
        while progresses and progresses[-1] >= 100:
            progresses.pop()
            speeds.pop()
            stack += 1
        if stack != 0:
            answer.append(stack)
        if not progresses:
            return answer

def solution(progresses, speeds):
    answer = []
    stack = 0
    time = 0
    while progresses:
        if progresses[0] + (time * speeds[0]) >= 100:
            progresses.pop(0)
            speeds.pop(0)
            stack += 1
        else:
            if stack != 0:
                answer.append(stack)
            stack = 0
            time += 1
    answer.append(stack)
    return answer


from . import rust_ext

__version__ = "0.1.0"

import numpy as np
from sklearn.base import BaseEstimator, RegressorMixin

class psd1d(BaseEstimator, RegressorMixin):
    def __init__(self, max_lag=100, delta=1.0):
        self.max_lag = max_lag
        self.delta = delta

    def fit(self, y, x=None):
        """
        y:
        x: Ingored
        """
        if y.ndim > 1:
            raise ValueError
        self.max_lag = min(self.max_lag, y.shape[0])

        if y.dtype in (np.float64, np.complex128):
            pass
        elif y.dtype in (np.complex64, np.complex256):
            y = y.astype(np.complex128)
        else:
            y = y.astype(np.float64)

        if y.dtype == np.float64:
            self.gamma_ = rust_ext.reflection_coeff_f64(self.max_lag, y)
            assert self.gamma_.shape[0] == self.max_lag + 1
            self.p_ = rust_ext.variance_f64(self.gamma_.diagonal(), y)
            self.lag_ = self.max_lag
        elif y.dtype == np.complex128:
            self.gamma_ = rust_ext.reflection_coeff_c64(self.max_lag, y)
            assert self.gamma_.shape[0] == self.max_lag + 1
            self.p_ = rust_ext.variance_c64(self.gamma_.diagonal(), y)
            self.lag_ = self.max_lag
        else:
            raise ValueError

        return self

    def predict(self, x):
        """
        x:
        """
        if x.ndim > 1:
            raise ValueError
        if self.lag_ > self.max_lag:
            raise ValueError

        if self.gamma_.dtype == np.float64:
            return rust_ext.power_spector_f64(
                self.delta, self.p_[self.lag_], self.gamma_[self.lag_, :], x
            )
        elif self.gamma_.dtype == np.complex128:
            return rust_ext.power_spector_c64(
                self.delta, self.p_[self.lag_], self.gamma_[self.lag_, :], x
            )
        else:
            raise ValueError


import datetime
import random
from random import randint

from faker import Faker

def rand_ratio():
    return f'https://loremflickr.com/{randint(840, 900)}/{randint(473, 573)}/cook,food/'

def data_hora_aleatoria():
    ano_atual = datetime.datetime.now().year
    ano_aleatorio = random.randint(2022, ano_atual)
    mes_aleatorio = random.randint(1, 12)
    dia_aleatorio = random.randint(1, 28)
    hora_aleatoria = random.randint(0, 23)
    minuto_aleatorio = random.randint(0, 59)

    data_hora = datetime.datetime(
        ano_aleatorio, mes_aleatorio, dia_aleatorio, hora_aleatoria, minuto_aleatorio)

    return data_hora.strftime('%d/%m/%Y às %H:%M')

fake = Faker('pt_BR')

def make_recipe():
    return {
        'id': fake.random_number(digits=4, fix_len=True),
        'title': fake.sentence(nb_words=6),
        'description': fake.sentence(nb_words=12),
        'preparation_time': fake.random_number(digits=2, fix_len=True),
        'preparation_time_unit': 'Minutos',
        'servings': fake.random_number(digits=2, fix_len=True),
        'servings_unit': 'Porçõe',
        'preparation_steps': fake.text(3000),
        'timestamp': data_hora_aleatoria(),
        'author': {
            'first_name': fake.first_name(),
            'last_name': fake.last_name()
        },
        'category': {
            'name': fake.word()
        },
        'cover': {
            'url': rand_ratio()
        }
    }

if __name__ == '__main__':
    from pprint import pprint
    pprint(make_recipe())


import sys
from collections import OrderedDict

import numpy as np
from gym import spaces

from pyrep.const import RenderMode
from pyrep.objects.dummy import Dummy
from pyrep.objects.vision_sensor import VisionSensor
from rlbench.environment import Environment
from rlbench.action_modes import ArmActionMode, ActionMode
from rlbench.observation_config import ObservationConfig
from rlbench.tasks import *

# Don't forget to add: export PYTHONPATH=PATH_TO_YOUR_LOCAL_RLBENCH_REPO

# list of state types
state_types = ['left_shoulder_rgb',
               'left_shoulder_depth',
               'left_shoulder_mask',
               'right_shoulder_rgb',
               'right_shoulder_depth',
               'right_shoulder_mask',
               'wrist_rgb',
               'wrist_depth',
               'wrist_mask',
               'joint_velocities',
               'joint_velocities_noise',
               'joint_positions',
               'joint_positions_noise',
               'joint_forces',
               'joint_forces_noise',
               'gripper_pose',
               'gripper_touch_forces',
               'task_low_dim_state']

class RLBenchEnv():
    """ make RLBench env to have same interfaces as openai.gym """

    def __init__(self, task_name: str, state_type: list = 'state', ):
        # render_mode=None):
        """
        create RL Bench environment
        :param task_name: task names can be found in rlbench.tasks
        :param state_type: state or vision or a sub list of state_types list like ['left_shoulder_rgb']
        """
        if state_type == 'state' or state_type == 'vision' or isinstance(state_type, list):
            self._state_type = state_type
        else:
            raise ValueError('State type value error, your value is {}'.format(state_type))
        # self._render_mode = render_mode
        self._render_mode = None
        obs_config = ObservationConfig()
        obs_config.set_all(True)
        action_mode = ActionMode(ArmActionMode.ABS_JOINT_VELOCITY)
        self.env = Environment(
            action_mode, obs_config=obs_config, headless=True)
        self.env.launch()
        try:
            self.task = self.env.get_task(getattr(sys.modules[__name__], task_name))
        except:
            raise NotImplementedError

        _, obs = self.task.reset()
        self.spec = Spec(task_name)

        if self._state_type == 'state':
            self.observation_space = spaces.Box(
                low=-np.inf, high=np.inf, shape=obs.get_low_dim_data().shape)
        elif self._state_type == 'vision':
            space_dict = OrderedDict()
            space_dict["state"] = spaces.Box(
                low=-np.inf, high=np.inf, shape=obs.get_low_dim_data().shape)
            for i in ["left_shoulder_rgb", "right_shoulder_rgb", "wrist_rgb", "front_rgb"]:
                space_dict[i] = spaces.Box(
                    low=0, high=1, shape=getattr(obs, i).shape)
            self.observation_space = spaces.Dict(space_dict)
        else:
            space_dict = OrderedDict()
            for name in self._state_type:
                if name.split('_')[-1] in ('rgb', 'depth', 'mask'):
                    space_dict[name] = spaces.Box(
                        low=0, high=1, shape=getattr(obs, name).shape)
                else:
                    space_dict[name] = spaces.Box(
                        low=-np.inf, high=np.inf,
                        shape=getattr(obs, name).shape)
                self.observation_space = spaces.Dict(space_dict)
        self.action_space = spaces.Box(low=-1.0, high=1.0, shape=(self.env.action_size,), dtype=np.float32)

        # if render_mode is not None:
        #     # Add the camera to the scene
        #     cam_placeholder = Dummy('cam_cinematic_placeholder')
        #     self._gym_cam = VisionSensor.create([640, 360])
        #     self._gym_cam.set_pose(cam_placeholder.get_pose())
        #     if render_mode == 'human':
        #         self._gym_cam.set_render_mode(RenderMode.OPENGL3_WINDOWED)
        #     else:
        #         self._gym_cam.set_render_mode(RenderMode.OPENGL3)

    def _extract_obs(self, obs):
        if self._state_type == 'state':
            return np.array(obs.get_low_dim_data(), np.float32)
        elif self._state_type == 'vision':
            return np.array([np.array(obs.get_low_dim_data(), np.float32),
                    np.array(obs.left_shoulder_rgb, np.float32),
                    np.array(obs.right_shoulder_rgb, np.float32),
                    np.array(obs.wrist_rgb, np.float32),
                    np.array(obs.front_rgb, np.float32), ])
        else:
            result = ['tag']
            for name in self._state_type:
                result.append(np.array(getattr(obs, name), np.float32))
            return np.delete(np.array(result,), 0, 0)

    def seed(self, seed_value):
        # set seed as in openai.gym env
        pass

    def render(self, mode='human'):
        # todo render available at any time
        if self._render_mode is None:
            self._render_mode = mode
            # Add the camera to the scene
            cam_placeholder = Dummy('cam_cinematic_placeholder')
            self._gym_cam = VisionSensor.create([640, 360])
            self._gym_cam.set_pose(cam_placeholder.get_pose())
            if mode == 'human':
                self._gym_cam.set_render_mode(RenderMode.OPENGL3_WINDOWED)
            else:
                self._gym_cam.set_render_mode(RenderMode.OPENGL3)

        if mode != self._render_mode:
            raise ValueError(
                'The render mode must match the render mode selected in the '
                'constructor. \nI.e. if you want "human" render mode, then '
                'create the env by calling: '
                'gym.make("reach_target-state-v0", render_mode="human").\n'
                'You passed in mode %s, but expected %s.' % (
                    mode, self._render_mode))
        if mode == 'rgb_array':
            return self._gym_cam.capture_rgb()

    def reset(self):
        descriptions, obs = self.task.reset()
        return self._extract_obs(obs)

    def step(self, action):
        obs, reward, terminate = self.task.step(action)
        return self._extract_obs(obs), reward, terminate, None

    def close(self):
        self.env.shutdown()

class Spec():
    """ a fake spec """

    def __init__(self, id_name):
        self.id = id_name


def runningSum(nums):
    res=[0 for _ in range(len(nums))]
    res[0]=nums[0]
    for i in range(1,len(nums)):
        res[i]=res[i-1]+nums[i]
    return res

nums=[3,1,2,10,1]

print(runningSum(nums))


# Perfect numbers are sum of its factors equal to that number
# n=int(input("n:"))
# l=[]
# for i in range(1,n):
#     if(n%i==0):
#         l.append(i)
# print("Factors:",l)
# sum=0
# for i in l:
#     sum=sum+i
# if sum==n:
#     print("Perfect Number")
# else:
#     print("Not Perfect Number")

# wap to display all perfect number from n to m
n=int(input("n: "))
m=int(input("m: "))
l=[]
sum=0
if n>m or n<0 or m<0:
    print("Enter Valid Range")
for j in range(n,m+1):
    for i in range(1,j):
        if(j%i==0):
            l.append(i)
    for i in l:
        sum=sum+i
    if sum==j:
        print(j)
    sum=0
    l=[]


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 16 14:40:01 2019

@author: shirhe-lyh

Extracts features for different models.
"""

import torch

from core import xception

# A map from network name to network function
networks_map = {
    'xception_41': xception.xception_41,
    'xception_65': xception.xception_65,
    'xception_71': xception.xception_71,
}

# A map from network name to out_channels
out_channels_map = {
    'xception_41': 2048,
    'xception_65': 2048,
    'xception_71': 2048,
}

# Names for end point features
DECODER_END_POINTS = 'decoder_end_points'

# A dictionary from network name to a map of end point features
networks_to_feature_maps = {
    'xception_41': {
        DECODER_END_POINTS: {
            4: ['entry_flow/block2/unit_1/xception_module/'
                'separable_conv2_pointwise'],
        },
    },
    'xception_65': {
        DECODER_END_POINTS: {
            4: ['entry_flow/block2/unit_1/xception_module/'
                'separable_conv2_pointwise'],
        },
    },
    'xception_71': {
        DECODER_END_POINTS: {
            4: ['entry_flow/block3/unit_1/xception_module/'
                'separable_conv2_pointwise'],
        },
    },
}

feature_out_channels_map = {
    'xception_41': 256,
    'xception_65': 256,
    'xception_71': 256,
}

# A map from feature extractor name to the network name scope used in the
# ImageNet pretrained versions of these models.

# Mean pixel vale.
_MEAN_RGB = [123.15, 115.90, 103.06]

def feature_extractor(model_variant, output_stride=8, pretrained=True):
    """Extracts features by the particular model_variant.

    Args:
        model_variant: The name of feature extractor.
        output_stride: The ratio of input to output spatial resolution.
        pretrained: Whether or not to load pretrained parameters.

    Returns:
        extractor: The particular network to extract features.
        out_channels: The out channels of extractor.

    Raises:
        If model_variant not in networks_map.
    """
    if model_variant not in networks_map:
        raise ValueError('Unsupported network %s.' % model_variant)

    end_point = networks_to_feature_maps[model_variant][DECODER_END_POINTS][4][0]
    extractor = networks_map[model_variant](num_classes=None,
                                            global_pool=False,
                                            output_stride=output_stride,
                                            pretrained=pretrained,
                                            end_point=end_point)
    out_channels = out_channels_map[model_variant]
    extractor.out_channels = out_channels
    return extractor


print("Welcome to Bible Trivia!")

# Python code to retrieve the quiz questions and answers from an array
questions = [["Where did Moses die?", "Mount Nebo", ["Mount Nebo", "Mount Zion", "Mount of Olives", "Mount Sinai"]],
             ["What did God do on the fourth day of Creation?", "He created the sun, moon, and stars",
              ["He created animals", "He created the first man, Adam", "He created the sun, moon, and stars",
               "He created the Empire State Building"]]]

#function to run through quiz questions
def currentQuestion(questionslist):
    qnum = 0
    score = 0
    for question in questionslist:
        (question, answer, choices) = list(questionslist[qnum])
        print(question)
        for choice in choices:
            print(choice)
        userAnswer = input('type your answer here >')
        if userAnswer.lower() == answer.lower():
            score += 1
            print('Your answer is correct')
        else:
            print('Wrong answer, the correct answer is ' + answer)
        qnum += 1
    print("You got " + str(score) + '/' + str(qnum) + " correct")

def buildquiz():
    buildquestions = list()
    questionsnum = input("How many questions?")
    for question in range(int(questionsnum)):
        buildquestion = input("Type your question:")
        buildanswer = input("Type the correct answer:")
        buildchoices = input("Type four choices with a comma between each choice")
        buildquestions.append([buildquestion, buildanswer, list(map(str.strip, buildchoices.split(",")))])
    currentQuestion(buildquestions)

def runquiz():
    welcome_answer = input("Would you like to A. Build a quiz or B. play a quiz that's already built? Type A or B: ")
    if welcome_answer.upper() == 'A':
        buildquiz()
    elif welcome_answer.upper() == 'B':
        currentQuestion(questions)
    else:
        print("This option does not exist, try A or B")
        runquiz()

runquiz()


import random
from turtle import Turtle,Screen
is_race_on=False
screen=Screen()
screen.setup(width=500,height=400)
user_bet = screen.textinput(title="ENTER YOUR BET",prompt="WHICH TURTLE WILL WIN THE RACE?")
colors= ["purple","green","blue","yellow","red"]
y_positions= [-90,-40,10,60,110]
all_turtles=[]

for turtle_index in range(0,5):
    new_turtle=Turtle(shape="turtle")
    new_turtle.color(colors[turtle_index])
    new_turtle.penup()
    new_turtle.goto(x=-240,y=y_positions[turtle_index])
    all_turtles.append(new_turtle)

if user_bet:
    is_race_on=True

while is_race_on:
    for turtle in all_turtles:
       if turtle.xcor() >230:
           is_race_on=False
           winning_color=turtle.pencolor()

           if winning_color==user_bet:
               print("YOU HAVE WON",winning_color)
           else:
               print("better luck next time ")

       random_distance=random.randint(0,10)
       turtle.forward(random_distance)

screen.exitonclick()


import random

def compare_traits(male, female):
    male = male[:]
    female = female[:]

    person1 = male.pop(random.randint(0, len(male) - 1))
    person2 = female.pop(random.randint(0, len(female) - 1))

    similar_traits = 0
    for trait_name in person1:
        if person1[trait_name] == person2.get(trait_name):
            similar_traits += 1

    total_traits = len(person1) + len(person2)
    percentage_similar = (similar_traits / total_traits) * 100

    return (person1["name"], person2["name"], percentage_similar)

male = [{"name": "John", "pets": "birds", "drink": "coke", "habit": "smokes", "religion": "Christian"},
        {"name": "Joshua", "pets": "cats", "drink": "sprite", "habit": "bites nails", "religion": "Agnostic"},
        {"name": "Gerald", "pets": "snakes", "drink": "coke", "habit": "smokes", "religion": "Atheist"},
        {"name": "Ussop", "pets": "dogs", "drink": "ribena", "habit": "drinks", "religion": "Judeaism"},
        {"name": "Lambert", "pets": "none", "drink": "fanta", "habit": "drugs", "religion": "Agnostic"},
        {"name": "Friedmann", "pets": "none", "drink": "tea", "habit": "bites nails", "religion": "Muslim"},
        {"name": "Bazz", "pets": "birds", "drink": "wine", "habit": "drinks", "religion": "Atheist"},
        {"name": "Herbert", "pets": "hamster", "drink": "desperados", "habit": "smokes", "religion": "Agnostic"},
        {"name": "King", "pets": "none", "drink": "water", "habit": "smokes", "religion": "Muslim"},
        {"name": "Hugo", "pets": "snakes", "drink": "sprite", "habit": "drugs", "religion": "Christian"}]

female = [{"name": "Sophie", "pets": "cats", "drink": "coke", "habit": "drugs", "religion": "Atheist"},
        {"name": "Drew", "pets": "birds", "drink": "lemonade", "habit": "smokes", "religion": "Muslim"},
        {"name": "Fiona", "pets": "spiders", "drink": "fanta", "habit": "bites nails", "religion": "Hindu"},
        {"name": "Bea", "pets": "dogs", "drink": "wine", "habit": "drinks", "religion": "Christian"},
        {"name": "Matilda", "pets": "cats", "drink": "water", "habit": "drugs", "religion": "Agnostic"},
        {"name": "Erin", "pets": "goat", "drink": "sprite", "habit": "smokes", "religion": "Judeaism"},
        {"name": "Nonnie", "pets": "hamster", "drink": "ribena", "habit": "bites nails", "religion": "Taoism"},
        {"name": "Ariel", "pets": "dogs", "drink": "coke", "habit": "drinks", "religion": "Christian"},
        {"name": "Kristen", "pets": "snakes", "drink": "tea", "habit": "smokes", "religion": "Muslim"},
        {"name": "Vera", "pets": "cats", "drink": "desperados", "habit": "smokes", "religion": "Agnostic"}]

result = compare_traits(male, female)
print("Date:", result[0], "and", result[1])
print("Percentage of similar traits:", result[2])


#Stack class using python list
#support: push,pop,find_min,peek,is_empty,get_size
class Stack(object):

    def __init__(self):
        self.stack=[]
        self.__size=0
        self.min_value=[]
    def push(self,item):
        self.stack.append(item)
        self.__size+=1
        if not self.min_value or item<self.min_value[-1]:
            self.min_value.append(item)
    def pop(self):
        if self.is_empty():
            return "empty"

        if self.peek()==self.min_value[-1]:
            self.min_value.pop()
        self.__size-=1
        return self.stack.pop()
    def find_min(self):
        if self.min_value:
            return self.min_value[-1]
    def peek(self):
        if self.is_empty():
            return "empty"
        return self.stack[-1]
    def is_empty(self):
        return self.__size==0
    def get_size(self):
        return self.__size

#Queue class using linked list
#support: enqueue,dequeue,is_empty,get_size
class Queue(object):

    class _Node():
        def __init__(self,value):
            self.value=value
            self.next=None

    def __init__(self):
        self.length=0
        self.front=None
        self.rear=None
    def enqueue(self,item):

        node=self._Node(item)
        if self.length==0:
            self.front=self.rear=node
        else:
            self.rear.next=node
            self.rear=node
        self.length+=1

    def dequeue(self):
        if not self.is_empty():
            temp=self.front
            self.front=self.front.next
            self.length-=1
            if self.length==0:
                self.rear=None
            return temp.value
        else:
            return "queue is empty"
    def is_empty(self):
        return self.length==0
    def get_size(self):
        return self.length

#Deque class using double-linked list
#support: add_front,add_rear,remove_front,remove_rear,is_empty,get_size
class Deque(object):

    class _Node(object):
        def __init__(self,value):
            self.value=value
            self.prev=None
            self.next=None

    def __init__(self):
        self.front=None
        self.rear=None
        self.length=0
    def add_front(self,item):
        node=self._Node(item)
        if self.front:
            node.next=self.front
            self.front.prev=node
        self.front=node
        self.length+=1
        if self.length==1:
            self.rear=node
    def add_rear(self,item):
        node=self._Node(item)
        if self.rear:
            self.rear.next=node
            node.prev=self.rear
        self.rear=node
        self.length+=1
        if self.length==1:
            self.front=node
    def remove_front(self):
        node=self.front
        self.front=node.next
        self.length-=1
        if self.length==0:
            self.rear=None
        else:
            self.front.prev=None
        return node.value
    def remove_rear(self):
        node=self.rear
        self.rear=node.prev
        self.length-=1
        if self.length==0:
            self.front=None
        else:
            self.rear.next=None

        return node.value
    def is_empty(self):
        return self.length==0
    def get_size(self):
        return self.length

#Linked List class using double-linked list
#support: append,remove,search,index,insert,pop,is_empty,get_size
class UnorderedLinkedList(object):

    class _Node(object):
        def __init__(self,value):
            self.value=value
            self.next=None
    def __init__(self):
        self.head=None
    def append(self,item):
        node=self._Node(item)
        if not self.head:
            self.head=node
        else:
            tmp=self.head
            while tmp.next:
                tmp=tmp.next
            tmp.next=node
    def remove(self,item):
        prev=None
        this=self.head
        while this.value!=item and this.next:
            prev=this
            this=this.next
        if prev==None:
            self.head=this.next
        else:
            prev.next=this.next
    def search(self,item):
        this=self.head
        while this:
            if this.value==item:
                return True
            this=this.next
        return False
    def is_empty(self):
        return self.head==None
    def get_size(self):
        length=0
        this=self.head
        while this:
            this=this.next
            length+=1
        return length
    def index(self,item):
        pos=0
        this=self.head
        while this:
            if this.value==item:
                return pos
            this=this.next
            pos+=1
        return False
    def insert(self,pos,item):
        node=self._Node(item)
        if pos==0:
            node.next=self.head
            self.head=node
        else:
            this=self.head
            while this and pos>0:
                pos-=1
                prev=this
                this=this.next
            prev.next=node
            node.next=this
    def pop(self,pos=0):
        prev=None
        this=self.head
        while this and pos>0:
            pos-=1
            prev=this
            this=this.next
        if prev==None:
            node=self.head
            self.head=node.next
            return node.value
        prev.next=this.next
        return this.value

#minimum binary heap using python list
#support: insert,find_min,del_min,is_empty,get_size,build_heap
class Min_BinaryHeap(object):
    def __init__(self):
        self.heap=[0]
        self.length=0
    def _swim(self):
        i=self.length
        while i>1 and self.heap[i]<self.heap[i/2]:
            self.heap[i/2],self.heap[i]=self.heap[i],self.heap[i/2]
            i/=2
    def _sink(self):
        i=1
        while 2*i<=self.length:
            j=2*i
            if j<self.length and self.heap[j]>self.heap[j+1]:
                j+=1
            if self.heap[i]<=self.heap[j]:
                break
            self.heap[i],self.heap[j]=self.heap[j],self.heap[i]
            i=j

    def insert(self,key):
        self.length+=1
        if self.length>=len(self.heap):
            self.heap.append(key)
        else:
            self.heap[self.length]=key

        self._swim()
    def find_min(self):
        return self.heap[1]
    def del_min(self):
        if self.is_empty():
            return "empty"
        smallest=self.heap[1]
        self.heap[1]=self.heap[self.length]
        self.heap[self.length]=None
        self.length-=1
        self._sink()
        return smallest
    def is_empty(self):
        return self.length==0
    def get_size(self):
        return self.length
    def build_heap(self,the_list):
        for k in the_list:
            self.insert(k)

#Hash table
#support: put,get,hash_function
class HashTable(object):
    class _Node(object):
        def __init__(self,key,value):
            self.key=key
            self.value=value
            self.next=None
    def __init__(self,table_size=11):
        self.table_size=table_size
        self.slots=[None]*table_size
    def hash_function(self,key):
        return key % self.table_size
    def put(self,key,val):
        hash_value=self.hash_function(key)
        node=self._Node(key,val)
        if self.slots[hash_value]:
            tmp_node=self.slots[hash_value]
            while tmp_node.next:
                tmp_node=tmp_node.next
            tmp_node.next=node
        else:
            self.slots[hash_value]=node

    def get(self,key):
        hash_value=self.hash_function(key)
        tmp_node=self.slots[hash_value]
        while tmp_node and tmp_node.key!=key:
            tmp_node=tmp_node.next
        if tmp_node:
            return tmp_node.value
        return "no key value"
    def __getitem__(self,key):
        return self.get(key)
    def __setitem__(self,key,value):
        self.put(key,value)
    def __len__(self):
        count=0
        for e in self.slots:
            if e:
                tmp_node=e
                while tmp_node:
                    count+=1
                    tmp_node=tmp_node.next
        return count
    def __contains__(self,key):
        hash_value=self.hash_function(key)
        tmp_node=self.slots[hash_value]
        while tmp_node and tmp_node.key!=key:
            tmp_node=tmp_node.next
        if tmp_node:
            return True
        return False

#Binary Search Tree
#support: put,get,delete,find_min,find_rank,search_by_rank,is_empty,get_size
class BinarySearchTree(object):
    class _TreeNode(object):
        def __init__(self,key,value):
            self.key=key
            self.value=value
            self.left=None
            self.right=None
            self.node_num=1
    def __init__(self):
        self.root=None
    def is_empty(self):
        return self.get_size()==0
    def get_size(self):
        if self.root:
            return self.root.node_num
        return 0
    def __contains__(self,key):
        return self.get(key)!=None
    def put(self,key,value):
        if not self.root:
            self.root=self._TreeNode(key,value)
        else:
            self._put(key,value,node=self.root)
    def _put(self,key,value,node):
            node.node_num+=1
            if key<node.key:
                if node.left:
                    self._put(key,value,node.left)
                else:
                    node.left=self._TreeNode(key,value)
            elif key>node.key:
                if node.right:
                    self._put(key,value,node.right)
                else:
                    node.right=self._TreeNode(key,value)
            else:
                node.value=value
    def get(self,key):
        return self._get(key,self.root)
    def _get(self,key,node):
        if not node:
            return None
        if key<node.key:
            return self._get(key,node.left)
        elif key>node.key:
            return self._get(key,node.right)
        else:
            return node.value
    def delete(self,key):
        self.root=self._delete(key,self.root)
    def _delete(self,key,node):
        if not node:
            return None
        if key<node.key:
            node.left=self._delete(key,node.left)
        elif key>node.key:
            node.right=self._delete(key,node.right)
        else:
            if not node.left:
                return node.right
            if not node.right:
                return node.left
            x=self._find_min(node.right)
            x.right=self._delete(x.key,node.right)
            x.left=node.left
            node=x
        node.node_num=(node.left.node_num if node.left else 0)+ \
        (node.right.node_num if node.right else 0)+1
        return node
    def find_min(self):
        if self.is_empty():
            return None
        return self._find_min(self.root).key
    def _find_min(self,node):
        while node.left:
            node=node.left
        return node
    def find_rank(self,key):
        return self._find_rank(key,self.root)
    def _find_rank(self,key,node):
        if not node:
            return None
        if key<node.key:
            return self._find_rank(key,node.left)
        elif key>node.key:
            rank=self._find_rank(key,node.right)
            if rank:
                return rank+(node.left.node_num if node.left else 0)+1
            return None
        else:
            return (node.left.node_num if node.left else 0)+1

    def search_by_rank(self,rank):
        if rank>self.get_size() or rank==0:
            return None
        return self._search_by_rank(rank,self.root).key
    def _search_by_rank(self,rank,node):
        left_size=(node.left.node_num if node.left else 0)+1
        if rank<left_size:
            return self._search_by_rank(rank,node.left)
        elif rank>left_size:
            return self._search_by_rank(rank-left_size,node.right)
        else:
            return node

#graph
#support: add_vertex,add_edge,get_vertex,get_vertices
#also support: "in" operation and loop
class Graph(object):
    def __init__(self):
        self.vert_list={}

    def add_vertex(self,v):
        if v not in self.vert_list:
            self.vert_list[v]={}
    def add_edge(self,from_v,to_v,weight=0):
        if not from_v in self.vert_list:
            self.add_vertex(from_v)
        if not to_v in self.vert_list:
            self.add_vertex(to_v)
        self.vert_list[from_v][to_v]=weight
    def get_vertex(self,v_key):
        return self.vert_list.get(v_key,None)
    def get_vertices(self):
        return self.vert_list.keys()
    def __contains__(self,v):
        return v in self.vert_list
    def __iter__(self):
        return iter(self.vert_list.values())


import sys

data = sys.stdin.read()

rules, my_ticket, other_tickets = data.strip().split('\n\n')

# print('*')
# print(rules)
# print('*')
# print(my_ticket)
# print('*')
# print(other_tickets)
# print('*')

def parse_interval(v):
    lo, hi = v.split('-')
    return int(lo), int(hi)

def parse_rule(rule):
    t, rest = rule.split(':')
    fst, lst = rest.strip().split(' or ')
    return t, parse_interval(fst), parse_interval(lst)

def parse_rules(rules):
    d = {}
    for r in rules.split('\n'):
        (t, fst, lst) = parse_rule(r)
        d[t] = (fst, lst)
    return d

def parse_ticket(t):
    return [int(x) for x in t.split(',')]

def parse_tickets(o):
    lines = o.split('\n')
    return [parse_ticket(x) for x in lines[1:]]

def matching_rules(value, rules):
    m = []
    for (t, v) in rules.items():
        ((l1, h1), (l2, h2)) = v
        if (l1 <= value <= h1) or (l2 <= value <= h2):
            m.append(t)
    return m

def simple_check(ticket, rules):
    unmatched = []
    for v in ticket:
        if not matching_rules(v, rules):
            unmatched.append(v)
    return unmatched

rules = parse_rules(rules)
other_tickets = parse_tickets(other_tickets)
[my_ticket] = parse_tickets(my_ticket)

tot = 0
valid_tickets = []
for ticket in other_tickets:
    unmatched = simple_check(ticket, rules)
    is_valid = len(unmatched) == 0
    tot += sum(unmatched)
    if is_valid:
        valid_tickets.append(ticket)

print("part 1", tot)

possible = dict((pos, set(rules.keys())) for pos in range(len(my_ticket)))

for ticket in valid_tickets:
    for pos in range(len(my_ticket)):
        a = possible[pos]
        b = matching_rules(ticket[pos], rules)
        possible[pos] = a.intersection(b)

# check for simplifying structure
s = set()
for k,v in sorted(possible.items(), key = lambda p: len(p[1])):
    print (k, len(v))
    assert set(v).union(s) == set(v)
    s = set(v)

# This abuses the fact that the posibilities in the test data have a very simple structure.
used = set()
sol = {}
for k,v in sorted(possible.items(), key = lambda p: len(p[1])):
    vset = set(v)
    assert used.difference(vset) == set()
    s = set(v).difference(used)
    assert len(s) == 1
    sol[s.pop()] = k
    used = vset

print(sol)

s = 1
for name, val in sol.items():
    if name.startswith('departure'):
        s *= my_ticket[val]

print("part 2", s)


from flask_restplus import Namespace, Resource, fields
from core import db
from functools import wraps
from flask import request
from core import api_vars
import sys
from datetime import datetime
import json

api = Namespace('Public', description='The public side of the Lokaalbezetting API')

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):

        token = None

        if 'X-API-KEY' in request.headers:
            token = request.headers['X-API-KEY']

        if not token:
            return {'status': 'failed', 'error': 'This endpoint requires an access token'}, 401

        database = db.Database()
        matchedTokens = database.readToken(token=token, namespace='public')
        database.close()
        if matchedTokens == False:
            return {'status': 'failed', 'error': 'Could not check if token exists in database'}
        else:
            if len(matchedTokens) == 0:
                return {'status': 'failed', 'error': 'Incorrect token'}, 401

        return f(*args, **kwargs)

    return decorated

@api.route('/classrooms')
class Classrooms(Resource):

    @api.doc(security=['Token'])
    @token_required
    @api.response(200, 'Success')
    @api.response(401, 'Unauthorized')
    def get(self):

        classrooms = []

        database = db.Database()
        classroomsQuery = database.query('''SELECT classcode FROM classrooms;''')
        database.close()

        if classroomsQuery == False:
            return {'status': 'failed', 'error': 'Could not get classrooms from database.'}

        if len(classroomsQuery) < 1:
            return {'status': 'failed', 'error': 'There are no classrooms.'}

        for classroom in classroomsQuery:
            classroomdict = dict()
            classroomdict['classcode'] = classroom[0]
            classrooms.append(classroomdict)

        return {'status': 'ok', 'classrooms': classrooms}

@api.route('/occupation/buildings')
class Buildings(Resource):

    @api.doc(security=['Token'])
    @token_required
    @api.response(200, 'Success')
    @api.response(401, 'Unauthorized')
    def get(self):

        totalObject = []

        database = db.Database()
        buildings = database.query('''SELECT * FROM buildings ORDER BY name;''')

        if buildings == False:
            return {'status': 'failed', 'error': 'Could not get buildings from database'}

        if len(buildings) < 1:
            return {'status': 'failed', 'error': 'There are no buildings.'}

        for building in buildings:
            buildingdict = dict()
            buildingdict['id'] = building[0]
            buildingdict['name'] = building[1]
            buildingdict['streetname'] = building[2]
            buildingdict['buildingnumber'] = building[3]
            buildingdict['floors'] = []
            totalObject.append(buildingdict)

        floors = database.query('''SELECT * FROM floors ORDER BY floornumber;''')

        if floors == False:
            return {'status': 'failed', 'error': 'Could not get floors from database'}

        for floor in floors:
            floordict = dict()
            floordict['id'] = floor[0]
            floordict['floornumber'] = int(floor[1])
            floordict['classrooms'] = []

            for building in totalObject:
                if building['id'] == floor[2]:
                    building['floors'].append(floordict)

        classrooms = database.query('''SELECT * FROM classrooms;''')

        if classrooms == False:
            return {'status': 'failed', 'error': 'Could not get classrooms from database'}

        for classroom in classrooms:
            classroomdict = dict()
            classroomdict['classcode'] = classroom[0]

            free = "Unknown"

            try:
                freeQuery = database.query('''select count(*) from occupation WHERE classcode = '{}' AND time > now() - interval '60 seconds';'''.format(classroomdict['classcode']))

                if freeQuery[0][0] >= int(api_vars.MOTION_THRESHOLD):
                    free = False
                elif freeQuery[0][0] < int(api_vars.MOTION_THRESHOLD):
                    free = True
            except:
                free = "Unknown"

            classroomdict['free'] = free

            for buildings in totalObject:
                for floor in buildings['floors']:
                    if floor['id'] == classroom[1]:
                        floor['classrooms'].append(classroomdict)

        database.close()

        return {'status': 'ok', 'buildings': totalObject}

@api.route('/occupation/building/<string:building_id>')
class Building(Resource):

    @api.doc(security=['Token'])
    @token_required
    @api.response(200, 'Success')
    @api.response(401, 'Unauthorized')

    def get(self, building_id):

        totalObject = []

        database = db.Database()
        buildings = database.query('''SELECT * FROM buildings WHERE id = '{}' ORDER BY name;'''.format(building_id))

        if buildings == False:
            return {'status': 'failed', 'error': '{} is not a valid UUID.'.format(building_id)}

        if len(buildings) < 1:
            return {'status': 'failed', 'error': 'Building with id {} does not exist.'.format(building_id)}

        for building in buildings:
            buildingdict = dict()
            buildingdict['id'] = building[0]
            buildingdict['name'] = building[1]
            buildingdict['streetname'] = building[2]
            buildingdict['buildingnumber'] = building[3]
            buildingdict['floors'] = []
            totalObject.append(buildingdict)

        floors = database.query('''SELECT * FROM floors ORDER BY floornumber;''')

        if floors == False:
            return {'status': 'failed', 'error': 'Could not get floors from database'}

        for floor in floors:
            floordict = dict()
            floordict['id'] = floor[0]
            floordict['floornumber'] = int(floor[1])
            floordict['classrooms'] = []

            for building in totalObject:
                if building['id'] == floor[2]:
                    building['floors'].append(floordict)

        classrooms = database.query('''SELECT * FROM classrooms;''')

        if classrooms == False:
            return {'status': 'failed', 'error': 'Could not get classrooms from database'}

        for classroom in classrooms:
            classroomdict = dict()
            classroomdict['classcode'] = classroom[0]

            free = "Unknown"

            try:
                freeQuery = database.query('''select count(*) from occupation WHERE classcode = '{}' AND time > now() - interval '60 seconds';'''.format(classroomdict['classcode']))
                if freeQuery[0][0] >= int(api_vars.MOTION_THRESHOLD):
                    free = False
                elif freeQuery[0][0] < int(api_vars.MOTION_THRESHOLD):
                    free = True
            except:
                free = "Unknown"

            classroomdict['free'] = free

            for buildings in totalObject:
                for floor in buildings['floors']:
                    if floor['id'] == classroom[1]:
                        floor['classrooms'].append(classroomdict)

        building = totalObject[0]

        database.close()

        return {'status': 'ok', 'id': building['id'], 'name': building['name'], 'streetname': building['streetname'], 'buildingnumber': building['buildingnumber'], 'floors': building['floors']}

@api.route('/occupation/floor/<string:floor_id>')
class Floor(Resource):

    @api.doc(security=['Token'])
    @token_required
    @api.response(200, 'Success')
    @api.response(401, 'Unauthorized')

    def get(self, floor_id):

        database = db.Database()

        floors = database.query('''SELECT * FROM floors WHERE id = '{}';'''.format(floor_id))

        if floors == False:
            return {'status': 'failed', 'error': 'Could not get floors from database'}

        if len(floors) < 1:
            return {'status': 'failed', 'error': 'Floor with id {} does not exist'.format(floor_id)}

        floor_id = floors[0][0]
        floor_number = int(floors[0][1])
        classrooms_object = []

        classrooms = database.query('''SELECT * FROM classrooms WHERE id_floors = '{}';'''.format(floor_id))

        if classrooms == False:
            return {'status': 'failed', 'error': 'Could not get classrooms from database'}

        if len(classrooms) < 1:
            return {'status': 'failed', 'error': 'Floor with id {} has no classrooms'.format(floor_id)}

        for classroom in classrooms:
            classroomdict = dict()
            classroomdict['classcode'] = classroom[0]

            free = "Unknown"

            try:
                freeQuery = database.query('''select count(*) from occupation WHERE classcode = '{}' AND time > now() - interval '60 seconds';'''.format(classroomdict['classcode']))
                if freeQuery[0][0] >= int(api_vars.MOTION_THRESHOLD):
                    free = False
                elif freeQuery[0][0] < int(api_vars.MOTION_THRESHOLD):
                    free = True
            except:
                free = "Unknown"

            classroomdict['free'] = free

            classrooms_object.append(classroomdict)

        database.close()

        return {'status': 'ok', 'id': floor_id, 'classrooms': classrooms_object}

@api.route('/occupation/classroom/<string:classcode>')
class Classroom(Resource):

    @api.doc(security=['Token'])
    @token_required
    @api.response(200, 'Success')
    @api.response(401, 'Unauthorized')

    def get(self, classcode):

        database = db.Database()

        classrooms = database.query('''SELECT * FROM classrooms WHERE classcode = '{}';'''.format(classcode))

        if classrooms == False:
            return {'status': 'failed', 'error': 'Could not get classrooms from database'}

        if len(classrooms) < 1:
            return {'status': 'failed', 'error': 'Classroom with classcode {} does not exist'.format(classcode)}

        classcode = classrooms[0][0]

        free = "Unknown"

        try:
            freeQuery = database.query('''select count(*) from occupation WHERE classcode = '{}' AND time > now() - interval '60 seconds';'''.format(classcode))
            if freeQuery[0][0] >= int(api_vars.MOTION_THRESHOLD):
                free = False
            elif freeQuery[0][0] < int(api_vars.MOTION_THRESHOLD):
                free = True
        except:
            free = "Unknown"

        database.close()

        return {'status': 'ok', 'classcode': classcode, 'free': free}

@api.route('/floorplan/<string:floor_id>')
class Floorplan(Resource):

    @api.doc(security=['Token'])
    @token_required
    @api.response(200, 'Success')
    @api.response(401, 'Unauthorized')

    def get(self, floor_id):

        database = db.Database()

        try:
            result = database.query('''SELECT * FROM floorplans WHERE id_floors = '{}';'''.format(floor_id))
            if len(result) < 1:
                return {'status': 'failed', 'error': 'There is no floorplan for floor with UUID {}.'.format(floor_id)}
        except:
            return {'status': 'failed', 'error': 'Floor with UUID {} does not exist'.format(floor_id)}

        database.close()

        return {'status': 'ok', 'floorplan': str(result[0][0])}

@api.route('/export')
class Export(Resource):

    @api.doc(security=['Token'])
    @token_required
    @api.response(200, 'Success')
    @api.response(401, 'Unauthorized')

    def get(self):

        database = db.Database()
        classrooms = dict()

        result = database.query('''SELECT DISTINCT(classcode) FROM occupation;''')
        if len(result) < 1:
            return {'status': 'failed', 'error': 'There is no occupation data.'}

        for classroom in result:
            classrooms[classroom[0]] = []

        for classroom in classrooms.keys():
            detections = database.query('''SELECT time FROM occupation WHERE classcode = '{}';'''.format(classroom))
            detections_formatted = []
            for detection in detections:
                detections_formatted.append(detection[0].strftime("%x %X"))

            classrooms[classroom] = detections_formatted

        database.close()

        return {'status': 'ok', 'export': classrooms}


import tensorflow as tf

class Attention(tf.keras.Model):
    def __init__(self, units):
        super(Attention, self).__init__()
        self.units = units
        # define layers during initialization
        self.W1 = tf.keras.layers.Dense(self.units)
        self.W2 = tf.keras.layers.Dense(self.units)
        self.V = tf.keras.layers.Dense(1)

    def call(self, features, hidden):
        # expand hidden to shape (batch_size, 1, hidden_size)
        hidden_with_time_axis = tf.expand_dims(hidden, 1)
        attention_hidden_layer = tf.nn.tanh(
            self.W1(features) + self.W2(hidden_with_time_axis))
        # build score funciton to shape (batch_size, 8*8, units)
        score = self.V(attention_hidden_layer)
        # extract attention weights with shape (batch_size, 8*8, 1)
        attention_weights = tf.nn.softmax(score, axis=1)
        # create the context vector with shape (batch_size, 8*8,embedding_dim)
        context_vector = attention_weights * features
        # reduce the shape to (batch_size, embedding_dim)
        context_vector = tf.reduce_sum(context_vector, axis=1)

        return context_vector, attention_weights


import FWCore.ParameterSet.Config as cms

process = cms.Process('Analysis')

process.options = cms.untracked.PSet(
    wantSummary = cms.untracked.bool(True)
    )
process.MessageLogger = cms.Service('MessageLogger',
                                    tauPlots = cms.untracked.PSet(
    INFO = cms.untracked.PSet(
    limit = cms.untracked.int32(0)
    ),
    FwkReport = cms.untracked.PSet(
    optionalPSet = cms.untracked.bool(True),
    reportEvery = cms.untracked.int32(1000),
    limit = cms.untracked.int32(1000)
    ),
    default = cms.untracked.PSet(
    optionalPSet = cms.untracked.bool(True),
    limit = cms.untracked.int32(100)
    ),
    Root_NoDictionary = cms.untracked.PSet(
    optionalPSet = cms.untracked.bool(True),
    limit = cms.untracked.int32(0)
    ),
    FwkJob = cms.untracked.PSet(
    optionalPSet = cms.untracked.bool(True),
    limit = cms.untracked.int32(0)
    ),
    FwkSummary = cms.untracked.PSet(
    optionalPSet = cms.untracked.bool(True),
    reportEvery = cms.untracked.int32(1),
    limit = cms.untracked.int32(10000000)
    ),
    threshold = cms.untracked.string('INFO')
    ),
    destinations = cms.untracked.vstring('tauPlots', 'cout')
    )

process.source = cms.Source('PoolSource',
                            duplicateCheckMode = cms.untracked.string('noDuplicateCheck'),
                            fileNames = cms.untracked.vstring(
#    'file:/user/edelhoff/mcData/CMSSW_313/LM0-313-SUSYPAT-V00-04-07.root'
    'file:/user/edelhoff/mcData/CMSSW_314/LM0-314-SUSYPAT-V00-04-11.root'
#    'file:/user/edelhoff/mcData/CMSSW_314/RelValZTT_314_SUSYPAT_V00-04-12_1000ev.root'
#defective:    'file:/user/edelhoff/mcData/CMSSW_314/RelVal_314_ZTT/RelValZTT_314_SUSYPAT_V00-04-12_1.root',
#    'file:/user/edelhoff/mcData/CMSSW_314/RelVal_314_ZTT/RelValZTT_314_SUSYPAT_V00-04-12_2.root',
#    'file:/user/edelhoff/mcData/CMSSW_314/RelVal_314_ZTT/RelValZTT_314_SUSYPAT_V00-04-12_3.root',
#    'file:/user/edelhoff/mcData/CMSSW_314/RelVal_314_ZTT/RelValZTT_314_SUSYPAT_V00-04-12_4.root',
)
)

process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(10))

###########------ Tools -------#############
process.dump = cms.EDAnalyzer('EventContentAnalyzer')

process.printTree = cms.EDAnalyzer("ParticleTreeDrawer",
    src = cms.InputTag("genParticles"),#genTausWithHistory"),#tauGenParticles"),#genParticles"),#
    printP4 = cms.untracked.bool(False),
    printPtEtaPhi = cms.untracked.bool(False),
    printVertex = cms.untracked.bool(False),
    printStatus = cms.untracked.bool(True),
    printIndex = cms.untracked.bool(False),
    status = cms.untracked.vint32( 1, 2, 3 )
  )

process.printDecay = cms.EDAnalyzer("ParticleDecayDrawer",
    src = cms.InputTag("genParticles"),#hadronicGenTaus"),#
    printP4 = cms.untracked.bool(False),
    printPtEtaPhi = cms.untracked.bool(False),
    printVertex = cms.untracked.bool(False)
)

process.TFileService = cms.Service('TFileService', fileName = cms.string('tauPlots.root'))

###########------ Selection Paths -------#############
process.load('SuSyAachen.Skimming.electronSelection_cff')
process.load('SuSyAachen.Skimming.muonSelection_cff')
process.load('SuSyAachen.Skimming.tauSelection_cff')
process.load('SuSyAachen.Skimming.jetMETSelection_cff')

process.load('SuSyAachen.Skimming.genSelection_cff')

process.load('SuSyAachen.Skimming.diLeptonFilter_cff')

process.GenParticles = cms.Path(
    process.seqGenParticles
    * process.seqBasicGenParticles
    * process.seqMatchedParticles
)

process.Leptons = cms.Path(
    process.seqMuons
    + process.seqElectrons
    + process.seqTaus
    + process.seqSSDiLeptons
#    + process.seqSelectJetMET
    + process.dump
    )
###########------ Histos -------#############
process.load('SuSyAachen.Histograms.leptonCounter_cff')

process.Histograms = cms.Path(
    cms.ignore(process.SSTauTau) +
    process.seqLeptonCounter
#    + process.printTree
#    + process.printDecay
)

###########------ Output -------#############

#from PhysicsTools.PatAlgos.patEventContent_cff import patEventContent
process.out = cms.OutputModule("PoolOutputModule",
                               fileName = cms.untracked.string('tauPAT.root'),
                               # save only events passing the full path
                               #SelectEvents   = cms.untracked.PSet( SelectEvents = cms.vstring('GenParticles') ),
                               # save PAT Layer 1 output; you need a '*' to
                               # unpack the list of commands 'patEventContent'
                               outputCommands = cms.untracked.vstring('drop *',
                                                                      'keep patElectrons_*_*_*',
                                                                      'keep patMuons_*_*_*',
                                                                      'keep patTaus_*_*_*',
                                                                      'keep recoGenParticles_*_*_*',
                                                                      'keep recoGenJets_*_*_*',
                                                                      'drop *_genParticles_*_*')
                               )
process.outpath = cms.EndPath(process.out)

process.schedule = cms.Schedule( process.Leptons, process.GenParticles,
                                 process.Histograms
, process.outpath
)


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

import sys
import csv
import dns.resolver
import time
#pip3 install PyQt5
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QIcon, QPixmap

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setup_UI()

    def setup_UI(self):
        # set up window size
        self.setGeometry(500, 100, 800, 500)
        self.setWindowTitle("Simple Viewer")

        # set Table
        self.table_Widget = QTableWidget(self)

        # set Column
        self.table_Widget.setColumnCount(4)
        self.colum_setting()
        self.table_Widget.resizeColumnsToContents()
        self.table_Widget.resizeRowsToContents()

        # nslookup
        self.title_1 = QLabel("Nslookup")
        self.lablName1 = QLabel("Main_DNS")
        self.editName1 = QLineEdit()
        self.lablName2 = QLabel("Sub_DNS")
        self.editName2 = QLineEdit()
        self.lablName3 = QLabel("Domain")
        self.editName3 = QLineEdit()
        self.btn_Ok = QPushButton("View ip")
        self.btn_Ok.clicked.connect(self.btnOk_Clicked)

        self.title_2 = QLabel("\nCsv Viewer")
        # open button, close button
        self.btn_open = QPushButton("파일 열기", self)
        self.btn_open.clicked.connect(self.file_open)

        self.btn_close = QPushButton("창닫기", self)
        self.btn_close.clicked.connect(QCoreApplication.instance().quit)

        # mal ip print
        self.btn_sort = QPushButton("ip 출력", self)
        self.btn_sort.clicked.connect(self.find_mal_ip)

        # 선택한 ip 출력
        self.lblName = QLabel("보고싶은 ip 입력")
        self.editName = QLineEdit()
        self.btnOk = QPushButton("OK")
        self.btnOk.clicked.connect(self.btnOkClicked)

        # layout
        title_layout = QHBoxLayout()
        title_layout.addWidget(self.title_1)

        title_layout2 = QHBoxLayout()
        title_layout2.addWidget(self.title_2)

        ip_layout = QHBoxLayout()
        ip_layout.addWidget(self.lablName1)
        ip_layout.addWidget(self.editName1)
        ip_layout.addWidget(self.lablName2)
        ip_layout.addWidget(self.editName2)
        ip_layout.addWidget(self.lablName3)
        ip_layout.addWidget(self.editName3)
        ip_layout.addWidget(self.btn_Ok)

        test_layout = QHBoxLayout()
        test_layout.addWidget(self.lblName)
        test_layout.addWidget(self.editName)
        test_layout.addWidget(self.btnOk)

        high_LayOut = QHBoxLayout()
        high_LayOut.addWidget(self.btn_open)
        high_LayOut.addWidget(self.btn_close)

        low_LayOut = QVBoxLayout()
        low_LayOut.addWidget(self.table_Widget)
        self.table_Widget.setColumnWidth(0, 220)
        self.table_Widget.setColumnWidth(1, 200)
        self.table_Widget.setColumnWidth(2, 203)
        self.table_Widget.setColumnWidth(3, 130)
        low_LayOut.addWidget(self.btn_sort)

        layout = QVBoxLayout()
        layout.addLayout(title_layout)
        layout.addLayout(ip_layout)
        layout.addLayout(title_layout2)
        layout.addLayout(low_LayOut)
        layout.addLayout(test_layout)
        layout.addLayout(high_LayOut)

        self.setLayout(layout)

    def file_open(self):
        self.table_Widget.clear()
        self.colum_setting()
        self.table_Widget.setRowCount(0)
        files = QFileDialog.getOpenFileNames(self)
        for f in files[0]:
            file_name = f.split('/')[-1]
            file_path = f
            if (".csv" in file_name):
                self.line_list = []
                self.ip = []

                f_csv = open(file_path, 'r', encoding='utf-8')
                rdr = csv.reader(f_csv)
                for line in rdr:
                    row_numb = self.table_Widget.rowCount()
                    self.table_Widget.insertRow(row_numb)
                    i = (int(line[0])-1)
                    # csv list input
                    self.table_Widget.setItem(i, 0, QTableWidgetItem(line[1]))
                    self.table_Widget.setItem(i, 1, QTableWidgetItem(line[2]))
                    self.table_Widget.setItem(i, 2, QTableWidgetItem(line[3]))
                    self.table_Widget.setItem(i, 3, QTableWidgetItem(line[4]))

                    self.ip.append(line[3])
                    self.line_list.append(line)

                f_csv.close()

            else:
                QMessageBox.about(self, "Warning", "This is not csv file")

    def colum_setting(self):
        self.table_Widget.setHorizontalHeaderLabels(['Time', 'Address', 'ip', 'dns'])

    def find_mal_ip(self):
        try:
            QMessageBox.about(self, "Malicious ip", "\n".join(set(self.ip)))
        except:
            QMessageBox.about(self, "Warning", "Put file first")

    def btnOkClicked(self):
        try:
            input_ip = self.editName.text()
            self.table_Widget.clear()
            self.colum_setting()
            self.mali_ip = set(self.ip)
            row_number = 0
            add_list = []
            self.table_Widget.setRowCount(0)

            for index in range(len(self.line_list)):
                self.table_Widget.removeRow(index)

            for i in range(len(self.line_list)):
                if(self.line_list[i][3] in (input_ip)):
                    add_list.append(self.line_list[i])

            for i in range(len(add_list)):
                row_numb = self.table_Widget.rowCount()
                self.table_Widget.insertRow(row_numb)
                self.table_Widget.setItem(row_number, 0, QTableWidgetItem(add_list[i][1]))
                self.table_Widget.setItem(row_number, 1, QTableWidgetItem(add_list[i][2]))
                self.table_Widget.setItem(row_number, 2, QTableWidgetItem(add_list[i][3]))
                self.table_Widget.setItem(row_number, 3, QTableWidgetItem(add_list[i][4]))
                row_number += 1
        except:
            QMessageBox.information(self, "Warning", "Input only ip")

    def btnOk_Clicked(self):
        try:
            main_dns = self.editName1.text()
            sub_dns = self.editName2.text()
            domain = self.editName3.text()
            domain = domain.replace('http://','')
            domain = domain.replace('https://','')
            self.table_Widget.clear()
            self.colum_setting()

            resolver = dns.resolver.Resolver()
            try:
                # main dns query
                resolver.nameservers = [main_dns]
                answers = resolver.query(domain)
            except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
                # sub dns query
                resolver.nameservers = [sub_dns]
                answers = resolver.query(domain)
                pass

            dns_address = []
            for rdata in answers:
                dns_address.append(rdata.address)

            QMessageBox.information(self, "Nslookup", str(domain) + "\n\n" + str("\n".join(set(dns_address))))

        except:
            QMessageBox.information(self, "Warning", "Input Correct please")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    app.exec_()