from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QDialog, QLabel, QPushButton, QSizePolicy, QComboBox, QGroupBox, QScrollArea, QListWidget, QListWidgetItem

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

from myo_armband.myo_trainer import *

import pickle
import os
import time

class GestureTrackerDialog(QDialog):

    def __init__(self):
        '''
        Shows a graph for training gesture recognition
        '''
        super(GestureTrackerDialog, self).__init__()
        self.name = None
        self.design = None
        self.ip = None

        self.window_width = 1000
        self.window_height = 800
        self.setFixedSize(self.window_width, self.window_height)
        self.setWindowTitle("Train Gestures")
        self.setStyleSheet('QDialog {background-color: white;}')

        # setup the figure canvas
        self.graph = PlotWindow(parent=self, width=8, height=7.5)
        self.graph.move(180,0)

        # record groupbox
        self.gb_record = QGroupBox("controls", parent=self)
        self.gb_record.setGeometry(10,10,170,120)

        # record button
        self.record = QPushButton("record", self.gb_record)
        #self.okay.clicked.connect(self.on_okay)
        button_width = 160
        button_height = 35
        self.record.setGeometry(6, 25, button_width, button_height)
        self.record.setStyleSheet('QPushButton {color: black;}')
        self.record.clicked.connect(self.begin_countdown)
        self.countdown_label = QLabel("",parent=self)
        self.countdown_label.setGeometry(350,150,400,400)
        self.countdown_label.setStyleSheet('QLabel {color: rgba(250,0,0,50%); font: 500pt Arial}')
        self.countdown_label.hide()
        self.countdown = Countdown()
        self.countdown.update_countdown.connect(self.update_countdown)
        self.countdown.fully_counted_down.connect(self.begin_recording)
        self.trainer = Trainer()
        self.trainer.connect_armband()
        self.trainer.some_data_passer.connect(self.some_gesture_data_receiver)
        self.trainer.all_data_passer.connect(self.all_gesture_data_receiver)
        self.data_buffer = None

        # save button
        self.save = QPushButton("save", self.gb_record)
        #self.okay.clicked.connect(self.on_okay)
        button_width = 160
        button_height = 35
        self.save.setGeometry(6, 55, button_width, button_height)
        self.save.setStyleSheet('QPushButton {color: black;}')
        self.save.clicked.connect(self.save_buffer)

        # dropdown menu of available gestures to calibrate
        #self.gestures = self.get_possible_designs()
        self.gesture_box = QComboBox(self.gb_record)
        self.gesture_box.setGeometry(9,85,155,30)

        # history groupbox
        self.gb_record = QGroupBox("trainable estures", parent=self)
        self.gb_record.setGeometry(10,140,170,200)

        # history scrollpane
        self.gesture_history = QScrollArea(parent=self.gb_record)
        self.gesture_history.setGeometry(8,25,155,165)
        self.gesture_list = GestureList(self.gesture_history, self)
        self.gesture_list.setGeometry(0, 0, self.gesture_history.width(), self.gesture_history.height())
        self.gesture_list.itemClicked.connect(self.item_clicked)

        # populate the history scrollpane
        self.gesture_data = []
        if os.path.isfile("myo_armband/data_train.pkl"):
            with open("myo_armband/data_train.pkl", "rb") as infile:
                self.gesture_data = pickle.load(infile)
        self.item_ordering = []
        for item in self.gesture_data:
            self.item_ordering.append(item[7])
            list_item = QListWidgetItem(item[7])
            list_item.setData(Qt.UserRole, item)
            self.gesture_list.addItem(list_item)

        # populate the gesture_box combobox
        for item in self.gesture_data:
            self.gesture_box.addItem(item[7])

        # okay and cancel buttons
        self.okay = QPushButton("Okay", self)
        self.okay.clicked.connect(self.on_okay)
        button_width = 100
        button_height = 35
        self.okay.setGeometry((self.width()/2 - button_width/2)-50, self.height() - button_height, button_width, button_height)
        self.okay.setStyleSheet('QPushButton {color: black;}')

        self.cancel = QPushButton("Cancel", self)
        self.cancel.clicked.connect(self.on_cancel)
        button_width = 100
        button_height = 35
        self.cancel.setGeometry((self.width()/2 - button_width/2)+50, self.height() - button_height, button_width, button_height)
        self.cancel.setStyleSheet('QPushButton {color: black;}')

    def begin_countdown(self):
        self.countdown.start()

    def begin_recording(self):
        self.data_buffer = [[],[],[],[],[],[],[],"none"]
        self.trainer.start()

    def some_gesture_data_receiver(self, data, xlim):
        self.data_buffer[0].extend(data[0])
        self.data_buffer[1].extend(data[1])
        self.data_buffer[2].extend(data[2])
        self.data_buffer[3].extend(data[3])
        self.data_buffer[4].extend(data[4])
        self.data_buffer[5].extend(data[5])
        self.data_buffer[6].extend(data[6])
        self.graph.plot_gesture_data(self.data_buffer,xlim)

    def all_gesture_data_receiver(self, data):
        self.data_buffer = data
        self.data_buffer.append(str(self.gesture_box.currentText()))
        self.graph.plot_gesture_data(data)
        self.data_buffer = data

    def update_countdown(self):
        if self.countdown_label.text() == "":
            self.countdown_label.setText("3")
            self.countdown_label.show()
        elif self.countdown_label.text() == "3":
            self.countdown_label.setText("2")
        elif self.countdown_label.text() == "2":
            self.countdown_label.setText("1")
        else:
            self.countdown_label.setText("")
            self.countdown_label.hide()

    def update_gesture_train_data(self):
        print("updating")
        with open("myo_armband/data_train.pkl", "wb") as outfile:
            pickle.dump(self.gesture_data, outfile)

    def item_clicked(self):
        data = self.gesture_list.selectedItems()[0].data(Qt.UserRole)
        self.graph.plot_gesture_data(data)

    def save_buffer(self):
        new_data = []
        if self.data_buffer is not None:
            for data in self.gesture_data:
                if self.data_buffer[7] == data[7]:
                    new_data.append(self.data_buffer)
                else:
                    new_data.append(data)

        self.gesture_data = new_data
        self.data_buffer = None

        self.gesture_list.clear()
        for ordered_item_name in self.item_ordering:
            for item in self.gesture_data:
                if ordered_item_name == item[7]:
                    list_item = QListWidgetItem(item[7])
                    list_item.setData(Qt.UserRole, item)
                    self.gesture_list.addItem(list_item)

    def on_okay(self):
        self.update_gesture_train_data()
        self.close()

    def on_cancel(self):
        self.close()

class Countdown(QThread):

    update_countdown = pyqtSignal()
    fully_counted_down = pyqtSignal()

    def run(self):
        for i in range(3):
            self.update_countdown.emit()
            time.sleep(1)
        self.update_countdown.emit()
        self.fully_counted_down.emit()

class PlotWindow(FigureCanvas):

    def __init__(self, parent=None, width=8, height=6, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.subplots(6,1)
        fig.tight_layout()

        FigureCanvas.__init__(self, fig)
        self.fig=fig
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        self.plot_gesture_data([[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[0,1],"none"])

    def plot_gesture_data(self, data, xlim=None):
        times = data[6]
        norm_times = []
        for time in times:
            norm_times.append(time-times[0])

        self.axes[0].clear()
        self.axes[0].plot(norm_times,data[0])
        self.axes[0].set_ylabel("x accel")
        if xlim is not None:
            self.axes[0].set_xlim([0,xlim])

        self.axes[1].clear()
        self.axes[1].plot(norm_times,data[1])
        self.axes[1].set_ylabel("y accel")
        if xlim is not None:
            self.axes[1].set_xlim([0,xlim])

        self.axes[2].clear()
        self.axes[2].plot(norm_times,data[2])
        self.axes[2].set_ylabel("z accel")
        if xlim is not None:
            self.axes[2].set_xlim([0,xlim])

        self.axes[3].clear()
        self.axes[3].plot(norm_times,data[3])
        self.axes[3].set_ylabel("x rotate")
        if xlim is not None:
            self.axes[3].set_xlim([0,xlim])

        self.axes[4].clear()
        self.axes[4].plot(norm_times,data[4])
        self.axes[4].set_ylabel("y rotate")
        if xlim is not None:
            self.axes[4].set_xlim([0,xlim])

        self.axes[5].clear()
        self.axes[5].plot(norm_times,data[5])
        self.axes[5].set_ylabel("z rotate")
        if xlim is not None:
            self.axes[5].set_xlim([0,xlim])

        self.fig.tight_layout()
        self.draw()
        self.flush_events()

class GestureList(QListWidget):

    def __init__(self, parent, pane):
        super().__init__(parent=parent)
        self.pane = pane

    def keyPressEvent(self, event):
        if event.key() == 16777219: # previously Qt.Key_Delete
            self._del_item()

    def _del_item(self):
        for item in self.selectedItems():
            self.takeItem(self.row(item))
            item.data(Qt.UserRole).markForDeletion()
        self.pane.update_model()


#為了不出現 OMP: Error #15
import os
os.environ["KMP_DUPLICATE_LIB_OK"]  =  "TRUE"

import cv2
from matplotlib import pyplot as plt
import numpy as np
import imutils
import easyocr

img = cv2.imread('img/redCar.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# matplotlib需使用RGB
# plt.imshow(cv2.cvtColor(gray_img, cv2.COLOR_BGR2RGB))

#優化過濾
bfilter = cv2.bilateralFilter(gray_img,11,17,17)
#邊緣檢測
edged = cv2.Canny(bfilter,30,200)
# plt.imshow(cv2.cvtColor(edged, cv2.COLOR_BGR2RGB))

#找輪廓 由簡單的線條表示
keypoints = cv2.findContours(edged.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#imutils取輪廓並傳回
contours = imutils.grab_contours(keypoints)
#排序 由上到下找 返回前10個輪廓
contours = sorted(contours,key=cv2.contourArea,reverse=True)[:10]

#取四邊形位置
location = None
for contour in contours:
    #數字越高 越粗略計算圖形
    approx = cv2.approxPolyDP(contour,10,True)
    if len(approx) == 4:
        location = approx
        break
print(location)

#遮罩得到車牌 先創一個和圖形大小一樣的空白
mask = np.zeros(gray_img.shape, np.uint8)
#在圖像繪製輪廓
new_img = cv2.drawContours(mask,[location],0,255,-1)
#僅顯示位置的部位
new_img = cv2.bitwise_and(img,img,mask=mask)
# plt.imshow(cv2.cvtColor(new_img, cv2.COLOR_BGR2RGB))

#選取白色部位
(x,y) = np.where(mask==255)
#左上角
(x1,y1) = (np.min(x),np.min(y))
#右下角
(x2,y2) = (np.max(x),np.max(y))
#擷取車牌部位
cropped_img = gray_img[x1:x2+1,y1:y2+1]
plt.imshow(cv2.cvtColor(cropped_img, cv2.COLOR_BGR2RGB))

#使用的語言
reader = easyocr.Reader(['en'])
#讀取裁減後圖片(車牌)的文字
result = reader.readtext(cropped_img)
#print(result)

#車牌文字位置 從後面數來第二個
text = result[0][-2]
#字體
font = cv2.FONT_HERSHEY_SIMPLEX
#圖片 文字型態
res = cv2.putText(img, text=text, org=(approx[0][0][0],approx[1][0][1]+30),fontFace=font,fontScale=1,color=(255,255,0),thickness=2,lineType=cv2.LINE_AA)
#繪製矩形
res = cv2.rectangle(img,tuple(approx[0][0]),tuple(approx[2][0]),(255,255,0),3)
plt.imshow(cv2.cvtColor(res,cv2.COLOR_BGR2RGB))


'''
Created on 13/03/2013

@author: Kah
'''
import math

def middleIndices(data):
    '''Given a list of items, this will calculate the indices of items that
    contribute are in the middle.

    Returns the indices of the middle items in a list. Note that if the data
    contains an even number of items, then the list will contain the indices of
    the two middle items.'''

    length = len(data)
    if length == 0:
        return []

    if length == 1:
        return [0]

    index = int(math.floor(length / 2))
    if length % 2 == 1:
        return [index]

    return [index - 1, index]

def middleSplit(data):
    '''Splits a list of items in the middle. If there are an odd number of
    items, the middle item will not appear in either of the sublists.

    Returns the split as a single list containing the two sublists resulting
    from the split. Note that the data is returned if it contains less than
    two items.'''

    if len(data) < 2:
        return [data]

    refIndices = middleIndices(data)
    if len(refIndices) == 1:
        middle = refIndices[0]
        return [data[:middle], data[middle + 1:]]
    elif len(refIndices) == 2:
        middle = refIndices[1]
        return [data[:middle], data[middle:]]


"""
Reinforcement learning maze example.
Red rectangle:          explorer.
Black rectangles:       hells       [reward = -1].
Yellow bin circle:      paradise    [reward = +1].
All other states:       ground      [reward = 0].
This script is the main part which controls the update method of this example.
The RL is in RL_brain.py.
View more on my tutorial page: https://morvanzhou.github.io/tutorials/
"""
from maze_env import Maze
from RL_brain import QLearningTable
from TwentyFortyEight import Board
from time import sleep
from math import log
import pickle
import os

BRAIN_FILE = 'C:/Users/Nexor/Desktop/2048brain'

def mylog(item):
	if item == 0:
		return 0
	return int(log(item, 2))

def update():
	for episode in range(100000):
		# initial observation
		observation = env.reset()
		while True:
			# fresh env
			env.printGrid(True)
			# RL choose action based on observation
			flat_observation = [item for sublist in observation for item in sublist]
			action = RL.choose_action(str(observation).replace('[','').replace(']', ''))
			# RL take action and get next observation and reward
			observation_, reward, done = env.step(action)
			flat_observation_ = [item for sublist in observation_ for item in sublist]
			# RL learn from this transition
			RL.learn(str(flat_observation).replace('[','').replace(']', ''), action, reward, str(flat_observation_).replace('[','').replace(']', ''))
			# swap observation
			observation = observation_
			# break while loop when end of this episode
			if done:
				pickle.dump(RL, open(BRAIN_FILE, 'wb'))
				break
if __name__ == "__main__":
	env = Board()
	if os.path.exists(BRAIN_FILE):
		RL = pickle.load(open(BRAIN_FILE, 'rb'))
	else:
		RL = QLearningTable(actions=list(range(env.n_actions)))
	while True:
		update()


def caesar(teks, key):
    hasil = ' '
    data = open(teks, "r")
    for i in data.read():
        if i == ' ':
            hasil += i
        elif i.islower():
            hasil += chr((ord(i) + key - 97) % 26 + 97)
        else:
            hasil += chr((ord(i) + key - 65) % 26 + 65)
    data.close()
    enc = open(teks + ".encrypt", "w")
    enc.write(hasil)
    enc.close()
    print('\nFile enkripsi : {}.encrypt'.format(teks))

teks = input('Nama file yang ingin di enkripsi : ')
key = int(input('Input key : '))
caesar(teks, key)


import os
import datetime

from flask import Flask, render_template
from flask_cors import CORS

from . import db
from . import commands
from . import blueprints
from .metadata import KEY_AREA_TYPES, OTHER_CODES, AREA_TYPES
from .controllers.areatypes import area_types_count

def get_es_url(default):

    potential_env_vars = [
        "ELASTICSEARCH_URL",
        "ES_URL",
        "BONSAI_URL"
    ]
    for e_v in potential_env_vars:
        if os.environ.get(e_v):
            return os.environ.get(e_v)
    return default

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        ES_URL=get_es_url('http://localhost:9200'),
        ES_INDEX=os.environ.get('ES_INDEX', 'postcodes'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    db.init_app(app)
    commands.init_app(app)
    CORS(app)

    # template helpers
    @app.context_processor
    def inject_now():
        return dict(
            now=datetime.datetime.now(),
            key_area_types=KEY_AREA_TYPES,
            other_codes=OTHER_CODES,
            area_types=AREA_TYPES,
        )

    # routes and blueprints
    @app.route('/')
    def index():
        ats = area_types_count(db.get_db())
        return render_template('index.html.j2', result=ats)

    @app.route('/about')
    def about():
        return render_template('about.html.j2')

    blueprints.init_app(app)

    return app


#  Copyright (c) 2020 Xcodz.
#  All Rights Reserved.
import os

import requests
import configparser
import argparse
import shutil

if __name__ == '__main__':
    parser = argparse.ArgumentParser("Denver API Installer",
                                     description="This is software installer for Denver API, to use it you require a "
                                                 "active Internet Access")
    parser.add_argument("-c", "--conf", metavar="ConfigurationFile", action="store", required=False,
                        default="./installer_info/dn.ini")
    parser.add_argument("-d", "--dir", action="store", required=False, default=".", metavar="DirectoryToInstall")
    args = parser.parse_args()

    # Configuration Loading
    configuration = configparser.ConfigParser(interpolation=None)
    configuration.read_string(open(args.conf).read(), "DenverConfiguration")
    configuration = configuration["Denver"]

    # User Interface
    print("Powered by", configuration["DownloadSite"])
    print("\nPreparing to get File")
    url = str(configuration["DownloadLink"])
    print(f"Downloading \"{url}\"")
    page = requests.get(url)
    print("Writing \"Denver.zip\"")
    with open("Denver.zip", "w+b") as file:
        file.write(page.content)
    print("Unpacking \"Denver.zip\"")
    shutil.unpack_archive("Denver.zip", args.dir)
    print("Deleting \"Denver.zip\"")
    os.remove("Denver.zip")
    print("Target Complete")


# -*- coding: utf-8 -*-
# @Author: shubham
# @Date:   2017-04-09 03:00:40
# @Last Modified by:   shubham
# @Last Modified time: 2017-04-09 03:37:27

def non_decreasing(n):
	n = str(n)
	return all(x<=y for x, y in zip(n, n[1:]))

def tidy(n):
	n = list(map(int, str(n)))
	for idx in range(len(n)-1):
		if n[idx] > n[idx+1]:
			break

	n[idx] -= 1
	for i in range(idx+1, len(n)):
		n[i] = 9

	return int(''.join(map(str, n)))

def main():
	for t in range(int(input())):
		n = int(input())
		while not non_decreasing(n):
			n = tidy(n)
		print('Case #{}: {}'.format(t+1, n))

if __name__ == '__main__':
	main()


__author__ = 'N1CK'

#1
a = [int(i) for i in input().split()]
for i in range(len(a)):
    a[i] = int(a[i])
for k in range(len(a)):
    if len(a) == 1:
        print(a[k])
    elif k == 0:
        n1 = a[len(a) - 1]
        n2 = a[k + 1]
        summary = n1 + n2
        print(summary, end=' ')
    elif k == len(a) - 1:
        n1 = a[k - 1]
        n2 = a[0]
        summary = n1 + n2
        print(summary, end=' ')
    else:
        n1 = a[k - 1]
        n2 = a[k + 1]
        summary = n1 + n2
        print(summary, end=' ')

#2
a = [int(i) for i in input().split()]
a.sort()
count = 0
a1 = [0]
if len(a) != 1:
    for i in range(len(a) - 1):
        if a[i] == a[i + 1]:
            count += 1
            if count > 0:
                a1 += [a[i]]
            count = 0
a1 += [10000000000002]
for i in range(2, len(a1)):
    if a1[i] != a1[i - 1]:
        print(a1[i - 1], end=' ')


#!/usr/bin/env python3

import os
import tempfile
from collections import Counter
from pathlib import Path
import utils.console as console
import utils.config as cfg
from grabber.facebook import FBGrabber
from grabber.google import GoogleGrabber
from grabber.yandex import YandexGrabber
from grabber.imageraider import ImageRaiderGrabber
from face_recog import FaceRecog
from instaLooter import InstaLooter
from report.report import makeReport

def presentResult(predictions):
    argmax = Counter(predictions)
    console.section("Result")
    (most_common_str, _) = argmax.most_common(n=1)[0]
    console.task("Google says it could be: {0}".format(most_common_str))

def filterInstaLinks(links):
    r = []
    for l in links:
        if "instagram.com" in l:
            r.append(l)
    return r

def parseInstaUsername(links):
    usernames = []
    for l in links:
        a = l[8:]
        a = a.split('/')
        if len(a) >= 2:
            usernames.append(a[1])
        else:
            console.subfailure('Error parsing {0}'.format(l))
    return usernames

def validateInstaUser(username, num_jitters):
    images = getInstaLinks(username)
    r = FaceRecog(username, images, num_jitters=num_jitters)
    r.loadKnown(username)
    profile_links, _ = r.getValidLinksAndImg(username)
    return len(profile_links) > 0

def getInstaLinks(username):
    looter = InstaLooter(profile=username)
    images = []
    i = 0
    for media in looter.medias():
        if i > cfg.instaLimit():
            break
        if not media['is_video']:
            console.subtask("Got Image: {0}".format(media['display_src'].strip()[:90]))
            images.append(media['display_src'])
            i = i + 1
    return images

def main():
    # collect user input
    console.prompt('Enter the persons name to find on FB: ')
    name = input('')

    console.prompt('How many jitters, higher is better [max 100]: ')
    num_jitters = input('')
    num_jitters = int(num_jitters)
    if num_jitters > 100:
        console.subfailure('Dude wtf?!')
        num_jitters = 100
        console.subfailure('Using 100 jitters...')

    # grab profile urls
    f = FBGrabber(name)
    f.grabData()

    # do face recognition on those profile images
    r = FaceRecog(f.getProfileLinks(), f.getProfileImages(), num_jitters=num_jitters)
    r.loadKnown(name)

    profile_links, profile_imgs = r.getValidLinksAndImg(name)
    console.section('Result')
    console.task('Found the following Profiles:')
    for i in range(len(profile_links)):
        console.subtask(profile_links[i])

    # google reverse image search on profile pics
    g = GoogleGrabber()
    for img in profile_imgs:
        g.collectLinks(img)

    # google reverse image search on reference pic
    g.collectLinksLocal()
    rev_links, predictions = g.finish()

    yandex = YandexGrabber()
    for img in profile_imgs:
        yandex.collectLinks(img)

    #add to rev_links
    for e in yandex.finish():
        rev_links.append(e)
    rev_links = list(set(rev_links))

    instaNames = parseInstaUsername(filterInstaLinks(rev_links))
    validatedInstaNames = []
    console.section("Validating Instagram Profiles")
    for un in instaNames:
        console.task("Validating Profile: '{0}'".format(un))
        if validateInstaUser(un, num_jitters):
            validatedInstaNames.append(un)

    raider_img_list = profile_imgs
    for v in validatedInstaNames:
        l = getInstaLinks(v)
        for li in l:
            raider_img_list.append(li)

    if len(raider_img_list) <= 0:
        console.failure('No Links founds...')
    else:
        raider = ImageRaiderGrabber()
        raider.insertImageLinks(raider_img_list)
        raider.downloadCSV()
        raider_links = raider.processCSV()
        for raider_link in raider_links:
            rev_links.append(raider_link)

    rev_links = list(set(rev_links))
    predictions = list(set(predictions))
    console.section('Links')
    print(rev_links)
    console.section('Predictions')
    try:
        predictions = [x.lower() for x in predictions]
    except:
        predictions = []
    print(predictions)
    presentResult(predictions)

    console.section("Creating PDF Report")
    makeReport(name, rev_links, predictions, validatedInstaNames)

    p = os.path.join(tempfile.gettempdir(), 'imageraider')
    if os.path.isdir(p):
        pathlist = Path(p).glob('**/*')
        for path in pathlist:
            s_p = str(path)
            os.remove(s_p)
    console.task("KTHXBYE")

if __name__ == "__main__":
    console.banner()
    main()


# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
"""

import os
import pickle
from multiprocessing import Pool

import datasets
from datasets import Dataset as HFDataset
from datasets import load_dataset
from loguru import logger
from torch.utils.data import Dataset
from tqdm.auto import tqdm

PROMPT_DICT = {
    "prompt_input": (
        "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"
        "### Instruction:\n{instruction}\n{input_text}\n\n### Response:"
    ),
    "prompt_no_input": (
        "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"
        "### Instruction:\n{instruction}\n\n### Response:"
    ),
}

def preprocess_data(data):
    instruction, input_text, target_text, tokenizer, args = data

    if input_text:
        prompt = PROMPT_DICT["prompt_input"].format(instruction=instruction, input_text=input_text)
    else:
        prompt = PROMPT_DICT["prompt_no_input"].format(instruction=instruction)

    full_prompt = prompt + target_text + tokenizer.eos_token
    full_max_length = args.max_seq_length + args.max_length
    example = tokenizer(
        full_prompt,
        truncation=True,
        max_length=full_max_length,
        padding=False,
        add_special_tokens=False
    )
    example["labels"] = example["input_ids"].copy()
    if args.is_chat_task:
        user_example = tokenizer(
            prompt,
            truncation=True,
            max_length=args.max_seq_length,
            padding=False,
            add_special_tokens=False
        )
        user_prompt_len = len(user_example["input_ids"])
        # set labels to full max length to adjust for DataCollatorForSeq2Seq padding
        example["labels"] = [-100] * (full_max_length - len(example['labels']) + user_prompt_len) + \
                            example["labels"][user_prompt_len:]

    return example

def preprocess_batch_for_hf_dataset(example, tokenizer, args):
    data = (example["instruction"], example["input"], example["output"], tokenizer, args)
    example = preprocess_data(data)
    return example

def load_hf_dataset(data, tokenizer, args, mode):
    if isinstance(data, str):
        if data.endswith('.json') or data.endswith('.jsonl'):
            dataset = load_dataset("json", data_files=data)
        elif os.path.isdir(data):
            dataset = datasets.load_from_disk(data)
        else:
            dataset = load_dataset(
                data,
                download_mode="force_redownload"
                if args.reprocess_input_data
                else "reuse_dataset_if_exists",
            )
        # This is not necessarily a train dataset. The datasets library insists on calling it train.
        dataset = dataset['train']
        if mode == 'dev' and args.max_eval_samples is not None:
            max_eval_samples = min(len(dataset), args.max_eval_samples)
            dataset = dataset.select(range(max_eval_samples))
    else:
        dataset = HFDataset.from_pandas(data)

    dataset = dataset.shuffle().map(
        lambda x: preprocess_batch_for_hf_dataset(x, tokenizer=tokenizer, args=args),
        batched=False, remove_columns=dataset.column_names
    ).filter(lambda x: len(x['input_ids']) > 0)

    return dataset

class LlamaDataset(Dataset):
    def __init__(self, tokenizer, args, data, mode):
        cached_features_file = os.path.join(
            args.cache_dir,
            args.model_name.replace("/", "_")
            + "_cached_"
            + str(args.max_seq_length)
            + str(len(data)),
        )

        if os.path.exists(cached_features_file) and (
                (not args.reprocess_input_data and not args.no_cache)
                or (mode == "dev" and args.use_cached_eval_features and not args.no_cache)
        ):
            logger.info(" Loading features from cached file %s" % cached_features_file)
            with open(cached_features_file, "rb") as handle:
                self.examples = pickle.load(handle)
        else:
            logger.info(" Creating features from dataset file at %s" % args.cache_dir)

            data = [
                (instruction, input_text, target_text, tokenizer, args)
                for instruction, input_text, target_text in zip(
                    data["instruction"], data["input"], data["output"]
                )
            ]

            if (mode == "train" and args.use_multiprocessing) or (
                    mode == "dev" and args.use_multiprocessing_for_evaluation
            ):
                if args.multiprocessing_chunksize == -1:
                    chunksize = max(len(data) // (args.process_count * 2), 500)
                else:
                    chunksize = args.multiprocessing_chunksize

                with Pool(args.process_count) as p:
                    self.examples = list(
                        tqdm(
                            p.imap(preprocess_data, data, chunksize=chunksize),
                            total=len(data),
                            disable=args.silent,
                        )
                    )
            else:
                self.examples = [preprocess_data(d) for d in tqdm(data, disable=args.silent)]
            if not args.no_cache:
                logger.info(" Saving features into cached file %s" % cached_features_file)
                with open(cached_features_file, "wb") as handle:
                    pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL)

    def __len__(self):
        return len(self.examples)

    def __getitem__(self, index):
        return self.examples[index]


from . import accepts
from . import expects

import types

class spec(object) :

    @staticmethod
    def populate_values(ret, data) :
        obj = ret() if type(ret) is type else ret
        cls_names = obj.__class__.__dict__.keys()
        obj_names = obj.__dict__.keys()

        for k,v in data.items() :
            if k in cls_names :
                if isinstance(obj.__class__.__dict__[k], expects.expect) :
                    obj.__class__.__dict__[k].__set__(obj, v)
                elif k in obj.__class__.__dict__ or k in obj.__dict__ :
                    pass
                else :
                    raise AttributeError('Can not set (%s, %s)'%(k,v))
            else :
                setattr(obj, k, v)

        return obj

    @staticmethod
    def dump_values(instance) :
        d = dict()
        cls_data = instance.__class__.__dict__.items()
        obj_data = instance.__dict__.items()

        for k,v in cls_data :
            if k.startswith('_') or type(v) in (type, types.FunctionType) : continue
            d[k] = getattr(instance, k)
        return d

    def __init__(self) :
        pass

    def validate(self) :
        # expect will be in class; its func decorator
        for name,fn in self.__class__.__dict__.items() :
            if not isinstance(fn, expects.expect) : continue
            if not fn.required : continue
            if fn.__get__(self) is None :
                return False
        return True

    def populate(self, data):
        spec.populate_values(self, data)

    def dump(self) :
        return spec.dump_values(self)


length  =int(input())
ctr =0
answers = []
choices = [0,1,2,3,4,5,6,7,8,9]
while ctr < length:
    a = input()
    b = a.split(" ")
    ctr2 = 0
    while ctr2 < len(choices):
        if    ( str(choices[ctr2]) not in b):
            answers.append(choices[ctr2] )
        ctr2+=1
    ctr+=1
for z in answers:
    print(str(z), end='')


import matplotlib.pyplot as plt
from MontaVetores import RetornaVetoresComMedias as vetoresMedia

#RetornaVetoresComMedias('3','2')

x = [] #tempo
y1 = [] # s1-TX-Port1
y2 = [] # s1-TX-Port2
y3 = [] # s1-TX-Port3
y4 = [] #s3-RX-Port1
y5 = [] #s3-RX-Port2
#y3 = [] #media da saida rx R3

#y4 = [] #Saida 1 do iperf
#y5 = [] #Saida 2 do Iperf
#y6 = [] #Saida 3 do Iperf
#y7 = [] #Saida 4 do Iperf

cenario = '3'
teste = '2'
#y1,y2,y3,y4,y5 = vetores('1','1','15') #Teste, Cenario, num_arq Onde Teste=0,1,2=Iperf,  Cenario=1,2,3, num_arq=[1,...,30]
y1,y2,y3,y4,y5 = vetoresMedia(cenario,teste) #Cenario,Tese    Onde Cenario=1,2,3 Teste=0,1,2=Iperf,

for i in range(0,len(y1)): #TempoCerto
    x.append(i)
    #y1.append(int((dados[i][0])*1**(-6)))
    #y2.append(int((dados[i][1])*1**(-6
    y1[i] = y1[i]*0.000008
    y2[i] = y2[i]*0.000008
    y3[i] = y3[i]*0.000008
    #y1.append(int(dados[i][0]*0.000008))
    #y2.append(int(dados[i][1]*0.000008))
    #y3.append(int(dados[i][1]*0.000008))
#print(len(y1))
'''
somatorio = 0
for i in y1:
    somatorio = somatorio + i
media = int(somatorio/len(y1))
#print(media)
for i in range(0,len(y1)):
    y3.append(media)
#print(y3) #Media da saida do VLC

#vet_temp1 = obtemVetorIperf(path2) #Vetor Iperf
#vet_temp2 = obtemVetorIperf(path3) #Vetor Iperf
#vet_temp3 = obtemVetorIperf(path4) #Vetor Iperf
#vet_temp4 = obtemVetorIperf(path5) #Vetor Iperf

#print(len(vet_temp1)
'''
'''
Reduzindo os vetores para tam 112
'''
'''
aux1 = []
aux2 = []
aux3 = []
aux4 = []
for i in range(0,112):
    aux1.append(x[i])
    aux2.append(y1[i])
    aux3.append(y2[i])
    aux4.append(y3[i])
x = aux1
y1 = aux2
y2 = aux3
y3 = aux4
'''
'''
Fim da reducao
'''

#for i in range(0,112): #Copia o vetor de iperf ate o tamanho de y1 e y2
    #y4.append(int(vet_temp1[i])*125000) #Converte Mbits em Bytes
    #y5.append(int(vet_temp2[i])*125000) #Converte Mbits em Bytes
    #y6.append(int(vet_temp3[i])*125000) #Converte Mbits em Bytes
    #y7.append(int(vet_temp4[i])*125000) #Converte Mbits em Bytes

#print(y4)
#print(y1)

fig,ax1 = plt.subplots()
if teste == '0':
    ax1.plot(x,y1,'r-',linewidth=1.5,linestyle='-', label=u'Video Out')
elif teste == '1':
    ax1.plot(x,y1,'r-',linewidth=1.5,linestyle='-', label=u'Video Out')
    ax1.plot(x,y2,'g-',linewidth=1.5,linestyle='-',label=u'iPerf 1 Out' )
else:
    ax1.plot(x,y1,'r-',linewidth=1.5,linestyle='-', label=u'Video Out')
    ax1.plot(x,y2,'g-',linewidth=1.5,linestyle='-',label=u'iPerf 1 Out' )
    ax1.plot(x,y3,'y-',linewidth=1.5,linestyle='-',label=u'iPerf 2 Out')
#ax1.plot(x,y4,'b',linewidth=1.5,linestyle='-',label='Iperf 1')
#ax1.plot(x,y5,'g',linewidth=1.5,linestyle='-',label='Iperf 2')
#ax1.plot(x,y6,'y',linewidth=1.5,linestyle='-',label='Iperf 3')
#Propriedade do Graficos
#ax1([0,len(x),0,1000])
#Limites do grafico
ax1.set_ylim(0,25)
ax1.set_xlim(0,180) #O tempo correto eh 205

'''
ax2 = fig.add_subplot(1,2,2)
ax2.plot(x,y4,'b',linewidth=1.5,linestyle='-',label='Iperf 1')
#ax2.plot(x,y5,'g',linewidth=1.5,linestyle='-',label='Iperf 2')
#ax2.plot(x,y6,'y',linewidth=1.5,linestyle='-',label='Iperf 3')
#ax2.plot(x,y7,'r',linewidth=1.5,linestyle='-',label='Iperf 4')
#Limites do Grafico
ax2.set_ylim(1600000000,2200000000)
ax2.set_xlim(0,112)
'''

##Propriedades do Grafico
#ax1.tick_params(axis='x',colors='c')
#ax1.tick_params(axis='y',colors='c')
#ax2.tick_params(axis='x',colors='c')
#ax2.tick_params(axis='y',colors='c')

#ax1.yaxis.label.set_color('c')
#ax1.xaxis.label.set_color('c')
#ax2.yaxis.label.set_color('c')
#ax2.xaxis.label.set_color('c')

ax1.legend(loc='upper right') #Local das legendas
#ax2.legend(loc='upper right') #Local das Legendas

#ax1.yaxis.label.set_color('c')
#ax1.xaxis.label.set_color('c')

ax1.set_xlabel('Time(s)',fontsize=14)
ax1.set_ylabel('Megabits',fontsize=16)
#ax2.set_title('Grafico Iperf')
#ax2.set_xlabel('tempo(s)')
#ax2.set_ylabel('Bytes')

plt.show()

'''
if teste == '0':
    plt.savefig('/home/bruno/ryu/Bruno/Resultados/Graficos/Cenario'+cenario+'_SemIperf.png')
elif teste == '1':
    plt.savefig('/home/bruno/ryu/Bruno/Resultados/Graficos/Cenario'+cenario+'_1Iperf.png')
else:
    plt.savefig('/home/bruno/ryu/Bruno/Resultados/Graficos/Cenario'+cenario+'_2Iperf.png')
'''


"""Sensor for Shelly."""
import aioshelly

from homeassistant.components import sensor
from homeassistant.const import (
    ELECTRICAL_CURRENT_AMPERE,
    ENERGY_KILO_WATT_HOUR,
    POWER_WATT,
    TEMP_CELSIUS,
    TEMP_FAHRENHEIT,
    UNIT_PERCENTAGE,
    VOLT,
)
from homeassistant.helpers.entity import Entity

from . import ShellyBlockEntity, ShellyDeviceWrapper
from .const import DOMAIN

SENSORS = {
    "battery": [UNIT_PERCENTAGE, sensor.DEVICE_CLASS_BATTERY],
    "current": [ELECTRICAL_CURRENT_AMPERE, sensor.DEVICE_CLASS_CURRENT],
    "deviceTemp": [None, sensor.DEVICE_CLASS_TEMPERATURE],
    "energy": [ENERGY_KILO_WATT_HOUR, sensor.DEVICE_CLASS_ENERGY],
    "energyReturned": [ENERGY_KILO_WATT_HOUR, sensor.DEVICE_CLASS_ENERGY],
    "extTemp": [None, sensor.DEVICE_CLASS_TEMPERATURE],
    "humidity": [UNIT_PERCENTAGE, sensor.DEVICE_CLASS_HUMIDITY],
    "overpowerValue": [POWER_WATT, sensor.DEVICE_CLASS_POWER],
    "power": [POWER_WATT, sensor.DEVICE_CLASS_POWER],
    "voltage": [VOLT, sensor.DEVICE_CLASS_VOLTAGE],
}

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up sensors for device."""
    wrapper = hass.data[DOMAIN][config_entry.entry_id]
    sensors = []

    for block in wrapper.device.blocks:
        for attr in SENSORS:
            if not hasattr(block, attr):
                continue

            sensors.append(ShellySensor(wrapper, block, attr))

    if sensors:
        async_add_entities(sensors)

class ShellySensor(ShellyBlockEntity, Entity):
    """Switch that controls a relay block on Shelly devices."""

    def __init__(
        self,
        wrapper: ShellyDeviceWrapper,
        block: aioshelly.Block,
        attribute: str,
    ) -> None:
        """Initialize sensor."""
        super().__init__(wrapper, block)
        self.attribute = attribute
        unit, device_class = SENSORS[attribute]
        self.info = block.info(attribute)

        if (
            self.info[aioshelly.BLOCK_VALUE_TYPE]
            == aioshelly.BLOCK_VALUE_TYPE_TEMPERATURE
        ):
            if self.info[aioshelly.BLOCK_VALUE_UNIT] == "C":
                unit = TEMP_CELSIUS
            else:
                unit = TEMP_FAHRENHEIT
        elif self.info[aioshelly.BLOCK_VALUE_TYPE] == aioshelly.BLOCK_VALUE_TYPE_ENERGY:
            unit = ENERGY_KILO_WATT_HOUR

        self._unit = unit
        self._device_class = device_class

    @property
    def unique_id(self):
        """Return unique ID of entity."""
        return f"{super().unique_id}-{self.attribute}"

    @property
    def name(self):
        """Name of sensor."""
        return f"{self.wrapper.name} - {self.attribute}"

    @property
    def state(self):
        """Value of sensor."""
        if self.attribute in [
            "deviceTemp",
            "extTemp",
            "humidity",
            "overpowerValue",
            "power",
        ]:
            return round(getattr(self.block, self.attribute), 1)
        # Energy unit change from Wmin or Wh to kWh
        if self.info[aioshelly.BLOCK_VALUE_UNIT] == "Wmin":
            return round(getattr(self.block, self.attribute) / 60 / 1000, 2)
        if self.info[aioshelly.BLOCK_VALUE_UNIT] == "Wh":
            return round(getattr(self.block, self.attribute) / 1000, 2)
        return getattr(self.block, self.attribute)

    @property
    def unit_of_measurement(self):
        """Return unit of sensor."""
        return self._unit

    @property
    def device_class(self):
        """Device class of sensor."""
        return self._device_class


"""Module contains routes, used for problem table."""
import json
import hashlib
import time
import os

from flask import request, jsonify, Response
from flask_login import current_user

from ecomap import validator
from ecomap.app import app, logger
from ecomap.db import util as db

@app.route('/api/problems')
def problems():
    """Handler for sending short data about all problem stored in db.
    Used by Google Map instance
    :return: list of problems with id, title, latitude, longitude,
    problem type, status and date of creation
    """
    problem_tuple = db.get_all_problems()
    parsed_json = []
    if problem_tuple:
        for problem in problem_tuple:
            parsed_json.append({
                'problem_id': problem[0], 'title': problem[1],
                'latitude': problem[2], 'longitude': problem[3],
                'problem_type_Id': problem[4], 'status': problem[5],
                'date': problem[6]})
    return Response(json.dumps(parsed_json), mimetype='application/json')

@app.route('/api/problem_detailed_info/<int:problem_id>', methods=['GET'])
def detailed_problem(problem_id):
    """This method returns json object with detailed problem data.
    :params problem_id - id of selected problem
    :return json with detailed info about problem
    """
    problem_data = db.get_problem_by_id(problem_id)
    activities_data = db.get_activity_by_problem_id(problem_id)
    photos_data = db.get_problem_photos(problem_id)
    photos = []
    activities = {}

    if problem_data:
        problems = {
            'problem_id': problem_data[0], 'title': problem_data[1],
            'content': problem_data[2], 'proposal': problem_data[3],
            'severity': problem_data[4], 'status': problem_data[5],
            'latitude': problem_data[6], 'longitude': problem_data[7],
            'problem_type_id': problem_data[8], 'date': problem_data[9]}
    else:
        return jsonify({'message': ' resource not exists'}), 404

    if activities_data:
        activities = {
            'created_date': activities_data[0],
            'problem_id': activities_data[1],
            'user_id': activities_data[2],
            'activity_type': activities_data[3]}
    if photos_data:
        for photo_data in photos_data:
            photos.append({
                'url': photo_data[0],
                'description': photo_data[1],
                'user_id': photo_data[2]})

    response = Response(json.dumps([[problems], [activities], photos]),
                        mimetype='application/json')
    return response

@app.route('/api/problem_post', methods=['POST'])
def post_problem():
    """Function which adds data from problem form to DB.
    :return: If request data is invalid:
    {'status': False, 'error': [list of errors]}, 400
    If all ok:
    {'added_problem': 'problem_title'
    'problem_id': 'problem_id'}
    """
    if request.method == 'POST' and request.form:
        data = request.form
        logger.warning(json.dumps(request.form))
        logger.info(data)
        valid = validator.problem_post(data)
        if valid['status']:
            logger.debug('Checks problem post validation. %s', valid)
            user_id = current_user.uid
            posted_date = int(time.time())
            last_id = db.problem_post(data['title'],
                                      data['content'],
                                      data['proposal'],
                                      data['latitude'],
                                      data['longitude'],
                                      data['type'],
                                      posted_date,
                                      user_id)
            if last_id:
                db.problem_activity_post(last_id, posted_date,
                                         user_id)
            logger.debug('New problem post was created with id %s', last_id)
            response = jsonify(added_problem=data['title'],
                               problem_id=last_id)
        else:
            response = Response(json.dumps(valid),
                                mimetype='application/json'), 400
        return response

@app.route('/api/usersProblem/<int:user_id>', methods=['GET'])
def get_user_problems(user_id):
    """This method retrieves all user's problem from db.
        :returns list of user's problem represented with next objects:
        {"id": 190,
         "title": "name",
         "latitude": 51.419765,
         "longitude": 29.520264,
         "problem_type_id": 1,
         "status": 0,
         "date": "2015-02-24T14:27:22.000Z",
         "severity": '3',
         "is_enabled": 1
        }
    """
    problems_list = []
    problem_tuple = db.get_user_problems(user_id)
    logger.info(problem_tuple)
    for problem in problem_tuple:
        problems_list.append({'id': problem[0],
                              'title': problem[1],
                              'latitude': problem[2],
                              'logitude': problem[3],
                              'problem_type_id': problem[4],
                              'status': problem[5],
                              'date': problem[6] * 1000,
                              'severity': problem[8],
                              'is_enabled': problem[7]})
    return Response(json.dumps(problems_list), mimetype='application/json')

@app.route('/api/photo/<int:problem_id>', methods=['POST'])
def problem_photo(problem_id):
    """ Connected with problem_post. Creating for uploading photos
        with problem.
        :return: json with success if photo have been uploaded
    """
    response = jsonify(), 400
    extension = '.png'
    static_url = '/uploads/problems/%s/' % problem_id
    f_path = os.environ['STATICROOT'] + static_url
    user_id = current_user.uid
    now = time.time()*100000
    unique_key = (int(now)+user_id)
    hashed_name = hashlib.md5(str(unique_key))
    f_name = '%s%s' % (hashed_name.hexdigest(), extension)

    if request.method == 'POST':
        problem_img = request.files['file']
        photo_descr = request.form['description']

        if problem_img and validator.validate_image_file(problem_img):
            if not os.path.exists(f_path):
                os.makedirs(os.path.dirname('%s%s' % (f_path, f_name)))
            problem_img.save(os.path.join(f_path, f_name))
            img_path = '%s%s' % (static_url, f_name)
            db.add_problem_photo(problem_id, img_path, photo_descr, user_id)
            response = json.dumps({'added_file': img_path})
        else:
            response = jsonify(error='error with import file'), 400
    return response


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

from google.appengine.ext import ndb

# The Python Markdown implementation by Waylan Limberg
from markdown import markdown
# The GitHub-Flavored Markdown
from gfm import gfm

class Member(ndb.Model):
	RANKS = [
		{
			# 0
			'name': 'Cadet',
			'abbr': 'Cdt.',
			'disp': ''
		}, {
			# 1
			'name': 'Ensign',
			'abbr': 'Ens.',
			'disp': unichr(9679) # ●
		}, {
			# 2
			'name': 'Lieutenant, Junior Grade',
			'abbr': 'Lt. J.G.',
			'disp': unichr(9675) + unichr(9679) # ○●
		}, {
			# 3
			'name': 'Lieutenant',
			'abbr': 'Lt.',
			'disp': unichr(9679) + unichr(9679) # ●●
		}, {
			# 4
			'name': 'Lieutenant Commander',
			'abbr': 'Lt. Cmdr.',
			'disp': unichr(9675) + unichr(9679) + unichr(9679) # ○●●
		}, {
			# 5
			'name': 'Commander',
			'abbr': 'Cmdr.',
			'disp': unichr(9679) + unichr(9679) + unichr(9679) # ●●●
		}, {
			# 6
			'name': 'Captain',
			'abbr': 'Capt.',
			'disp': unichr(9679) + unichr(9679) + unichr(9679) + unichr(9679) # ●●●●
		}, {
			# 7
			'name': 'Commodore',
			'abbr': 'Cmdre.',
			'disp': '[' + unichr(9679) + ']' # [●]
		}, {
			# 8
			'name': 'Rear Admiral',
			'abbr': 'Adm.',
			'disp': '[' + unichr(9679) + unichr(9679) + ']' # [●●]
		}, {
			# 9
			'name': 'Vice Admiral',
			'abbr': 'Adm.',
			'disp': '[' + unichr(9679) + unichr(9679) + unichr(9679) + ']' # [●●●]
		}, {
			# 10
			'name': 'Admiral',
			'abbr': 'Adm.',
			'disp': '[' + unichr(9679) + unichr(9679) + unichr(9679) + unichr(9679) + ']' # [●●●●]
		}, {
			# 11
			'name': 'Fleet Admiral',
			'abbr': 'Adm.',
			'disp': '[' + unichr(9679) + unichr(9679) + unichr(9679) + unichr(9679) + unichr(9679) + ']' # [●●●●●]
		}
	]

	id = ndb.StringProperty() # UUID
	show = ndb.BooleanProperty() # Show the user on the public site?
	name = ndb.StringProperty()
	dce = ndb.StringProperty() # None for people who were never RIT students
	mailing_list = ndb.BooleanProperty()
	current_student = ndb.BooleanProperty()
	email = ndb.StringProperty() # Member's preferred e-mail
	semesters_paid = ndb.StringProperty(repeated=True)
	never_paid = ndb.ComputedProperty(lambda self: len(self.semesters_paid) == 0) # Thank you to bossylobster and wag2639 on StackOverflow.
	committee_rank = ndb.BooleanProperty()
	merit_rank1 = ndb.BooleanProperty()
	merit_rank2 = ndb.BooleanProperty()

	def get_missions(self):
		return Mission.query(Mission.runners == self.id).order(-Mission.date).fetch(limit=None)

	def get_rank(self):
		# Cadets cannot earn ranks
		if len(self.semesters_paid) == 0:
			return 0

		rank = 1

		# Longevity
		if len(self.semesters_paid) >= 4:
			rank += 1

		# Led weekly mission
		if Mission.query(Mission.runners == self.id, Mission.type == 0).count(limit=1) != 0:
			rank += 1

		# Volunteered with special mission or committee
		if self.committee_rank or Mission.query(Mission.runners == self.id, Mission.type == 1).count(limit=1) != 0:
			rank += 1

		# Merit ranks
		if self.merit_rank1:
			rank += 1
		if self.merit_rank2:
			rank += 1

		# Voted captain
		if BridgeCrew.query(BridgeCrew.captain == self.id).count(limit=1) != 0:
			rank = 6

		# Alumni ranks
		if not self.current_student:
			if rank == 6:
				# Captains become rear admirals
				rank = 8
			else:
				# Non-captains become commodores
				rank = 7

		# Was an admiral (advisor)
		if BridgeCrew.query(BridgeCrew.admiral == self.id).count(limit=1) != 0:
			rank = 10

		return rank

	def get_rank_disp(self):
		return Member.RANKS[self.rank]['disp']

	def get_rank_name(self):
		return Member.RANKS[self.rank]['name']

	def get_name_with_rank(self):
		return Member.RANKS[self.rank]['abbr'] + ' ' + self.name

	missions = property(get_missions)
	rank = property(get_rank)
	rank_disp = property(get_rank_disp)
	rank_name = property(get_rank_name)
	name_with_rank = property(get_name_with_rank)

class BridgeCrew(ndb.Model):
	start = ndb.DateTimeProperty()
	end = ndb.DateTimeProperty()
	admiral = ndb.StringProperty() # Bridge crew member entries are member UUIDs
	captain = ndb.StringProperty()
	first_officer = ndb.StringProperty()
	ops = ndb.StringProperty()
	comms = ndb.StringProperty()
	engi = ndb.StringProperty()

	def get_admiral_name(self):
		admiral_member = Member.query(Member.id == self.admiral).get()
		return admiral_member.name

	def get_captain_name(self):
		captain_member = Member.query(Member.id == self.captain).get()
		return captain_member.name

	def get_first_officer_name(self):
		first_officer_member = Member.query(Member.id == self.first_officer).get()
		return first_officer_member.name

	def get_ops_name(self):
		ops_member = Member.query(Member.id == self.ops).get()
		return ops_member.name

	def get_comms_name(self):
		comms_member = Member.query(Member.id == self.comms).get()
		return comms_member.name

	def get_engi_name(self):
		engi_member = Member.query(Member.id == self.engi).get()
		return engi_member.name

	def get_year_str(self):
		if self.start.year == self.end.year:
			return str(self.start.year)
		else:
			return str(self.start.year) + '-' + str(self.end.year)

	admiral_name = property(get_admiral_name)
	captain_name = property(get_captain_name)
	first_officer_name = property(get_first_officer_name)
	ops_name = property(get_ops_name)
	comms_name = property(get_comms_name)
	engi_name = property(get_engi_name)
	year_str = property(get_year_str)

class Mission(ndb.Model):
	TYPES = [
		'Weekly', # 0
		'Special', # 1
		'Away', # 2
	]

	id = ndb.StringProperty() # Mission number (or special identifier for non-standard mission)
	type = ndb.IntegerProperty()
	title = ndb.StringProperty()
	description = ndb.TextProperty()
	start = ndb.DateTimeProperty()
	end = ndb.DateTimeProperty()
	location = ndb.StringProperty()
	runners = ndb.StringProperty(repeated=True) # Member UUIDs
	wave_url = ndb.StringProperty()
	fb_url = ndb.StringProperty()
	gplus_url = ndb.StringProperty()
	the_link_url = ndb.StringProperty()
	youtube_url = ndb.StringProperty()

	def get_start_str(self):
		if self.start:
			return self.start.strftime('%Y-%m-%dT%H:%M')
		return ''

	def get_end_str(self):
		if self.end:
			return self.end.strftime('%Y-%m-%dT%H:%M')
		return ''

	def get_pretty_date(self):
		pretty_date = self.start.strftime('%B %d, %Y · %I:%M %p')
		# Do not show the date twice for single-day events.
		if self.start.date() == self.end.date():
			pretty_date += self.end.strftime(' - %I:%M %p')
		else:
			pretty_date += self.end.strftime(' - %B %d, %Y · %I:%M %p')
		return pretty_date

	def get_runners_str(self):
		return ','.join(self.runners)

	def get_runners_list(self):
		runners_list = []
		for runner_id in self.runners:
			runner = Member.query(Member.id == runner_id).get()
			if runner:
				runners_list.append(runner)
		return runners_list

	def get_type_name(self):
		return Mission.TYPES[self.type] + ' Mission'

	def get_youtube_embed_url(self):
		if not self.youtube_url:
			return None
		return self.youtube_url.replace('watch?v=', 'embed/').replace('playlist?list=', 'embed/videoseries?list=')

	def get_html_description(self):
		# Convert the description from Markdown to HTML.
		return markdown(text=gfm(self.description),safe_mode='escape').replace('<a href="', '<a target="_blank" href="')

	start_str = property(get_start_str)
	end_str = property(get_end_str)
	pretty_date = property(get_pretty_date)
	runners_str = property(get_runners_str)
	runners_list = property(get_runners_list)
	type_name = property(get_type_name)
	youtube_embed_url = property(get_youtube_embed_url)
	html_description = property(get_html_description)


import requests

def display(board):
    for i in range(len(board)):
        if i % 3 == 0 and i != 0:
            print("- - - - - - - - - - -")
        for j in range(len(board[i])):
            if j % 3 == 0 and j != 0:
                print("| ", end="")
            if j == 8:
                print(str(board[i][j]))
            else:
                print(str(board[i][j]) + " ",end="")

def find_empty(board):
    for i in range(len(board)):
        for j in range(len(board[i])):
            if board[i][j] == 0:
                return (i,j)

def valid(board,value,pos):
    #check row
    for j in range(len(board[pos[0]])):
        if value == board[pos[0]][j]:
            return False
    #check column
    for i in range(len(board)):
        if value == board[i][pos[1]]:
            return False
    #check box
    box_y = pos[0]//3
    box_x = pos[1]//3
    for i in range(box_y * 3, box_y * 3 + 3):
        for j in range(box_x * 3, box_x * 3 + 3):
            if value == board[i][j]:
                return False
    return True

def solve(board):
    find = find_empty(board)
    if not find:
        return True
    else:
        row, pos = find

    for i in range(1,10):
        if valid(board,i,find):
            board[row][pos] = i

            if solve(board):
                return True

            board[row][pos] = 0

    return False

def generate_board(difficulty):
    easy = requests.get("https://sugoku.herokuapp.com/board?difficulty=easy")
    medium = requests.get("https://sugoku.herokuapp.com/board?difficulty=medium")
    hard = requests.get("https://sugoku.herokuapp.com/board?difficulty=hard")
    if difficulty == "easy":
        board = easy.json()["board"]
    if difficulty == "medium":
        board = medium.json()["board"]
    if difficulty == "hard":
        board = hard.json()["board"]
    return board


import os
import re
from datetime import datetime
from datetime import timedelta
import openpyxl

import pandas as pd

def max_min(html_text):
    pd_html = pd.DataFrame({'index': html.index, 'Name': html.values})
    a = pd_html.drop('index', axis=1)

    for i in range(a.shape[0]):
        if type(a.Name[i]) == str:
            for y in range(10):
                if ' ' + str(y) + ':' in a.Name[i]:
                    a.Name[i].replace(' ' + str(y) + ':', ' 0' + str(y) + ':')
                else:
                    continue
        if type(a.Name[i]) == str:

            if '0000' in a.Name[i]:
                a.Name[i] = pd.NA
            elif '[' in a.Name[i]:
                a.Name[i] = a.Name[i].replace(';', '')
                a.Name[i] = datetime.strptime(a.Name[i].replace('[', '').replace(']', ''), '%d.%m.%Y %H:%M:%S:%f')
            else:
                a.Name[i] = pd.NA
        else:
            a.Name[i] = pd.NA
    a = a.dropna()
    print(min(a.Name).strftime("%d.%m.%Y %H:%M:%S:%f"))
    print(max(a.Name).strftime("%d.%m.%Y %H:%M:%S:%f"))
    # print(begin.strftime("%d.%m.%Y %H:%M:%S:%f"))
    # print(end.strftime("%d.%m.%Y %H:%M:%S:%f"))
    return min(a.Name), max(a.Name)

def read_xml(html_text, sheet, begin, end):
    a = html_text
    p = 0
    p1 = 0
    p2 = 0
    p3 = []
    for i in range(a.shape[0]):
        if type(a.Name[i]) == str:
            if '0000' in a.Name[i]:
                b = a.Name[i].split("  ")
                if int(b[0]) == 10:
                    a.Name[i - 1] += b[2].strip()
                    a.Name[i] = pd.NA
                elif int(b[0]) == 20:
                    a.Name[i - 2] += b[2]
                    a.Name[i] = pd.NA
                else:
                    a.Name[i] = b[2]

                if b[2].split(" ")[0:2] == ['00', '04'] and b[1].split(" ")[5:7] == ['06', '01']:
                    p += 1
                if b[2].split(" ")[0:2] == ['00', '60'] and b[1].split(" ")[5:7] == ['06', '01']:
                    p1 += 1
                if b[2].split(" ")[0:2] == ['11', '08'] and b[1].split(" ")[5:7] == ['06', '01']:
                    p2 += 1
                if '01' in b[1]:
                    aa = [' ']

                    p3.append(b[1:3])
            elif '[' in a.Name[i]:
                a.Name[i] = datetime.strptime(a.Name[i].replace('[', '').replace(']', ''), '%d.%m.%Y %H:%M:%S:%f')

    print('Первый этап закончен')
    x = 0
    if sheet == 'Спутник':
        delta = timedelta(hours=1)
        begin += delta
        end += delta
    count = 0
    datetime_count = 0
    for i in range(a.shape[0]):
        if type(a.Name[i]) == datetime:
            if a.Name[i] < begin or a.Name[i] > end:
                a.Name[i] = pd.NA
                y = 1
                if i + y + 1 < len(a.Name):
                    while type(a.Name[i + y]) != datetime:
                        a.Name[i + y] = pd.NA
                        if i + y + 1 < len(a.Name):
                            y += 1
                        else:
                            break
                else:
                    print('Список закончен')
                    break

            else:
                datetime_count += 1
                # print('Дата ' + str(datetime_count) + ' добавлена')
        elif type(a.Name[i]) == str:
            a.Name[i] = len(str(a.Name[i]).split(' '))
            x += a.Name[i]
            count += 1
            # print('Данные ' + str(count) + ' добавлены добавлены')
        # print('Обработано записей ' + str(i))
    print('Завершен расчет')
    a = a.dropna(how='all')
    a = a.reindex()
    print('Переиндексация завершена')
    print(sheet)
    print(str(x) + ' байт')
    print(str(count) + ' пакетов')
    print(str(datetime_count) + ' дат')
    print(a.shape)
    print(begin.strftime("%d.%m.%Y %H:%M:%S:%f"))
    print(end.strftime("%d.%m.%Y %H:%M:%S:%f"))
    a.to_excel(sheet + ".xlsx")
    print("Перепад даления 2 -\t\t\t", p, " раз запрошен")
    print("Загазованность служебная -\t", p1, " раз запрошен")
    print("GSM канал -\t\t\t\t\t", p2, " раз запрошен")

    #  for item in p3:
    #      print(item)

def html_reader(path_text):
    if 'csv' in path_text:
        html_text = pd.read_csv(path_text)
    else:
        html_text = pd.read_table(path_text)
    html_text.columns = ['Name']

    if 'поток' in path_text:
        for i in range(html_text.shape[0]):
            p = re.compile(r'<.*?>')
            html_text.Name[i] = p.sub('', html_text.Name[i])

    html_text = html_text.Name[html_text.Name.str.contains('00000') | html_text.Name.str.contains(']')]
    print('html read')

    return html_text

def read_xml_free(html_text, sheet):
    a = html_text
    for i in range(a.shape[0]):
        if type(a.Name[i]) == str:
            if '0000' in a.Name[i]:
                b = a.Name[i].split("  ")
                if int(b[0]) == 10:
                    a.Name[i - 1] += b[2].strip()
                    a.Name[i] = pd.NA
                elif int(b[0]) == 20:
                    a.Name[i - 2] += b[2]
                    a.Name[i] = pd.NA
                else:
                    a.Name[i] = b[2]

    print('Первый этап закончен')
    x = 0

    count = 0
    datetime_count = 0
    for i in range(a.shape[0]):

        # print('Дата ' + str(datetime_count) + ' добавлена')
        if type(a.Name[i]) == str:
            a.Name[i] = len(str(a.Name[i]).split(' '))
            x += a.Name[i]
            count += 1
            # print('Данные ' + str(count) + ' добавлены добавлены')
        # print('Обработано записей ' + str(i))
    print('Завершен расчет')
    a = a.dropna(how='all')
    a = a.reindex()
    print('Переиндексация завершена')
    print(sheet)
    print(str(x) + ' байт')
    print(str(count) + ' пакетов')
    print(str(datetime_count) + ' дат')
    print(a.shape)
    # print(begin.strftime("%d.%m.%Y %H:%M:%S:%f"))
    # print(end.strftime("%d.%m.%Y %H:%M:%S:%f"))
    a.to_excel(sheet + ".xlsx")

# read_xml(pathXls, 'Спутник', begin_time, end_time)
# read_xml(pathXls, 'GPRS', begin_time, end_time)
# read_xml(pathXls, 'Лист2')

# begin_time = datetime.strptime('19.04.2021 10:31:30:000', '%d.%m.%Y %H:%M:%S:%f')
# end_time = datetime.strptime('20.04.2021 09:35:16:000', '%d.%m.%Y %H:%M:%S:%f')
# begin_time = datetime.strptime('20.04.2021 10:31:30:000', '%d.%m.%Y %H:%M:%S:%f')
# end_time = datetime.strptime('21.04.2021 04:30:00:000', '%d.%m.%Y %H:%M:%S:%f')
path = 'C:\\Users\\СолдатовВВ\\Desktop\\Logs\\'
name_file = 'report_10_06_2021_08_30.html'

# name_file = 'Logs2\\Отчёт о потоках пакетов27.html'
path += name_file
if 'report' in path:
    type_name = 'GPRS'
else:
    type_name = 'Спутник'
html = html_reader(path)
html_clone = html.copy()
pd_html = pd.DataFrame({'index': html_clone.index, 'Name': html_clone.values})
html_clone = pd_html.drop('index', axis=1)
begin_time = datetime.strptime('10.06.2021 16:59:03:361', '%d.%m.%Y %H:%M:%S:%f')
end_time = datetime.strptime('10.06.2021 20:43:57:579', '%d.%m.%Y %H:%M:%S:%f')
# print(html_clone)
# max_min(html_clone)
# print(html_clone)
read_xml(html_clone, type_name, begin_time, end_time)
# read_xml_free(html_clone, type_name)


from xai.brain.wordbase.adjectives._schizoid import _SCHIZOID

#calss header
class _SCHIZOIDS(_SCHIZOID, ):
	def __init__(self,):
		_SCHIZOID.__init__(self)
		self.name = "SCHIZOIDS"
		self.specie = 'adjectives'
		self.basic = "schizoid"
		self.jsondata = {}


import random

from django.db import connection
from django.http import HttpResponse, JsonResponse

from core import constants
from orm import fake
from project.di import InteractorFactory

tour = InteractorFactory().tour

def insert(request):
    _members = [fake.MemberBase() for i in range(50)]

    _suppliers = [fake.SupplierBase() for i in range(50)]

    _tour_groups = [fake.TourGroupBase(supplier=random.choice(_suppliers)) for i in range(100)]

    _tags = []
    for row in _tour_groups:
        for tag in constants.TourGroupTag:
            if random.choice([1, 0]):
                _tags.append(fake.TourGroupTag(tour_group=row, tag=tag.value))

    _locations = []
    for row in _tour_groups:
        for i in range(random.randint(1, 5)):
            _locations.append(fake.TourGroupLocation(tour_group=row))

    _buckets = []
    for row in _tour_groups:
        from datetime import date, timedelta

        today = date.today()
        for i in range(random.randint(15, 30)):
            if random.choice([1, 1, 0]):
                _buckets.append(fake.TourGroupBucket(tour_group=row, date=today + timedelta(days=i)))

    for member in _members:
        for tour_group in _tour_groups:
            if random.choice([1, 0, 0]):
                fake.MemberFavorite(member=member, tour_group=tour_group)

    return JsonResponse(
        {
            "resp": {
                "members": len(_members),
                "suppliers": len(_suppliers),
                "tour_group": len(_tour_groups),
            }
        }
    )

def clear(request):
    with connection.cursor() as cursor:
        cursor.execute("SET FOREIGN_KEY_CHECKS = 0;")

        cursor.execute("truncate member_base;")
        cursor.execute("truncate member_favorite;")
        cursor.execute("truncate supplier_base;")
        cursor.execute("truncate score_base_log;")
        cursor.execute("truncate tour_group_base;")
        cursor.execute("truncate tour_group_bucket;")
        cursor.execute("truncate tour_group_tag;")
        cursor.execute("truncate tour_group_location;")

        cursor.execute("SET FOREIGN_KEY_CHECKS = 1;")

    return HttpResponse(200)


#encoding: utf-8
from OpenOrange import *
from Report import Report

class TaxInstallDecl(Report):

    def GetPayTermConds(self):
        pterms = {}
        query = Query()
        query.sql  = "SELECT {Code},{InterestRate} "
        query.sql += "FROM [PayTerm] "
        query.sql += "WHERE {PayType}=1 "
        if(query.open()):
          for pt in query:
            pterms[pt.Code] = pt.InterestRate
        return pterms

    def run(self):
        params = self.getRecord()
        totcap,totint = 0.0,0.0
        pterms = self.GetPayTermConds()
        query = Query()
        query.sql  = "SELECT iir.{Amount}, iir.{DueDate},iir.{InstallNr}, "
        query.sql += "{Installments},{PayTerm},{Office},{Total},{SerNr} "
        query.sql += "FROM [InvoiceInstallRow] iir "
        query.sql += "INNER JOIN [Invoice] ON iir.{masterId}=[Invoice].{internalId} "
        query.sql += "WHERE?AND iir.{DueDate} BETWEEN d|%s| AND d|%s| " % (params.FromDate,params.ToDate)
        if params.Office:
          query.sql += "WHERE?AND [Invoice].{Office}=s|%s| " %  params.Office
        query.sql += "GROUP BY {Office},{SerNr} "
        if(query.open()):
            self.printReportTitle("Listado de Devengado Exigible")
            self.startTable()
            self.header("Office","Invoice Nr","DueDate","Installment Nr","Total","Installment Amount","Capital","Interest")
            for r in query:
                rate = pterms.get(r.PayTerm,0)
                (interes,capital) = self.GetCapital(r.Installments,r.Amount,rate)
                self.startRow()
                self.addValue(r.Office)
                self.addValue(r.SerNr)
                self.addValue(r.DueDate)
                self.addValue(r.InstallNr)
                self.addValue(r.Total)
                self.addValue(r.Amount)
                self.addValue(capital)
                self.addValue(interes)
                self.endRow()
                totcap += capital
                totint += interes
            self.headerA("Total Capital","Total Interest")
            self.startRow()
            self.addValue(totcap)
            self.addValue(totint)
            self.endRow()
            self.endTable()
            query.close()

    def GetCapital(self,installs,cuota,rate):
        capital = cuota / (1 + installs * (rate/100))
        interes = capital * (rate/100)
        if (installs <= 10):
          captial = 0
        return (interes,capital)


"""
set max size for a window

"""

import tkinter as tk
import time

root = tk.Tk()
root.title('Python GUI - set min size for a window')

winw= 800
winh= 450
posx=300
posy=200
root.geometry(f'{winw}x{winh}+{posx}+{posy}')

# case 1.
w,h = root.minsize()
print(w,h)

# case 2.
root.minsize(400,225)

root.mainloop()


import cv2 as cv
import numpy as np
import imutils
# from ImagePreProcess import *
from . import ImagePreProcess
from . import Undistort
class LiveMeasure():
	def __init__(self):
		print("Optimization is enabled [T/F]: {}".format(cv.useOptimized()))
		self.cap = cv.VideoCapture(1)
	def close(self):
		self.cap.release()
	def get(self):
		DIM=(640, 480)
		K=np.array([[553.350692313905, 0.0, 342.9451779392026], [0.0, 545.573637355145, 211.4054580385251], [0.0, 0.0, 1.0]])
		D=np.array([[-0.2807810032443438], [2.1812482493268424], [-8.101784482269283], [10.048341560961232]])

		font = cv.FONT_HERSHEY_SIMPLEX
		image = ImagePreProcess.ImagePreProcess()
		length = " "
		setting = 1
		und = Undistort.Undistort()
		ret, frame = self.cap.read()
		if frame is not None:
			h,w = frame.shape[:2]
			#map1, map2 = cv.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, DIM, cv.CV_16SC2)
			undistorted_img = und.rectify(frame)

			#img = cv.GaussianBlur(undistorted_img,(5,5), 0)
			#median = cv.medianBlur(img,5)
			#blur = cv.bilateralFilter(median, 9, 75, 75)
			#img = image.process(frame)
			#thresh = cv2.threshold(undistorted_img,127,255,cv2.THRESH_BINARY)
			#cnts = cv.findContours(thresh, cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
			#cnts = imutils.grab_contours(cnts)
			hsv = cv.cvtColor(undistorted_img, cv.COLOR_BGR2HSV)
			#lower_red = np.array([110,65,65])
			#upper_red = np.array([130,255,255])
			map1, map2 = cv.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, DIM, cv.CV_16SC2)
			undistorted_img = cv.remap(frame, map1, map2, interpolation=cv.INTER_LINEAR, borderMode=cv.BORDER_CONSTANT)
			#img = cv.GaussianBlur(undistorted_img,(5,5), 0)
			#median = cv.medianBlur(img,5)
			#blur = cv.bilateralFilter(median, 9, 75, 75)
			hsv = cv.cvtColor(undistorted_img, cv.COLOR_BGR2HSV)

			if cv.waitKey(1) & 0xFF == ord('a'):
				setting +=1
			if setting%2 == 1:
				lower_red = np.array([110,55,55])
				upper_red = np.array([140,255,255])
			if setting%2 == 0:
				lower_red = np.array([110,45,45])
				upper_red = np.array([140,255,255])
			mask = cv.inRange(hsv, lower_red, upper_red)
			res = cv.bitwise_and(undistorted_img,undistorted_img, mask= mask)
			mask = cv.inRange(hsv, lower_red, upper_red)
			res = cv.bitwise_and(undistorted_img,undistorted_img, mask= mask)

			img = image.process(res)
			cnts = cv.findContours(img, cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
			cnts = imutils.grab_contours(cnts)

			for c in cnts :
				if cv.contourArea(c) >= 500  :

					rect = cv.minAreaRect(c)
					box = cv.boxPoints(rect)
					box = np.int0(box)
					cv.drawContours(undistorted_img,[box],0,(0,0,255),2)
					(x, y), (width, height), rect_angle = rect

					if height < width :
						convert = 1.905/height
						length =  (6.5/5.9)*convert * width

					if height>width:
						convert = 1.905/width
						length =  (6.5/5.9)*convert * height

					cv.putText(undistorted_img,str(length),(100,100), font, 1,(50,50,255),1,cv.LINE_AA)

				#cv.drawContours(frame, [c], -1, (0, 255, 0), 2)

			#cv.imshow('frame',frame)
			#cv.imshow("undistorted", undistorted_img)
			#cv.imshow("Canny Edge", img)
			#cv.imshow('mask',mask)
			#cv.imshow('res',res)
			#print(lower_red)
			return (str(length), undistorted_img)
		return (None, None)

				#cv.imwrite("image.jpg",frame)

		# if cv.waitKey(1) & 0xFF == ord('q'):
		# 		break


from django.urls import path, re_path
from product import views

app_name = "product"
urlpatterns = [

    path("cart/", views.cartView.as_view(), name='show'),
    path("", views.beddingCatrgory.as_view(), name='bedding'),
    path("product", views.addToCart.as_view(), name='add'),
    path("Summary/", views.Submitted_View.as_view(), name='summary'),
    path("antiques/", views.antiquesCategory.as_view(), name='antique'),
    path('<int:pk>/itemshow/', views.productDetails.as_view(), name = 'item' ),

]


from django.shortcuts import render, get_object_or_404
from .models import Category, Product
from cart.forms import CartAddProductForm

def product_list(request, category_slug=None):
    category_page = None
    products = None
    if category_slug != None:
        category_page = get_object_or_404(Category, slug=category_slug)
        products = Product.objects.filter(category=category_page, available=True)
    else:
        products = Product.objects.all().filter(available=True)
    return render(request,
                  'shop/product/list.html',
                  {'category': category_page,
                   'products': products,
                   })

def product_detail(request, id, slug):
    product = get_object_or_404(Product,
                                id=id,
                                slug=slug,
                                available=True)
    cart_product_form = CartAddProductForm()
    return render(request,
                  'shop/product/detail.html',
                  {'product': product,
                   'cart_product_form': cart_product_form})


# -*- coding: utf-8 -*-
# -----------------------------------------------------------
#
# Profile
# Copyright (C) 2012  Matthias Kuhn
# -----------------------------------------------------------
#
# licensed under the terms of GNU GPL 2
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this progsram; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# ---------------------------------------------------------------------

import logging

from qgis.PyQt.QtCore import QSettings, Qt, QUrl, pyqtSignal, pyqtSlot
from qgis.PyQt.QtPrintSupport import QPrinter, QPrintPreviewDialog
from qgis.PyQt.QtWebKit import QWebSettings
from qgis.PyQt.QtWebKitWidgets import QWebPage, QWebView
from qgis.PyQt.QtWidgets import QVBoxLayout, QWidget

from ..tools.qgepnetwork import QgepGraphManager
from ..utils.translation import QgepJsTranslator
from ..utils.ui import plugin_root_path

class QgepWebPage(QWebPage):
    logger = logging.getLogger(__name__)

    def __init__(self, parent):
        QWebPage.__init__(self, parent)

    def javaScriptConsoleMessage(self, msg, line, source):
        self.logger.debug("{} line {}: {}".format(source, line, msg))

class QgepPlotSVGWidget(QWidget):
    webView = None
    webPage = None
    frame = None
    profile = None
    verticalExaggeration = 10
    jsTranslator = QgepJsTranslator()

    # Signals emitted triggered by javascript actions
    reachClicked = pyqtSignal([str], name="reachClicked")
    reachMouseOver = pyqtSignal([str], name="reachMouseOver")
    reachMouseOut = pyqtSignal([str], name="reachMouseOut")
    reachPointClicked = pyqtSignal([str, str], name="reachPointClicked")
    reachPointMouseOver = pyqtSignal([str, str], name="reachPointMouseOver")
    reachPointMouseOut = pyqtSignal([str, str], name="reachPointMouseOut")
    specialStructureClicked = pyqtSignal([str], name="specialStructureClicked")
    specialStructureMouseOver = pyqtSignal([str], name="specialStructureMouseOver")
    specialStructureMouseOut = pyqtSignal([str], name="specialStructureMouseOut")

    # Signals emitted for javascript
    profileChanged = pyqtSignal([str], name="profileChanged")
    verticalExaggerationChanged = pyqtSignal([int], name="verticalExaggerationChanged")

    def __init__(self, parent, network_analyzer: QgepGraphManager, url: str = None):
        QWidget.__init__(self, parent)

        self.webView = QWebView()
        self.webView.setPage(QgepWebPage(self.webView))

        self.networkAnalyzer = network_analyzer

        settings = QSettings()

        layout = QVBoxLayout(self)
        if url is None:
            # Starting with QGIS 3.4, QWebView requires paths with / even on windows.
            default_url = (
                plugin_root_path().replace("\\", "/") + "/svgprofile/index.html"
            )
            url = settings.value("/QGEP/SvgProfilePath", default_url)
            url = "file:///" + url

        developer_mode = settings.value("/QGEP/DeveloperMode", False, type=bool)

        if developer_mode is True:
            self.webView.page().settings().setAttribute(
                QWebSettings.DeveloperExtrasEnabled, True
            )
        else:
            self.webView.setContextMenuPolicy(Qt.NoContextMenu)

        self.webView.load(QUrl(url))
        self.frame = self.webView.page().mainFrame()
        self.frame.javaScriptWindowObjectCleared.connect(self.initJs)

        layout.addWidget(self.webView)

    def setProfile(self, profile):
        self.profile = profile
        # Forward to javascript
        self.profileChanged.emit(profile.asJson())

    def initJs(self):
        self.frame.addToJavaScriptWindowObject("profileProxy", self)
        self.frame.addToJavaScriptWindowObject("i18n", self.jsTranslator)

    def changeVerticalExaggeration(self, val):
        self.verticalExaggeration = val
        self.verticalExaggerationChanged.emit(val)

    def printProfile(self):
        printer = QPrinter(QPrinter.HighResolution)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setPaperSize(QPrinter.A4)
        printer.setOrientation(QPrinter.Landscape)

        printpreviewdlg = QPrintPreviewDialog()
        printpreviewdlg.paintRequested.connect(self.printRequested)

        printpreviewdlg.exec_()

    @pyqtSlot(QPrinter)
    def printRequested(self, printer):
        self.webView.print_(printer)

    @pyqtSlot(str)
    def onReachClicked(self, obj_id):
        self.reachClicked.emit(obj_id)

    @pyqtSlot(str)
    def onReachMouseOver(self, obj_id):
        self.reachMouseOver.emit(obj_id)

    @pyqtSlot(str)
    def onReachMouseOut(self, obj_id):
        self.reachMouseOut.emit(obj_id)

    @pyqtSlot(str, str)
    def onReachPointClicked(self, obj_id, reach_obj_id):
        self.reachPointClicked.emit(obj_id, reach_obj_id)

    @pyqtSlot(str, str)
    def onReachPointMouseOver(self, obj_id, reach_obj_id):
        self.reachPointMouseOver.emit(obj_id, reach_obj_id)

    @pyqtSlot(str, str)
    def onReachPointMouseOut(self, obj_id, reach_obj_id):
        self.reachPointMouseOut.emit(obj_id, reach_obj_id)

    @pyqtSlot(str)
    def onSpecialStructureClicked(self, obj_id):
        self.specialStructureClicked.emit(obj_id)

    @pyqtSlot(str)
    def onSpecialStructureMouseOver(self, obj_id):
        self.specialStructureMouseOver.emit(obj_id)

    @pyqtSlot(str)
    def onSpecialStructureMouseOut(self, obj_id):
        self.specialStructureMouseOut.emit(obj_id)

    # Is called from the webView when it's been reloaded and wants to have the
    # profile information resent
    @pyqtSlot()
    def updateProfile(self):
        if self.profile:
            self.profileChanged.emit(self.profile.asJson())
            self.verticalExaggerationChanged.emit(self.verticalExaggeration)


import bs4
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json
import datetime
import re

#f= open("guru99.txt","w+")
#f.write("some shit")
dataArr=[]

options = Options()
options.set_headless(headless=True)
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(options=options, executable_path='C:/Users/Developer/Downloads/chromedriver_win32_2.40/chromedriver.exe')
driver.get("https://www.indeed.com/jobs?q=java&l=usa&sort=date")
print ("Headless Chrome Initialized")

html=driver.page_source.encode('utf-8')
#print(html)
soup = BeautifulSoup(html, "html.parser")
positions=soup.find_all("div", {"class": "row result clickcard"})
length=len(positions)

print ("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
print (length)

for i in positions:
    data = {}
    h2=i.find("h2",{"class":"jobtitle"})
    a=h2.find("a")
    data['title']=a['title']
    data['linkToVacancy']="www.indeed.com"+a['href']
    data['company']=i.find("span",{"class":"company"}).get_text()
    data['location']=i.find("span",{"class":"location"}).get_text()
    data['summary']=i.find("span",{"class":"summary"}).get_text()
    date=i.find("span",{"class":"date"}).get_text()
    today=datetime.date.today()
    if "days" or "day" not in date:
        data['date']=today.isoformat()
    else:

        data['date']=(today + datetime.timedelta(days=-int(re.search(r'\d+', date).group()))).isoformat()

    data['website']="indeed"
    dataArr.append(data)

driver.quit()
json_data = json.dumps(dataArr)
#f.write(json_data)

with open('indeed.json', 'w') as outfile:
    json.dump(dataArr, outfile)

outfile.close()
x = datetime.date.today()
end_date = x + datetime.timedelta(days=10)
print(end_date)

#f.close()


from django.urls import path, re_path
from Store.views import *

urlpatterns = [
    path('register/', register),
    path('login/', login),
    path("logout/", logout),
    path("index/", index),
    re_path("index/", index),
    path("base/", base),
    path("register_store/", register_store),
    path("add_goods/", add_goods),
    re_path(r"list_goods/(?P<state>\w+)", list_goods),
    re_path("update_goods/(?P<goods_id>\d+)", update_goods),
    re_path("set_goods/(?P<state>\w+)/", set_goods),
    path(r'list_goods_type/', list_goods_type),
    path(r'delete_goods_type/', delete_goods_type),
    path("order_list/", order_list),
    re_path(r"order_list/(?P<state>\w+)", order_list),
    re_path("set_order/(?P<state>\w+)/", set_order),
    path('agl/', ajax_goods_list),
    path('get_add/', get_add),
]


import requests
import json
import os

from dotenv import load_dotenv
from pathlib import Path

from web3.auto import w3

load_dotenv()

headers = {
    "Content-Type": "application/json",
    "pinata_api_key": os.getenv("PINATA_API_KEY"),
    "pinata_secret_api_key": os.getenv("PINATA_SECRET_API_KEY"),
}

def initContract():
    with open(Path("CryptoRecord.json")) as json_file:
        abi = json.load(json_file)

    return w3.eth.contract(address=os.getenv("CRYPTORECORD_ADDRESS"), abi=abi)

def convertDataToJSON(landlord, token_id, previous, lease, omnibus, time, description):
    data = {
        "pinataOptions": {"cidVersion": 1},
        "pinataContent": {
            "name": "Space Report",
            # Apartment as "token_id"
            "apartment": token_id,
            "landlord": landlord,
            "previous": previous,
            "lease": lease,
            "omnibus": omnibus,
            "description": description,
            # This is the uploaded v1 URI for apartment on IPFS all in lower case
            "image": f"ipfs://improvemyfavoriteapartmentxoxo_{token_id}",
            "time": time
        },
        "pinataMetadata": {
            "name": description,
            "keyvalues": {
                "customKey": description,
                "customKey2": "baes"
            }
        }
    }
    return json.dumps(data)

def pinJSONtoIPFS(json):
    r = requests.post(
        "https://api.pinata.cloud/pinning/pinJSONToIPFS", data=json, headers=headers
    )
    ipfs_hash = r.json()["IpfsHash"]
    return f"ipfs://{ipfs_hash}"


#!/usr/bin/env python
from setuptools import setup, find_packages

rootdir = "src"

artifact = {
        "name": "detonator core",
        "version": "0.3",
        "description": '''The Detonator core package. A middleware implementation of PEP 333 specification for web development.''',

        "packages": find_packages(rootdir),
        "package_dir": {'':rootdir},
        "namespace_packages": [ "detonator", "detonator.core" ],

        "author": "Miere L. Teixeira",
        "author_email": "miere00@gmail.com",
        "license" : "LGPL2",
    }

setup(**artifact)


import base64
import json

from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django import http
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import exceptions
from horizon.forms import views
from horizon import tables
from horizon import tabs

from muranoclient.common import exceptions as exc
from muranodashboard import api as api_utils
from muranodashboard.environments import api
import tables as env_tables
import tabs as env_tabs

from oslo_log import log as logging
LOG = logging.getLogger(__name__)

from horizon import messages
from muranodashboard.environments import consts
from muranodashboard.common import utils
from muranodashboard.dynamic_ui import helpers
from muranodashboard.dynamic_ui import services
from muranodashboard.catalog.views import LazyWizard
class Wizard(views.ModalFormMixin, LazyWizard):
    template_name = 'clouds/wizard_create.html'
    do_redirect = False
    environment_id = env_tables.get_cloud_id()

    def get_prefix(self, *args, **kwargs):
        base = super(Wizard, self).get_prefix(*args, **kwargs)
        fmt = utils.BlankFormatter()
        return fmt.format('{0}_{app_id}', base, **kwargs)

    def get_form_prefix(self, step=None, form=None):
        if step is None:
            return self.steps.step0
        else:
            index0 = self.steps.all.index(step)
            return str(index0)

    def done(self, form_list, **kwargs):
        app_name = self.storage.extra_data['app'].name

        service = form_list[0].service
        attributes = service.extract_attributes()
        attributes = helpers.insert_hidden_ids(attributes)
        storage = attributes.setdefault('?', {}).setdefault(consts.DASHBOARD_ATTRS_KEY, {})
        storage['name'] = app_name

        do_redirect = self.get_wizard_flag('do_redirect')
        wm_form_data = service.cleaned_data.get('workflowManagement')
        if wm_form_data:
            do_redirect = do_redirect or not wm_form_data.get(
                'stay_at_the_catalog', True)

        fail_url = reverse("horizon:admin:clouds:index")
        try:
            env_url = reverse('horizon:admin:clouds:index')
            srv = api.service_create(self.request, self.environment_id, attributes)
        except exc.HTTPForbidden:
            msg = _("Sorry, you can't add task right now.")
            exceptions.handle(self.request, msg, redirect=fail_url)
        except Exception:
            message = _('Adding task failed.')
            LOG.exception(message)
            exceptions.handle(self.request, message, redirect=fail_url)
        else:
            message = _("The '{0}' task successfully added.").format(app_name)
            LOG.info(message)
            messages.success(self.request, message)

            if do_redirect:
                return http.HttpResponseRedirect(env_url)
            else:
                srv_id = getattr(srv, '?')['id']
                return self.create_hacked_response(
                    srv_id,
                    attributes['?'].get('name') or attributes.get('name'))

    def create_hacked_response(self, obj_id, obj_name):
        # copy-paste from horizon.forms.views.ModalFormView; should be done
        # that way until we move here from django Wizard to horizon workflow
        if views.ADD_TO_FIELD_HEADER in self.request.META:
            field_id = self.request.META[views.ADD_TO_FIELD_HEADER]
            response = http.HttpResponse(json.dumps(
                [obj_id, html.escape(obj_name)]
            ))
            response["X-Horizon-Add-To-Field"] = field_id
            return response
        else:
            return http.HttpResponse()

    def get_form_initial(self, step):
        init_dict = {'request': self.request,
                     'app_id': self.kwargs['app_id'],
                     'environment_id': self.environment_id}
        return self.initial_dict.get(step, init_dict)

    def _get_wizard_param(self, key):
        param = self.kwargs.get(key)
        return param if param is not None else self.request.POST.get(key)

    def get_wizard_flag(self, key):
        value = self._get_wizard_param(key)
        return utils.ensure_python_obj(value)

    def get_context_data(self, form, **kwargs):
        context = super(Wizard, self).get_context_data(form=form, **kwargs)
        app_id = self.kwargs.get('app_id')
        app = self.storage.extra_data.get('app')

        # Save extra data to prevent extra API calls
        mc = api_utils.muranoclient(self.request)
        if not app:
            app = mc.packages.get(app_id)
            self.storage.extra_data['app'] = app

        env_name = mc.environments.get(self.environment_id).name

        context['field_descriptions'] = services.get_app_field_descriptions(self.request, app_id, self.steps.index)
        context.update({'type': app.fully_qualified_name,
                        'service_name': app.name,
                        'app_id': app_id,
                        'environment_id': self.environment_id,
                        'environment_name': env_name,
                        'do_redirect': self.get_wizard_flag('do_redirect'),
                        'drop_wm_form': self.get_wizard_flag('drop_wm_form'),
                        'prefix': self.prefix,
                        'got_picture': app.supplier.has_key('Logo'),
                        })
        return context

class CloudView(tabs.TabbedTableView):
    tab_group_class = env_tabs.EnvironmentDetailsTabs
    template_name = 'clouds/index.html'
    page_title = 'Hybrid Clouds'
    environment_id = env_tables.get_cloud_id()

    def get_context_data(self, **kwargs):
        context = super(CloudView, self).get_context_data(**kwargs)
        context['tenant_id'] = self.request.session['token'].tenant['id']
        context['environment_id'] = self.environment_id
        context["url"] = self.get_redirect_url()
        return context

    def get_tabs(self, request, *args, **kwargs):
        try:
            deployments = api.deployments_list(self.request, self.environment_id)
        except exc.HTTPException:
            msg = _('Unable to retrieve list of deployments')
            exceptions.handle(self.request, msg, redirect=self.get_redirect_url())

        logs = []
        if deployments:
            last_deployment = deployments[0]
            logs = api.deployment_reports(self.request, self.environment_id, last_deployment.id)
        return self.tab_group_class(request, logs=logs, **kwargs)

    @staticmethod
    def get_redirect_url():
        return reverse_lazy("horizon:admin:clouds:index")

class DetailServiceView(tabs.TabbedTableView):
    tab_group_class = env_tabs.ServicesTabs
    template_name = 'clouds/details.html'
    page_title = '{{ service_name }}'

    def get_context_data(self, **kwargs):
        context = super(DetailServiceView, self).get_context_data(**kwargs)
        service = self.get_data()
        context["service"] = service
        context["service_name"] = getattr(self.service, 'name', '-')
        context["custom_breadcrumb"] = [(_("Clouds"), CloudView.get_redirect_url()),]
        return context

    def get_data(self):
        service_id = self.kwargs['service_id']
        self.environment_id = env_tables.get_cloud_id()
        try:
            self.service = api.service_get(self.request, self.environment_id, service_id)
        except exc.HTTPUnauthorized:
            exceptions.handle(self.request)

        except exc.HTTPForbidden:
            redirect = reverse('horizon:admin:clouds:index')
            exceptions.handle(self.request, _('Unable to retrieve details for task'), redirect=redirect)
        else:
            self._service = self.service
            return self._service

    def get_tabs(self, request, *args, **kwargs):
        service = self.get_data()
        return self.tab_group_class(request, service=service, **kwargs)

class DeploymentDetailsView(tabs.TabbedTableView):
    tab_group_class = env_tabs.DeploymentDetailsTabs
    table_class = env_tables.EnvConfigTable
    template_name = 'clouds/reports.html'
    page_title = _('Clouds at {{ deployment_start_time }}')

    def get_context_data(self, **kwargs):
        context = super(DeploymentDetailsView, self).get_context_data(**kwargs)
        context["deployment_start_time"] = api.get_deployment_start(self.request, self.environment_id, self.deployment_id)
        context["custom_breadcrumb"] = [(_("Clouds"), CloudView.get_redirect_url()),]
        return context

    def get_deployment(self):
        deployment = None
        try:
            deployment = api.get_deployment_descr(self.request,
                                                  self.environment_id,
                                                  self.deployment_id)
        except (exc.HTTPInternalServerError, exc.HTTPNotFound):
            msg = _("Deployment with id %s doesn't exist anymore")
            redirect = reverse("horizon:admin:clouds:deployments")
            exceptions.handle(self.request,
                              msg % self.deployment_id,
                              redirect=redirect)
        return deployment

    def get_logs(self):
        logs = []
        try:
            logs = api.deployment_reports(self.request,
                                          self.environment_id,
                                          self.deployment_id)
        except (exc.HTTPInternalServerError, exc.HTTPNotFound):
            msg = _('Deployment with id %s doesn\'t exist anymore')
            redirect = reverse("horizon:admin:clouds:deployments")
            exceptions.handle(self.request,
                              msg % self.deployment_id,
                              redirect=redirect)
        return logs

    def get_tabs(self, request, *args, **kwargs):
        self.deployment_id = self.kwargs['deployment_id']
        self.environment_id = env_tables.get_cloud_id()
        deployment = self.get_deployment()
        logs = self.get_logs()

        return self.tab_group_class(request, deployment=deployment, logs=logs,
                                    **kwargs)

class JSONResponse(http.HttpResponse):
    def __init__(self, content=None, **kwargs):
        if content is None:
            content = {}
        kwargs.pop('content_type', None)
        super(JSONResponse, self).__init__(
            content=json.dumps(content), content_type='application/json',
            **kwargs)

class StartActionView(generic.View):
    @staticmethod
    def post(request, environment_id, action_id):
        if api.action_allowed(request, environment_id):
            task_id = api.run_action(request, environment_id, action_id)
            url = reverse('horizon:admin:clouds:action_result',
                          args=(environment_id, task_id))
            return JSONResponse({'url': url})
        else:
            return JSONResponse()

class ActionResultView(generic.View):
    @staticmethod
    def is_file_returned(result):
        try:
            return result['result']['?']['type'] == 'io.murano.File'
        except (KeyError, ValueError, TypeError):
            return False

    @staticmethod
    def compose_response(result, is_file=False, is_exc=False):
        filename = 'exception.json' if is_exc else 'result.json'
        content_type = 'application/octet-stream'
        if is_file:
            filename = result.get('filename') or 'action_result_file'
            content_type = result.get('mimeType') or content_type
            content = base64.b64decode(result['base64Content'])
        else:
            content = json.dumps(result, indent=True)

        response = http.HttpResponse(content_type=content_type)
        response['Content-Disposition'] = (
            'attachment; filename=%s' % filename)
        response.write(content)
        response['Content-Length'] = str(len(response.content))
        return response

    def get(self, request, environment_id, task_id, optional):
        mc = api_utils.muranoclient(request)
        result = mc.actions.get_result(environment_id, task_id)
        if result:
            if result and optional == 'poll':
                if result['result'] is not None:
                    # Remove content from response on first successful poll
                    del result['result']
                return JSONResponse(result)
            return self.compose_response(result['result'],
                                         self.is_file_returned(result),
                                         result['isException'])
        # Polling hasn't returned content yet
        return JSONResponse()


from torchio.transforms import Lambda
from torchio import Image, ImagesDataset, INTENSITY, LABEL, Subject

subject = Subject(
    label=Image('~/Dropbox/MRI/t1_brain_seg.nii.gz', LABEL),
    t1=Image('~/Dropbox/MRI/t1.nii.gz', INTENSITY),
)
subjects_list = [subject]

dataset = ImagesDataset(subjects_list)
sample = dataset[0]
transform = Lambda(lambda x: -1.5 * x, types_to_apply=INTENSITY)
transformed = transform(sample)
dataset.save_sample(transformed, {'t1': '/tmp/t1_lambda.nii'})