import sys, os, shutil
from mars_rover import Ui_MainWindow, QtWidgets
from PyQt5 import QtCore, QtGui, QtWidgets
import subprocess

class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.btnUpdateGridSize.clicked.connect(self.set_new_grid)
        self.btnNumRoversUpdate.clicked.connect(self.create_rovers_list)
        self.comboRoverSelect.currentTextChanged.connect(self.load_selected_rover)
        self.btnMoveForward.clicked.connect(self.move_rover_forward)
        self.btnTurnRight.clicked.connect(self.turn_rover_right)
        self.btnTurnLeft.clicked.connect(self.turn_rover_left)
        self.scene = None
        self.rovers_dict = {}
        self.rover_coords = {}
        self.selected_rover = None
        self.set_direction = 'N'
        self.grid_x_dimension = None
        self.grid_y_dimension = None
        self.read = True
        self.rovers_list = []

        data = {"Rover Name": [], "X-Coord": [], "Y-Coord": [], "Direction": [] }
        self.table_data = data
        self.setTableData()

    def setTableData(self):
        """Set output table default layout"""
        horHeaders = []
        header = self.tableRoverInfo.horizontalHeader()
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
        for n, key in enumerate((self.table_data.keys())):
            horHeaders.append(key)
            for m, item in enumerate(self.table_data[key]):
                newitem = QtWidgets.QTableWidgetItem(item)
                self.tableRoverInfo.setItem(m, n, newitem)
        self.tableRoverInfo.setHorizontalHeaderLabels(horHeaders)

    def set_new_grid(self):
        """Create new grid/coordinate field"""
        self.grid_x_dimension = self.spinXGrid.value()
        self.grid_y_dimension = self.spinYGrid.value()

        self.scene = QtWidgets.QGraphicsScene()
        self.graphGridView.setScene(self.scene)
        pen = QtGui.QPen(QtCore.Qt.green)

        side = 30

        for i in range(self.grid_x_dimension):
            for j in range(self.grid_y_dimension):
                grids = QtCore.QRectF(QtCore.QPointF(i*side, j*side), QtCore.QSizeF(side, side))
                self.scene.addRect(grids, pen)

    def create_rovers_list(self):
        """Create new rovers based on user input"""
        self.set_new_grid()
        self.comboRoverSelect.blockSignals(True)
        self.comboRoverSelect.setCurrentIndex(0)
        self.comboRoverSelect.blockSignals(False)
        x_grid_coord = self.grid_x_dimension
        y_grid_coord = self.grid_y_dimension
        num_of_rovers = self.spinNumOfRovers.value()
        self.tableRoverInfo.setRowCount(0)
        self.rovers_list = []
        for x in range(num_of_rovers):
            self.rovers_dict["rover" + str(x)] = QtWidgets.QGraphicsEllipseItem((30*1) - 38, (30*y_grid_coord) - 8, 15, 15)
            self.rovers_dict["rover" + str(x)].setPen(QtGui.QPen(QtGui.QColor("blue")))
            self.rover_coords["rover" + str(x)] = [0, 0, 'N']
            self.scene.addItem(self.rovers_dict["rover"+str(x)])
            self.rovers_list.append("rover" + str(x))
            rowPosition = self.tableRoverInfo.rowCount()
            self.tableRoverInfo.insertRow(rowPosition)
        self.comboRoverSelect.clear()
        rover_names_list = self.rovers_dict.keys()
        self.comboRoverSelect.addItem("[ Select Rover ]")
        self.comboRoverSelect.addItems(rover_names_list)
        # self.table_data = {"Rover Name": self.rovers_list, "X-Coord": [], "Y-Coord": [], "Direction": [] }
        self.reset_coordinates_table_data()
        self.setTableData()

    def reload_rovers(self):
        """Reload rovers list after user input"""
        self.set_new_grid()
        x_grid_coord = self.grid_x_dimension
        y_grid_coord = self.grid_y_dimension
        num_of_rovers = self.spinNumOfRovers.value()

        for x in range(num_of_rovers):
            rover_coords = self.rover_coords["rover" + str(x)]
            rover_y_coord = (y_grid_coord - rover_coords[1])
            rover_x_coord = rover_coords[0]
            self.rovers_dict["rover" + str(x)] = QtWidgets.QGraphicsEllipseItem((30*(rover_x_coord + 1)) - 38, (30*rover_y_coord) - 8, 15, 15)
            self.rovers_dict["rover" + str(x)].setPen(QtGui.QPen(QtGui.QColor("blue")))
            self.scene.addItem(self.rovers_dict["rover" + str(x)])

    def reset_coordinates_table_data(self):
        """Reset coordinates table after user input"""
        x_coords_list = []
        y_coords_list = []
        dir_list = []

        for x in self.rover_coords.keys():
            x_coords_list.append(str(self.rover_coords[x][0]))
            y_coords_list.append(str(self.rover_coords[x][1]))
            dir_list.append(self.rover_coords[x][2])
        self.table_data = {"Rover Name": self.rovers_list, "X-Coord": x_coords_list, "Y-Coord": y_coords_list, "Direction": dir_list }

    def load_selected_rover(self):
        self.selected_rover = self.comboRoverSelect.currentText()
        if self.selected_rover == "[ Select Rover ]":
            pass
        else:
            try:
                curr_coords = self.rover_coords[self.selected_rover]
                self.set_direction = curr_coords[2]
            except Exception:
                pass

    def check_rover_range(self, curr_coords):
        """Check if rover is in bounds before moving"""
        out_of_range = False
        curr_x_coord = curr_coords[0]
        curr_y_coord = curr_coords[1]
        curr_rover_dir = curr_coords[2]

        if curr_x_coord == 0 and self.set_direction == "W":
            out_of_range = True
        if curr_x_coord == self.grid_x_dimension and self.set_direction == "E":
            out_of_range = True
        if curr_y_coord == 0 and self.set_direction == "S":
            out_of_range = True
        if curr_y_coord == self.grid_y_dimension and self.set_direction == "N":
            out_of_range = True
        return out_of_range

    def initiate_rover_move(self, curr_coords):
        """Move rover in direction set by user"""
        curr_x_coord = curr_coords[0]
        curr_y_coord = curr_coords[1]
        curr_rover_dir = curr_coords[2]
        if self.set_direction == "N":
            new_y_coord = curr_y_coord + 1
            self.rover_coords[self.selected_rover] = [curr_x_coord, new_y_coord, self.set_direction]
            self.reload_rovers()
        elif self.set_direction == "W":
            new_x_coord = curr_x_coord - 1
            self.rover_coords[self.selected_rover] = [new_x_coord, curr_y_coord, self.set_direction]
            self.reload_rovers()
        elif self.set_direction == "S":
            new_y_coord = curr_y_coord - 1
            self.rover_coords[self.selected_rover] = [curr_x_coord, new_y_coord, self.set_direction]
            self.reload_rovers()
        elif self.set_direction == "E":
            new_x_coord = curr_x_coord + 1
            self.rover_coords[self.selected_rover] = [new_x_coord, curr_y_coord, self.set_direction]
            self.reload_rovers()
        self.reset_coordinates_table_data()
        self.setTableData()

    def move_rover_forward(self):
        """Call initiate move function if rover is in bounds"""
        curr_coords = self.rover_coords[self.selected_rover]

        if self.check_rover_range(curr_coords):
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Error")
            msg.setInformativeText('Rover is out of range, Please change direction.')
            msg.setWindowTitle("Error")
            msg.exec_()
        else:
            self.initiate_rover_move(curr_coords)

    def check_selected_rover(self):
        """Check if combobox is set to a valid selection"""
        self.selected_rover = self.comboRoverSelect.currentText()
        if self.selected_rover == "[ Select Rover ]":
            return False
        else:
            return True
    def turn_rover_right(self):
        """Turn rover 90 degrees to the right"""
        curr_dir = self.set_direction
        if curr_dir == "N":
            self.set_direction = "E"
        elif curr_dir == "W":
            self.set_direction = "N"
        elif curr_dir == "S":
            self.set_direction = "W"
        elif curr_dir == "E":
            self.set_direction = "S"
        self.reset_coordinates_table_data()
        self.setTableData()

    def turn_rover_left(self):
        """Turn rover 90 degrees to the left"""
        curr_dir = self.set_direction
        if curr_dir == "N":
            self.set_direction = "W"
        elif curr_dir == "W":
            self.set_direction = "S"
        elif curr_dir == "S":
            self.set_direction = "E"
        elif curr_dir == "E":
            self.set_direction = "N"
        self.reset_coordinates_table_data()
        self.setTableData()

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


# coding=utf-8
from __future__ import print_function

from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.clock import Clock

from scenes import scenes_list, scenes

class MultiLineLabel(Label):
    """ Use this class for spliting long text on new lines if need

    """
    def __init__(self, **kwargs):
        super(MultiLineLabel, self).__init__( **kwargs)
        self.text_size = self.size
        self.bind(size=self.on_size)
        self.bind(text=self.on_text_changed)
        self.size_hint_y = None # Not needed here

    def on_size(self, widget, size):
        self.text_size = size[0], None
        self.texture_update()
        self.width = self.parent.width
        if self.size_hint_y is None and self.size_hint_x is not None:
            self.height = max(self.texture_size[1], self.line_height)
        elif self.size_hint_x is None and self.size_hint_y is not None:
            self.width = self.texture_size[0]

    def on_text_changed(self, widget, text):
        self.on_size(self, self.size)

class GUI(FloatLayout):
    """ Main game window

    """
    def __init__(self, **kwargs):
        super(GUI, self).__init__(**kwargs)

    def start_game(self):
        """ Game starts here

        :return:
        """
        self.clear_widgets()
        menu = RenderMenu(pos_hint={'x': 0}, size_hint_y=None,)
        self.add_widget(menu)
        menu.show_menu()

class RenderMenu(Widget):
    """ Build main menu of the app

    """
    def show_menu(self, **kwargs):
        """ Redner main menu of the game

        :param kwargs:
        :return:
        """
        btn = Button(text=u'Новая игра', pos_hint={'x': 0}, size_hint_y=None,)
        btn.bind(on_press=self.new_game)
        self.parent.add_widget(btn)

    def new_game(self, instance):
        """ Start new game

        :param instance:
        :return:
        """
        start_game = RenderScene(name='first_scene')
        self.parent.add_widget(start_game)
        self.parent.remove_widget(instance)
        start_game.start()

class RenderScene(Widget):
    """ Render scenes of the app

    """
    def __init__(self, **kwargs):
        super(RenderScene, self).__init__(**kwargs)
        self.first_scene = kwargs.pop('name')
        self.name = self.first_scene
        self.scene_count = 0
        self.finished = False
        self.prev_scene = None

    def start(self):
        self.show_next_situation()

    def on_touch_down(self, touch):
        """ Render scenes on touch

        :param touch:
        :return:
        """
        if not self.finished:
            self.show_next_situation()
        else:
            self.show_main()

    def show_next_situation(self):
        """ Render and switching between scenes of the game

        :return:
        """
        self.finished = False
        # if we showed all text - then we could show new scene in other case - show all text
        if not self.prev_scene or (self.prev_scene and self.prev_scene.finished):
            if self.prev_scene:
                self.parent.remove_widget(self.prev_scene)
            scene = scenes.get(self.name, [])
            if len(scene) > self.scene_count:
                text = RenderText(**scene[self.scene_count])
                self.parent.add_widget(text)
                text.start_show()
                self.scene_count += 1
                self.prev_scene = text
            else:
                index = scenes_list.index(self.name)
                if len(scenes_list) > index+1:
                    self.scene_count = 0
                    self.name = scenes_list[index+1]
                    scene = scenes.get(self.name, [])
                    text = RenderText(**scene[self.scene_count])
                    self.parent.add_widget(text)
                    text.start_show()
                    self.scene_count += 1
                    self.prev_scene = text
                else:
                    text = RenderText(text='Game ended')
                    self.parent.add_widget(text)
                    text.start_show()
                    self.finished = True
                    self.prev_scene = text
        else:
            self.prev_scene.show_all()

    def show_main(self):
        """ Return to the main menu

        :return:
        """
        self.finished = False
        self.parent.start_game()

class RenderText(MultiLineLabel):
    """ Use for rendering text
        :text_speed - speed of the showing text. TBD

    """

    def __init__(self, **kwargs):
        self.text_speed = kwargs.get('text_speed', 100)
        self.full_text = list(reversed(kwargs.pop('text', ''))) # need to make reverse to show in correct order
        self.finished = False
        super(RenderText, self).__init__(**kwargs)

    def start_show(self):
        """ Show text with interval

        :return:
        """
        show_time = 1/self.text_speed
        Clock.schedule_interval(self.text_update, show_time)

    def show_all(self):
        """ Show all text by clicking on screen

        :return:
        """
        Clock.unschedule(self.text_update)
        if self.full_text:
            self.finished = True
            self.text += ''.join(list(reversed(self.full_text)))

    def text_update(self, dt):
        """ update text of the label

        :param dt: needed for the Clock function
        :return:
        """
        if self.full_text:
            self.text += self.full_text.pop()
        else:
            self.finished = True
            return False


#!/usr/bin/python3

file = input("Enter file name: ")
if file == '':
    file = "code/mbox-short.txt"
elif file == 'na na boo boo':
    print(file.upper() + ' - ' + "You have been punk'd!")
    exit()

try:
    fhand = open(file)
except:
    print("File \"%s\" does not exist." % file)
    exit()

count = 0
num = 0
for line in fhand:
    if line.startswith('X-DSPAM-Confidence:'):
        start_pos = line.find(':') + 1
        line = line.rstrip()
        spam = line[start_pos:].lstrip()
        try:
            spam = float(spam)
        except:
            continue
        count += 1
        num += spam

spam_avg = str(num / count)
print("Average spam confidence: " + spam_avg)


from PyQt5 import QtCore, QtGui, QtWidgets
import encodeUi as eui
import decodeUi as dui
import Steganography.audio_to_text

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(450, 450)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setContentsMargins(10, 10, 10, 10)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.frame = QtWidgets.QFrame(self.centralwidget)
        self.frame.setStyleSheet("QFrame\n"
"{\n"
"    background-color: rgb(56, 67, 84);\n"
"    \n"
"    color: rgb(255, 255, 255);\n"
"    border-radius:10px;\n"
"}")
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")

        #encode button
        self.Encode_Btn = QtWidgets.QPushButton(self.frame)
        self.Encode_Btn.setGeometry(QtCore.QRect(170, 150, 89, 31))
        self.Encode_Btn.setObjectName("Encode_Btn")
        self.Encode_Btn.clicked.connect(self.encode_call)

        #decode button
        self.Decode_Btn = QtWidgets.QPushButton(self.frame)
        self.Decode_Btn.setGeometry(QtCore.QRect(170, 220, 89, 31))
        self.Decode_Btn.setObjectName("Decode_Btn")
        self.Decode_Btn.clicked.connect(self.decode_call)

        self.verticalLayout.addWidget(self.frame)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def encode_call(self):
        self.encode_window = QtWidgets.QMainWindow()
        self.encode_ui = eui.Ui_MainWindow()
        self.encode_ui.setupUi(self.encode_window)
        self.encode_window.show()

    def decode_call(self):
        self.decode_window = QtWidgets.QMainWindow()
        self.decode_ui = dui.Ui_MainWindow()
        self.decode_ui.setupUi(self.decode_window)
        self.decode_window.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.Encode_Btn.setText(_translate("MainWindow", "Encode"))
        self.Decode_Btn.setText(_translate("MainWindow", "Decode"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


### one code one day
### 2020/04/12
### leetcode 495 目标和

### 记忆化搜索 比背包DP慢

def findTargetSumWays(self, nums: List[int], S: int) -> int:
    def backtrack(first, target):
        if((first, target) in dp):
            return dp[(first, target)]
        else:
            count = 0
            if(target == 0):
                count += 1
            for i in range(first, len(nums)):
                if(target >= nums[i]):
                    count += backtrack(i+1, target-nums[i])
            dp[(first, target)] = count
            return count
    arrSum = sum(nums)
    if(arrSum < S or arrSum < (-1) * S):
        return 0
    else:
        if((arrSum + S) % 2 == 0):
            target = (arrSum + S) // 2
        else:
            return 0
        dp = {}
        return backtrack(0, target)


# optional flask dependency
from flask import Flask
from flask import request
from flask import jsonify
from metadate import parse_date

app = Flask(__name__)

@app.route("/metadate", methods=["GET", "POST"])
def root():
    text = request.args.get("text")
    print(text)
    future = request.args.get("future")
    future = future.lower() == 'true' if future else True
    res = parse_date(text, future)
    if res:
        res = res.to_dict()
    return jsonify(res)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8002)


from obiwan import priors
import os

def test_ELG():
    elg= priors.EmptyClass()

    d= priors.Data()
    outdir='.'
    #outdir='/home/kaylan/mydata/priors_data'
    #d.fetch(outdir)
    #elg.data= d.load_elg(DR=3)

    #elg.model= KDE_Model('elg',elg.data,outdir)
    #elg.model.kde= elg.model.get_kde()

    p= priors.Plot(outdir)
    #p.elg(elg.data, elg.model.df_wcut,elg.model.df_for_kde,
    #      elg.model.kde)
    assert(p.outdir == os.path.join(outdir,'plots'))


from datetime import (
    timedelta,
    datetime
)
from flask import current_app
from sqlalchemy import desc

from app import db
from app.dao.dao_utils import transactional
from app.models import InboundSms
from app.statsd_decorators import statsd

@transactional
def dao_create_inbound_sms(inbound_sms):
    db.session.add(inbound_sms)

def dao_get_inbound_sms_for_service(service_id, limit=None, user_number=None):
    q = InboundSms.query.filter(
        InboundSms.service_id == service_id
    ).order_by(
        InboundSms.created_at.desc()
    )

    if user_number:
        q = q.filter(InboundSms.user_number == user_number)

    if limit:
        q = q.limit(limit)

    return q.all()

def dao_get_paginated_inbound_sms_for_service(
    service_id,
    older_than=None,
    page_size=None
):
    if page_size is None:
        page_size = current_app.config['PAGE_SIZE']

    filters = [InboundSms.service_id == service_id]

    if older_than:
        older_than_created_at = db.session.query(
            InboundSms.created_at).filter(InboundSms.id == older_than).as_scalar()
        filters.append(InboundSms.created_at < older_than_created_at)

    query = InboundSms.query.filter(*filters)

    return query.order_by(desc(InboundSms.created_at)).paginate(
        per_page=page_size
    ).items

def dao_count_inbound_sms_for_service(service_id):
    return InboundSms.query.filter(
        InboundSms.service_id == service_id
    ).count()

@statsd(namespace="dao")
@transactional
def delete_inbound_sms_created_more_than_a_week_ago():
    seven_days_ago = datetime.utcnow() - timedelta(days=7)

    deleted = db.session.query(InboundSms).filter(
        InboundSms.created_at < seven_days_ago
    ).delete(synchronize_session='fetch')

    return deleted

def dao_get_inbound_sms_by_id(service_id, inbound_id):
    return InboundSms.query.filter_by(
        id=inbound_id,
        service_id=service_id
    ).one()


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

pd.set_option('display.max_rows', 1000)
pd.set_option('display.max_columns', 1000)
# 每年38个处理的非传递性
path = 'C:/Users/97899/Desktop/N/'
path_D = {"huang/huang_compe.xls": ["rank_nested","rank_no_nested"]}
df_ex = pd.read_excel(path + "实验处理_ex.xls")
title = ["Competition ranking about Carex korshinskyi in nested",
         "Competition ranking about Carex korshinskyi in no nested",]
columns = ['顺序', '氮素', '频率', '刈割']
m = -1
for key in path_D.keys():
    for sheet in path_D[key]:

        df_Int = pd.read_excel(path + key, sheet_name=sheet)
        df_Int = pd.concat([df_Int, pd.DataFrame(columns=columns)])
        m=m+1
        '''Intransitivity and experiment deal'''

        for item in range(df_Int.shape[0]):
            for jtem in range(df_ex.shape[0]):
                if int(df_Int.iloc[item, 0]) == int(df_ex.iloc[jtem, 1]):
                    df_Int.loc[item, '顺序'] = df_ex.iloc[jtem, 1]
                    df_Int.loc[item, '氮素'] = df_ex.iloc[jtem, 2]
                    df_Int.loc[item, '频率'] = df_ex.iloc[jtem, 3]
                    df_Int.loc[item, '刈割'] = df_ex.iloc[jtem, 4]
        df_Int.drop([0, 19], inplace=True)
        df_Int.drop([2008.0], axis=1, inplace=True)

        '''Group'''
        gb1 = df_Int.groupby("频率")
        gx = {}
        for g1 in gb1:
            gb2 = g1[1].groupby("刈割")
            gx[g1[0]] = {}
            for g2 in gb2:
                gb3 = g2[1].groupby("氮素")
                gx[g1[0]][g2[0]] = []
                for g3 in gb3:
                    print(g3[0])
                    g0 = g3[1].drop(["顺序", "氮素", "刈割", "频率", "Unnamed: 0"], axis=1)
                    # print(g0)
                    mean = np.mean([i for i in g0.values[0] if i > 0])
                    if np.isnan(mean):
                        gx[g1[0]][g2[0]].append(0)
                    else:
                        gx[g1[0]][g2[0]].append(mean)
                    # print(gx[g1[0]][g2[0]])
        '''Figure'''

        result = []
        for key1 in gx.keys():
            for key2 in gx[key1].keys():
                sum_ = sum(gx[key1][key2])
                result.append([i for i in gx[key1][key2]])
        category_names = ['N=0', 'N=1', 'N=2', 'N=3', 'N=5', 'N=10', 'N=15', 'N=20', 'N=50']

        results = {
            'LF-NM': result[0],
            'LF-M': result[1],
            'HF-NM': result[2],
            'HF-M': result[3],
        }

        def survey(results, category_names):
            """
            Parameters
            ----------
            results : dict
                A mapping from question labels to a list of answers per category.
                It is assumed all lists contain the same number of entries and that
                it matches the length of *category_names*.
            category_names : list of str
                The category labels.
            """
            labels = list(results.keys())
            data = np.array(list(results.values()))
            data_cum = data.cumsum(axis=1)
            category_colors = plt.get_cmap('RdYlGn')(
                np.linspace(0.15, 0.85, data.shape[1]))

            fig, ax = plt.subplots(figsize=(9.2, 5))
            ax.invert_yaxis()
            ax.xaxis.set_visible(False)
            ax.set_xlim(0, np.sum(data, axis=1).max())

            for i, (colname, color) in enumerate(zip(category_names, category_colors)):
                widths = data[:, i]
                starts = data_cum[:, i] - widths
                ax.barh(labels, widths, left=starts, height=0.5,
                        label=colname, color=color)
                xcenters = starts + widths / 2
                print(labels)

                r, g, b, _ = color
                text_color = 'black' if 0 < r * g * b else "red"
                for y, (x, c) in enumerate(zip(xcenters, widths)):
                    if c == 0:
                        continue
                    else:
                        ax.text(x, y, str("%.2f" % c), ha='center', va='center',
                                color=text_color,fontsize=15)
            ax.legend(ncol=1, bbox_to_anchor=(1.1, 0.5), fontsize=13)
            ax.set_title(title[m],fontsize=20)

            return fig, ax

        # plt.title("Biomass")
        survey(results, category_names)
        plt.show()


from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, render_to_response
from django.contrib import auth
from django.core.context_processors import csrf
#cross-site request forgery --> method for people hacking into website
from GradeTracker.models import Student, Course, Graded_Activities, SubGraded_Activities, Templates
from GradeTracker.forms import courseAdd, activityAdd, subactivityAdd, MyRegistrationForm

def addSub(request, student_id, course_id, graded_activity_id ):
    if request.user.is_authenticated():
        student = Student.objects.filter(user=request.user)[0]
        activity = get_object_or_404( Graded_Activities, pk=graded_activity_id )
        course = get_object_or_404( Course, pk=course_id )
        if request.method == 'POST':
            form = subactivityAdd(request.POST)
            if form.is_valid():
                activity.subgraded_activities_set.create( subactivity_name = form.cleaned_data['subactivityName'], subgrade_weight = form.cleaned_data['subactivityWeight'] )
                return HttpResponseRedirect('/GT/' + str(student.id) +'/' + str(activity.course.id)  + '/' + str(activity.id))
        else:
            form = subactivityAdd()
        return render(request, 'GradeTracker/activities.html', {'form':form, 'activity':activity, 'student':student, 'course':course} )
    else:
        return render(request, 'GradeTracker/login.html')

def deleteSubGradedActivity(request, subactivity_id):
    subactivity = get_object_or_404(SubGraded_Activities, pk=subactivity_id)
    activityReturned = subactivity.main_category.id
    subactivity.delete()
    return HttpResponseRedirect('/GT/' + str(activityReturned) )

def editSubGradedActivity(request):
    pass


import numpy
import matplotlib.pyplot as plt

def plot_stochastic_processes(processes, title):
    """
    This method plots a list of stochastic processes with a specified title
    :return: plots the graph of the two
    """
    plt.style.use(['bmh'])
    fig, ax = plt.subplots(1)
    fig.suptitle(title, fontsize=16)
    ax.set_xlabel('Time, t')
    ax.set_ylabel('Simulated Asset Price')
    x_axis = numpy.arange(0, len(processes[0]), 1)
    for i in range(len(processes)):
        plt.plot(x_axis, processes[i])
    plt.show()


from pandas import read_csv
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from  sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from keras.regularizers import l2
from sklearn.model_selection import train_test_split
from keras.constraints import maxnorm
import pandas as pd
from sklearn import svm

model_id = "drugbank_approved_joined_logP_SVR_rbf"
dataframe1 = read_csv("../ecfp-drugbank-approved.csv", delimiter = ',')
dataframe2 = read_csv("../maccskeys-drugbank-approved.csv", delimiter = ',')
dataframe  = pd.concat([dataframe1, dataframe2], axis=1)

dataset = dataframe.values
# split into input (X) and output (Y) variables
X = dataset[:,:]
Y = np.loadtxt("../drugbank_approved_logP.AlogP.value")
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)

# define wider model
model =  svm.SVR(kernel='rbf', C=10, gamma=0.2)

#hyperparameter; do it in the following pair

C=[1e-3, 1e-2, 1e-1, 1, 10, 100, 1000]
kernel=['rbf', 'linear', 'poly','sigmoid']
gamma=[0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0]
#coef0 for poly and sigmoid; degree for poly
coef0=[]
degree=[1,3,5,7,9]
"""
example
svr_rbf = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=.1)
svr_lin = SVR(kernel='linear', C=100, gamma='auto')
svr_poly = SVR(kernel='poly', C=100, gamma='auto', degree=3, epsilon=.1,
                       coef0=1)
linear: C
poly: C, degree, gamma, coef0
rbf: C, gamma,
sigmoid: C, gamma, coef0
"""
resultscsv='gridscores-'+str(model_id)+".csv"

import pickle
import scipy
from scipy import stats
nlayer=1
for i in range(1):
    estimators = svm.SVR(kernel='rbf',C=100, gamma=0.1 )

    history=estimators.fit(X_train, Y_train, )
    print(history.score(X_train, Y_train,))
    logFilePath = './log'+str(model_id)+'.txt'
    fobj = open(logFilePath, 'a')
    fobj.write('model id: ' + str(model_id)+'\n')
    fobj.write('x_train shape: ' + str(X_train.shape) + '\n')
    fobj.write('x_test shape: ' + str(X_test.shape)+'\n')
    fobj.write('training accuracy: ' + str(history.score(X_train, Y_train,)) + '\n')
    #fobj.write('model evaluation results: ' + str(score[0]) + '  ' +str(score[-1])+'\n')
    fobj.write('---------------------------------------------------------------------------\n')
    fobj.write('\n')
    fobj.close()

    prediction0=estimators.predict(X_train)
    print("train-pearson: ",scipy.stats.pearsonr(Y_train,prediction0))

    prediction=estimators.predict(X_test)
    print("test-pearson: ",scipy.stats.pearsonr(Y_test,prediction))
#hyperparameter; do it in the following pair

#save raw output
prediction0=estimators.predict(X_train)
predictedtxt0 = 'predicted_train_'+str(model_id)+'.txt'
truetxt0 = 'true_train_'+str(model_id)+'.txt'
np.savetxt(predictedtxt0, prediction0, fmt='%f')
np.savetxt(truetxt0, Y_train, fmt='%f')

predictedtxt = 'predicted_'+str(model_id)+'.txt'
truetxt = 'true_'+str(model_id)+'.txt'
np.savetxt(predictedtxt, prediction, fmt='%f')
np.savetxt(truetxt, Y_test, fmt='%f')

exit()


"""
Nombre: dashboard.py
objetivo: Construye el menu principal de la aplicacion de base de datos
Autor: Jose Francisco Garcia Fuentes
Fecha: 10 de octubre de 2019
"""

#cramos clase
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
#Enlazar otro archivo y extrar una clase
from insertar import inserto
from menusuperior import desplegable
import os

raiz=Tk()
raiz.title("AGREGAR")
desplegable(raiz)

#-------------------my code----------------------------------
 #----------------Botones y vampos---------------------------

miFrame=Frame(raiz, height=600, width=800, padx=40, pady=15)
miFrame.config( bg = '#FCF5E2')
miFrame.pack()

miClave=StringVar()
miNombre=StringVar()
miSueldo=StringVar()

labelClave=Label(miFrame, text="Clave:")
labelClave.grid(row=0, column=0, sticky="e", padx=10, pady=10)
labelClave.config( bg = '#FCF5E2')
cuadroClave=Entry(miFrame, textvariable=miClave)
cuadroClave.grid(row=0, column=1, padx=10, pady=10)

labelNombre=Label(miFrame, text="Nombre:")
labelNombre.grid(row=1, column=0, sticky="e", padx=10, pady=10)
labelNombre.config( bg = '#FCF5E2')
cuadroNombre=Entry(miFrame, textvariable=miNombre)
cuadroNombre.grid(row=1, column=1, padx=10, pady=10)

labelSueldo=Label(miFrame, text="Sueldo:")
labelSueldo.grid(row=2, column=0, sticky="e", padx=10, pady=10)
labelSueldo.config( bg = '#FCF5E2')
cuadroSueldo=Entry(miFrame, textvariable=miSueldo)
cuadroSueldo.grid(row=2, column=1, padx=10, pady=10)

def btguardar():

    inserto(miClave.get()[:4], miNombre.get()[:50], miSueldo.get()[:11])
    miClave.set("")
    miNombre.set("")
    miSueldo.set("")

botonguardar=Button(miFrame, text="GUARDAR", command=btguardar)
botonguardar.grid(row=3, column=1)
botonguardar.config(bg = '#B4EAF1')

#Mostramos ventana
raiz.mainloop()


from datetime import datetime
from dimagi.utils.couch.database import get_db
from dateutil.relativedelta import relativedelta
from patient_group import PathfinderPatientGroup
from dimagi.utils.parsing import string_to_datetime

def get_patients_by_provider(domain, provider):
    return get_db().view('pathfinder/pathfinder_gov_reg_by_username', keys=[[domain, provider]], include_docs=True).all()

def retrieve_patient_group(user_ids, domain, year, month):
    """
    Given a set of user IDs, retrieve all patients matching that set.  Update them with followup and referral form info.
    """
    caseid_set = set()
    patients = {}
    year = int(year)
    month = int(month)
    form_now = datetime(year, month, 1)+relativedelta(months=1)-relativedelta(seconds=1)
    pyear = 0
    pmonth = 0
    for result in user_ids:
        rform = result['doc']['form'] #shortcut
        try: # strptime() can fail if the CHW enters weird data.
            regdate = string_to_datetime(rform['patient']['date_of_registration'])
            if regdate > form_now:
                continue
        except:
            pass
        p = dict()
        age_tmp = string_to_datetime(rform['patient']['date_of_birth'])
        p['age'] = int((form_now - age_tmp).days / 365.25)
        p.update(rform['case'])
        p.update(rform['patient'])
        caseid_set.add(p['case_id'] )
        p['ward'] = p['village']
        p['registered_this_month'] = True if (regdate.year == form_now.year and regdate.month == form_now.month) else False
        p['followup_this_month'] = 0
        p['referrals_made'] = 0
        for i in ['provider',
                  'registration_and_followup_hiv',
                  'hiv_status_during_registration',
                  'hiv_status_after_test',
                  'referrals_hiv',
                  'ctc',
                  'medication_given',
                  'services',
                  'referrals']:
            if not i in p:
                p[i] = ''
        patients[p['case_id']] = p
    update_patients_with_followups(domain, patients, caseid_set,year,month)
    update_patients_with_referrals(patients,caseid_set,year,month)
    ## I chose not to remove patients without followups this month -- sometimes there's a referral in a month with no followup.
    # map(lambda x: patients.__delitem__(x), filter(lambda y: not patients[y]['followup_this_month'], patients.keys()))
    gp =  PathfinderPatientGroup()
    gp += patients.values()
    return gp

def update_patients_with_followups(domain, patients, caseid_set, year, month):
    """
    Given a set of patients, update them with info from followup forms.
    """
    followup_keys = [[domain, x, year, month] for x in list(caseid_set)]
    followups = get_db().view('pathfinder/pathfinder_gov_followup_by_caseid', keys = followup_keys, include_docs=True).all()
    for f in followups:
        if not f['key'][1] in patients:
            continue
        p = patients[f['key'][1]]
        f = f['doc']['form']
        fp = f['patient']
        p['provider'] = f['meta']['userID']

        # The code below exists to hack around issues like people coming back to life after being dead,
        # multiple followups in a single month having different services, medication, and/or referral values,
        # and so on.

        if not p.has_key('registration_and_followup_hiv') or p['registration_and_followup_hiv'] == 'continuing' or p['registration_and_followup_hiv'] == '': # don't allow a value of 'dead' to change
            if fp.has_key('reg_followup'):
                p['registration_and_followup_hiv'] = fp['reg_followup']
        if p.has_key('followup_this_month'):
            p['followup_this_month'] += 1
        else:
            p['followup_this_month'] = 1
        if "medication_given" in fp and fp['medication_given']:
            p['medication_given'] += fp['medication_given'] + " "
        if "services_given" in fp and fp['services_given']:
            p['services'] += fp['services_given'] + " "
        if "any_referral" in fp and fp['any_referral'] == "yes":
            p['referrals'] += fp['referrals'] + " "
        p.update(fp)

def update_patients_with_referrals(patients, ids, year,month):
    """
    Given a set of patients, count how many completed referrals they had in that month.
    """
    refs = get_db().view('pathfinder/pathfinder_gov_referral', keys=[[x, int(year), int(month)] for x in list(ids)], include_docs=True).all()

    for p in patients: patients[p]['referrals_completed'] = 0
    for r in refs:
        if r['doc']['form']['client']['referral'] == 'yes':
            patients[r['doc']['form']['case']['case_id']]['referrals_completed'] += 1


def add(str1, str2, str_list):
    list1 = list(reversed(list(str1)))
    list2 = list(reversed(list(str2)))
    sum = 0  # 每两位相加之和
    tmp = 0  # 进位
    result = list()  #结果

    for i in range(max(len(list1), len(list2))):
        try:
            first = list1[i]
        except:
            first = '0'
        try:
            second = list2[i]
        except:
            second = '0'
        sum = str_list.index(first) + str_list.index(second) + tmp

        if sum < 36:  # 没有进位的情况
            tmp = 0
            result.append(str_list[sum])
        else:  # 有进位的情况
            tmp = sum // 36
            result.append(str_list[sum % 36])
    if tmp:
        result.append('1')
    return ''.join(list(reversed(result)))

if __name__ == '__main__':
    str_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    print(add('z1y1', '112z', str_list))  # a211


import glob
import os
import shutil
import sys
from pathlib import Path
import cv2

def change_dir(new_dir):
    os.chdir(new_dir)
    return glob.glob('*')

home = str(Path.home())

src = home + '\\AppData\\Local\\Packages\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\LocalState\\Assets'
dst = home + '\\Desktop' + '\\test'  # empty folder

if change_dir(dst) != []:
    os.startfile(dst)
    sys.exit(0)

file_names = change_dir(src)
length = len(file_names)

for i in range(length):
    shutil.copy2(src + '/' + file_names[i], dst)

file_names = change_dir(dst)

for j in file_names:
    os.rename(j, j + '.jpg')

for k in range(length):
    image = cv2.imread(file_names[k] + '.jpg')
    height = image.shape[0]
    width = image.shape[1]
    if height != 1080 and width != 1920:
        os.remove(file_names[k] + '.jpg')

os.startfile(dst)


# Jorge Calzada Asenjo
# Python 3.7
# Challenge 1.04 - The Buffer

"""
How many men can use wall-mounted urinals at the same time without breaking
the rule that one must always leave a buffer between a urinal and other
urinal.
"""

'''
Example of entry:
5
1
2
3
4
5

Output for that example:
1
1
2
2
3
'''

import math

cases = int(input())

for value in range(0, cases):
    numberUrinals = int(input())
    result = int(numberUrinals / 2 + numberUrinals % 2)
    print(result)


# -*- encoding: utf-8 -*-
import supriya

material = []

voices = [
    'Daniel',
    'Fiona',
    'Victoria',
    'Tessa',
    'Karen',
    'Thomas',
    ]

texts = [
    'Be true.',
    "Don't leave me.",
    'Talk to me.',
    'Feed me.',
    'Heal me.',
    'Dance with me.',
    'Teach me.',
    'Hold me.',
    'Touch me.',
    'Love me.',
    'Let me help you.',
    "Don't hurt me.",
    'Show me a path.',
    'Give me light.',
    'Release me.',
    ]

for voice in voices:
    for text in texts:
        material.append(supriya.Say(text, voice=voice))

material = tuple(material)


# # https://atcoder.jp/contests/abc140/tasks/abc140_e
# # https://atcoder.jp/contests/agc005/tasks/agc005_b
# # https://atcoder.jp/contests/abc157/tasks/abc157_e

# '''
#     [Bit]
# '''
# class Bit:
#     """ used for only int(>=0)
#         1-indexed (ignore 0-index)
#     """
#     def __init__(self, n):
#         self.size = n
#         self.tree = [0] * (n + 1)
#         self.depth = n.bit_length()

#     def sum(self, i):
#         s = 0
#         while i > 0:
#             s += self.tree[i]
#             i -= i & -i
#         return s

#     def add(self, i, x):
#         while i <= self.size:
#             self.tree[i] += x
#             i += i & -i

#     def lower_bound(self, x):
#         """ 累積和がx以上になる最小のindexと、その直前までの累積和 """
#         sum_ = 0
#         pos = 0
#         for i in range(self.depth, -1, -1):
#             k = pos + (1 << i)
#             if k <= self.size and sum_ + self.tree[k] < x:
#                 sum_ += self.tree[k]
#                 pos += 1 << i
#         return pos + 1, sum_

#     def get_less_than_x_cnt(self, x):
#         """ 累積和がx未満 の個数 """
#         lb_pos, lb_sum = self.lower_bound(x)
#         return lb_pos-1

#     def get_less_than_and_x_cnt(self, x):
#         """ 累積和がx以下 の個数 """
#         lb_pos, lb_sum = self.lower_bound(x+1)
#         return lb_pos-1

#     def get_more_than_x_cnt(self, x):
#         """ 累積和がxより大きい 個数 """
#         return self.size - self.get_less_than_and_x_cnt(x)

# MAX = 200001
# # MAX = 5
# bit = Bit(MAX)
# for i in range(1,MAX+1):
#     bit.add(i,1)

# already = [False]*MAX
# n = int(input())
# pl = list(map(int, input().split()))
# ansl = []
# for p in pl:
#     if not already[p]:
#         bit.add(p,-1)
#         already[p] = True
#     # print(bit.tree)
#     ans,_ = bit.lower_bound(1)
#     # print(ans)
#     ansl.append(ans)

# for a in ansl: print(a)

MAX = 200001
n = int(input())
pl = list(map(int, input().split()))
curr_pos = 0
already = [False]*MAX

for p in pl:
    if p == curr_pos:
        while True:
            curr_pos += 1
            if already[curr_pos] == False:
                break
    print(curr_pos)
    already[p] = True


import joblib
import json
import os
import pandas as pd

def init():
    global model
    model_path = os.path.join(os.getenv("AZUREML_MODEL_DIR"), "hd_model.pkl")
    model = joblib.load(model_path)

def run(request):
    data = json.loads(request)
    feats = pd.DataFrame.from_records(data)
    print("Received matchup = ", feats)
    result = model.predict(feats)
    print("Prediction : 0 for Team1, 1 for Team2 = ", result)
    return result.tolist()


"""empty message

Revision ID: c139e0419ea4
Revises: 785210c85a4e
Create Date: 2021-08-11 11:51:29.391270

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'c139e0419ea4'
down_revision = '785210c85a4e'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('experience', sa.Column('total_number_of_guests', sa.Integer(), nullable=True))
    op.drop_column('experience', 'Total_number_of_guests')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('experience', sa.Column('Total_number_of_guests', sa.INTEGER(), autoincrement=False, nullable=True))
    op.drop_column('experience', 'total_number_of_guests')
    # ### end Alembic commands ###


from aws_cdk import core as cdk
from aws_cdk import (
    core,
    aws_ec2 as _ec2,
    aws_s3 as _s3
)

class HuiCustomVpcStack(cdk.Stack):

    def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # The code that defines your stack goes here
        dev_configs = self.node.try_get_context("envs")["dev"]

        #Custom VPC
        custom_vpc = _ec2.Vpc(
            self,
            "huicustomVPC",
            cidr=dev_configs['vpc_configs']['vpc_cidr'],
            max_azs=2,
            nat_gateways=1,
            subnet_configuration=[
                _ec2.SubnetConfiguration(
                    name="publicSubnet", cidr_mask=dev_configs['vpc_configs']['cidr_mask'],
                    subnet_type=_ec2.SubnetType.PUBLIC
                ),
                _ec2.SubnetConfiguration(
                    name="privateSubnet", cidr_mask=dev_configs['vpc_configs']['cidr_mask'],
                    subnet_type=_ec2.SubnetType.PRIVATE
                ),
                _ec2.SubnetConfiguration(
                    name="dbSubnet", cidr_mask=dev_configs['vpc_configs']['cidr_mask'],
                    subnet_type=_ec2.SubnetType.ISOLATED
                )
            ]
        )

        #Tag the VPC resources
        core.Tag.add(custom_vpc, "Billing", "HuiApplication")

        huibucket = _s3.Bucket(
            self,
            "HuiBucketId"
        )

        core.Tag.add(huibucket, "Billing", "HuiBucket")


from euler import primes
from itertools import islice
from sys import exit

all_primes = list(islice(primes(), 1000))

def decompose(n):
    for p in all_primes:
        if p*p > n: break
        while n % p == 0:
            n //=p
            yield p
    if n > 1:
        yield n

i = 2*3*5*7
while True:
    j = 0
    while len(set(decompose(i))) == 4:
        i += 1
        j += 1
        if j == 4:
            print(i-4)
            exit(0)
    i += 1


zakupy = {}

zakupy['chemia'] = ['płyn do nacz', 'pasta', 'szampon']
zakupy['nabiał'] = ['ser', 'mleko', 'lody']

print(zakupy)

for k in zakupy.keys():
    print(f'Klucz: {k}')

for v in zakupy.values():
    print(f"Wartość: {v}")

for klucz, wart in zakupy.items():
    print(f'Klucz {klucz} ma wartość {wart}')


import string
import sys,os
try:
  import xml.etree.cElementTree as ET
except ImportError:
  import xml.etree.ElementTree as ET

def getAllXml(path):
    txt = []
    cls = []
    for root, dirs, files in os.walk(path):
        for img_name in files:
            if not img_name.lower ().endswith (('.bmp', '.jpeg', '.jpg', '.png', '.tif', '.tiff')):
                continue
            imgpath = os.path.join (root, img_name)
            xml_name = img_name[0:img_name.find (".")]+".xml"
            xmlpath = os.path.join (root, xml_name)
            if (os.path.isfile (xmlpath) == True):
                tree = ET.parse (xmlpath)
                if (tree == None): continue
                gen = tree.getroot ()
                obj = gen.findall ("object")
                for item in obj:
                    str = ""
                    str += imgpath
                    name = item.find ("name").text
                    #name=name[name.find(" ")+1:len(name)]
                    if (name.find ("snail") != -1):
                        name = "snail"
                    elif (name.find ("coin") != -1):
                        name = "coin"
                    elif (name.find ("eel") != -1):
                        name = "eel"
                    elif (name.find ("female_sturgeon") != -1):
                        name = "female_sturgeon"
                    elif (name.find ("male_sturgeon") != -1):
                        name = "male_sturgeon"
                    elif (name.find ("female") != -1):
                        name = "female"
                    elif (name.find ("male") != -1):
                        name = "male"
                    elif (name.find ("carapace") != -1):
                        name = "carapace"
                    elif (name.find ("carb") != -1 or name.find ("crab") != -1):
                        name = "crab"
                    else:
                        print ("label error!,name is :", name)
                        continue
                    bndbox = item.find ("bndbox")
                    x1 = bndbox.find ("xmin").text
                    y1 = bndbox.find ("ymin").text
                    x2 = bndbox.find ("xmax").text
                    y2 = bndbox.find ("ymax").text
                    str += "," + (x1) + "," + (y1) + "," + (x2) + "," + (y2)
                    #str += ",crab"
                    str +=","+name
                    if(name not in cls):
                        cls.append(name)
                    txt.append (str)
            else:
                str = ""
                name = "eel"
                if (name not in cls):
                    cls.append (name)
                str += imgpath+",0,0,1,1,"+name
                txt.append(str)

    return txt,cls

if __name__ == '__main__':
    path="/home/sy/crab/unused/fish/"
    txt,cls=getAllXml(path)
    title="iscas_frcnn_test_fish"
    cnt = 1
    with open ("%s.csv" % title, "w") as f:
        for item in txt:
            cnt +=1
            print (item)
            f.write (item)
            f.write ("\n")
    f.close()
    print("count:",cnt)

    title = "iscas_frcnn_class_test_fish"
    id = 0
    with open ("%s.csv" % title, "w") as f:
        print('female_sturgeon,0',file = f)
        print('male_sturgeon,1',file = f)
        print('eel,2',file = f)
    f.close()


import socket
import threading
from D.Protocol_D import *
import time

def receive_thread(newSocket,address,route):
    count = 0
    while True:
        time.sleep(1)#睡0.5秒,与程序运行时间相加约为1秒
        data_gram = newSocket.recv(BUF_SIZE)
        if(len(data_gram) > 0):
            count = 0
            for temp in port_dict.keys():
                if address[1] == temp:
                     file_name = port_dict[temp] + '.json'
            with open(file_name,'wb') as json_obj:
                json_obj.write(data_gram)
            name = datagram(json_name = file_name)
            route.update_route(name.command,name.index)
        else:
            count = count + 1
            if count == 60:
                print('*****')
                print(address[1])
                route.shut_down(port_dict[address[1]])
                break
    print("close")
    #newSocket.close()

def receiver(route):
    HOST = '127.0.0.1'
    PORT = PC_PORT
    ADDR = (HOST,PORT)
    recSocket = socket.socket()
    #recSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    recSocket.bind(ADDR)
    recSocket.listen(10)
    while True:
        print("waiting for client")
        newSocket,destAddr = recSocket.accept()
        print("I can heiheihei")
        received_thread = threading.Thread(target = receive_thread,args = (newSocket,destAddr,route,))
        received_thread.start()


import argparse
import os
from math import log10

import pytorch_ssim
from data_utils import load_training_data, load_val_data, do_transform
from loss import GeneratorLoss
from model import Generator, Discriminator

import pandas as pd
import torch.optim as optim
import torch.utils.data
import torchvision.utils as utils
from torch.autograd import Variable
from torch.utils.data import DataLoader
from tqdm import tqdm

parser = argparse.ArgumentParser(description='Train Super Resolution Models')
parser.add_argument('--crop_size', default=90, type=int, help='training images crop size')
parser.add_argument('--upscale', default=4, type=int, choices=[2, 4, 8],
                    help='upscale factor')
parser.add_argument('--epochs', default=100, type=int, help='train epoch number')

if __name__ == '__main__':
    opt = parser.parse_args()

    crop_size = opt.crop_size
    upscale = opt.upscale_factor
    epoch = opt.epochs

    train_set = load_training_data('DIV2K_train_HR', crop_size=crop_size, upscale=upscale)
    val_set = load_val_data('DIV2K_valid_HR', upscale=upscale)
    train_loader = DataLoader(dataset=train_set, num_workers=4, batch_size=64, shuffle=True)
    val_loader = DataLoader(dataset=val_set, num_workers=4, batch_size=1, shuffle=False)

    netG = Generator(upscale)
    print('# generator parameters:', sum(param.numel() for param in netG.parameters()))
    netD = Discriminator()
    print('# discriminator parameters:', sum(param.numel() for param in netD.parameters()))
    generator_loss = GeneratorLoss()

    if torch.cuda.is_available():
        netG.cuda()
        netD.cuda()
        generator_loss.cuda()

    optimizerG = optim.Adam(netG.parameters())
    optimizerD = optim.Adam(netD.parameters())

    results = {'d_loss': [], 'g_loss': [], 'd_score': [], 'g_score': [], 'psnr': [], 'ssim': []}

    for epoch in range(1, epoch + 1):
        trainning_results = {'batch_sizes': 0, 'd_loss': 0, 'g_loss': 0, 'd_score': 0, 'g_score': 0}

        netG.train()
        netD.train()
        for data, target in train_loader:
            g_update_first = True
            batch_size = data.size(0)
            trainning_results['batch_sizes'] += batch_size

            real_img = Variable(target)
            if torch.cuda.is_available():
                real_img = real_img.cuda()
            z = Variable(data)
            if torch.cuda.is_available():
                z = z.cuda()
            generated_img = netG(z)

            netD.zero_grad()
            real_out = netD(real_img).mean()
            generate_out = netD(generated_img).mean()
            d_loss = 1 - real_out + generate_out
            d_loss.backward(retain_graph=True)
            optimizerD.step()

            netG.zero_grad()
            g_loss = generator_loss(generate_out, generated_img, real_img)
            g_loss.backward()

            generated_img = netG(z)
            generate_out = netD(generated_img).mean()

            optimizerG.step()
            trainning_results['g_loss'] += g_loss.item() * batch_size
            trainning_results['d_loss'] += d_loss.item() * batch_size
            trainning_results['d_score'] += real_out.item() * batch_size
            trainning_results['g_score'] += generate_out.item() * batch_size

        netG.eval()
        out_path = 'training_results/SRF_' + str(upscale) + '/'
        if not os.path.exists(out_path):
            os.makedirs(out_path)

        with torch.no_grad():
            val_bar = tqdm(val_loader)
            valing_results = {'mse': 0, 'ssims': 0, 'psnr': 0, 'ssim': 0, 'batch_sizes': 0}
            val_images = []
            for val_lr, val_hr_restore, val_hr in val_bar:
                batch_size = val_lr.size(0)
                valing_results['batch_sizes'] += batch_size
                lr = val_lr
                hr = val_hr
                if torch.cuda.is_available():
                    lr = lr.cuda()
                    hr = hr.cuda()
                sr = netG(lr)

                batch_mse = ((sr - hr) ** 2).data.mean()
                valing_results['mse'] += batch_mse * batch_size
                batch_ssim = pytorch_ssim.ssim(sr, hr).item()
                valing_results['ssims'] += batch_ssim * batch_size
                valing_results['psnr'] = 10 * log10(1 / (valing_results['mse'] / valing_results['batch_sizes']))
                valing_results['ssim'] = valing_results['ssims'] / valing_results['batch_sizes']
                val_bar.set_description(
                    desc='[converting LR images to SR images] PSNR: %.4f dB SSIM: %.4f' % (
                        valing_results['psnr'], valing_results['ssim']))

                val_images.extend(
                    [do_transform()(val_hr_restore.squeeze(0)), do_transform()(hr.data.cpu().squeeze(0)),
                     do_transform()(sr.data.cpu().squeeze(0))])

            val_images = torch.stack(val_images)
            val_images = torch.chunk(val_images, val_images.size(0) // 15)
            val_save_bar = tqdm(val_images, desc='[saving training results]')
            index = 1
            for image in val_save_bar:
                image = utils.make_grid(image, nrow=3, padding=5)
                utils.save_image(image, out_path + 'epoch_%d_index_%d.png' % (epoch, index), padding=5)
                index += 1

        torch.save(netG.state_dict(), 'epochs/netG_epoch_%d_%d.pth' % (upscale, epoch))
        torch.save(netD.state_dict(), 'epochs/netD_epoch_%d_%d.pth' % (upscale, epoch))

        results['d_loss'].append(trainning_results['d_loss'] / trainning_results['batch_sizes'])
        results['g_loss'].append(trainning_results['g_loss'] / trainning_results['batch_sizes'])
        results['d_score'].append(trainning_results['d_score'] / trainning_results['batch_sizes'])
        results['g_score'].append(trainning_results['g_score'] / trainning_results['batch_sizes'])
        results['psnr'].append(valing_results['psnr'])
        results['ssim'].append(valing_results['ssim'])

        if epoch % 10 == 0 and epoch != 0:
            out_path = 'statistics/'
            data_frame = pd.DataFrame(
                data={'Loss_D': results['d_loss'], 'Loss_G': results['g_loss'], 'Score_D': results['d_score'],
                      'Score_G': results['g_score'], 'PSNR': results['psnr'], 'SSIM': results['ssim']},
                index=range(1, epoch + 1))
            data_frame.to_csv(out_path + 'srf_' + str(upscale) + '_train_results.csv', index_label='Epoch')


"""Module for asset category resource."""

from flask_restplus import Resource
from flask import request, jsonify

from api.models import AssetCategory
from api.models import Asset
from main import api
from api.middlewares.token_required import token_required
from api.utilities.model_serializers.asset_category import (
    AssetCategorySchema, UpdateAssetCategorySchema,
    EagerLoadAssetCategoryAttributesSchema)
from ..utilities.model_serializers.asset import AssetSchema
from api.utilities.model_serializers.attribute import (AttributeSchema,
                                                       UpdateAttributeSchema)
from api.middlewares.base_validator import ValidationError
from api.utilities.validators.validate_id import validate_id
from api.utilities.messages.error_messages import serialization_errors
from ..utilities.validators.validate_json_request import validate_json_request
from ..utilities.paginator import paginate, pagination_helper

@api.route('/asset-categories')
class AssetCategoryResource(Resource):
    """
    Resource class for peforming crud on the asset categories
    """

    @token_required
    @validate_json_request
    def post(self):
        """
        Creates asset categories and the corresponding attributes
        """

        request_data = request.get_json()

        asset_category_schema = AssetCategorySchema()
        asset_category = asset_category_schema.load_object_into_schema(
            request_data)

        attributes_data = request_data.get('attributes')

        if attributes_data:
            attributes_schema = AttributeSchema(
                many=True, exclude=['id', 'deleted'])

            attributes = attributes_schema.load_object_into_schema(
                attributes_data)

            asset_category.attributes = attributes
            attributes = attributes_schema.dump(attributes).data
        else:
            raise ValidationError({
                'message':
                serialization_errors['provide_attributes']
            })

        asset_category = asset_category.save()

        response = jsonify({
            "status": 'success',
            "data": {
                "name": asset_category.name,
                "customAttributes": attributes
            }
        })

        response.status_code = 201
        return response

@api.route('/asset-categories/stats')
class AssetCategoryStats(Resource):
    """
    Resource class for getting asset categories and
    their corresponding asset counts
    """

    @token_required
    def get(self):
        """
        Gets asset categories and the corresponding asset count
        """
        asset_categories = AssetCategory._query(request.args)

        asset_category_schema = AssetCategorySchema(
            many=True, exclude=['deleted'])

        return {
            'status': 'success',
            'data': asset_category_schema.dump(asset_categories).data
        }

@api.route('/asset-categories/<string:id>')
class AssetCategoryListResource(Resource):
    """Asset category list resource"""

    @token_required
    @validate_id
    def get(self, id):
        """
        Get a single asset category
        """

        single_category = AssetCategory.get_or_404(id)

        attributes_schema = AttributeSchema(
            many=True, exclude=['choices', 'id', 'deleted'])

        return {
            'status': 'success',
            'data': {
                'name':
                single_category.name,
                'customAttributes':
                attributes_schema.dump(single_category.attributes).data
            }
        }, 200

    @token_required
    @validate_json_request
    @validate_id
    def patch(self, id):
        """
        Updates asset categories and the corresponding attributes
        """

        request_data = request.get_json()

        asset_category_schema = UpdateAssetCategorySchema()
        asset_category_data = asset_category_schema.load_object_into_schema(
            request_data)

        asset_category_name = asset_category_data.get('name')

        asset_category = AssetCategory.get_or_404(id)

        if asset_category_name:
            asset_category._update(name=asset_category_name)

        attributes_data = request_data.get('attributes')
        attributes_schema = UpdateAttributeSchema(
            many=True, exclude=['deleted'])

        if attributes_data:
            attributes_schema_data = attributes_schema.load_object_into_schema(
                attributes_data)  # noqa
            for attribute in attributes_schema_data:
                attribute_result = asset_category.attributes.filter_by(
                    id=attribute.get('id')).first()
                if attribute_result:
                    attribute_result._update(**attribute)

        attributes = attributes_schema.dump(
            asset_category.attributes.all()).data

        response = jsonify({
            "status": 'success',
            "data": {
                "name": asset_category.name,
                "customAttributes": attributes
            }
        })

        response.status_code = 200
        return response

    @token_required
    @validate_id
    def delete(self, id):
        """
        Soft delete asset categories
        """

        single_category = AssetCategory.get_or_404(id)
        single_category.delete()

        return {
            'status': 'success',
            'message': 'category deleted successfully'
        }

@api.route('/asset-categories')
class AssetCategoryList(Resource):
    """
    Resource class for getting the list of asset categories and
    their corresponding asset counts
    """

    @token_required
    def get(self):
        """
        Gets list of asset categories and the corresponding asset count
        """
        asset_categories_schema = AssetCategorySchema(
            many=True, exclude=['deleted'])

        if request.args:
            include = request.args.get('include')
            if include and include.lower() == 'attributes':
                asset_categories = AssetCategory._query()
                eager_loaded_schema = EagerLoadAssetCategoryAttributesSchema(
                    many=True, exclude=['deleted'])
                data = eager_loaded_schema.dump(asset_categories).data
            else:
                asset_categories = AssetCategory._query(request.args)
                data = asset_categories_schema.dump(asset_categories).data
        else:
            asset_categories = AssetCategory._query()
            data = asset_categories_schema.dump(asset_categories).data

        return {'status': 'success', 'data': data}

@api.route('/asset-categories/<string:id>/assets')
class AssetCategoryAsset(Resource):
    """
    Resource class for getting the list of assets that belong to an asset category  # noqa
    """

    @token_required
    @validate_id
    def get(self, id):
        """
        Gets list of assets that belong to an asset category
        """

        asset_category = AssetCategory.get_or_404(id)
        assets = AssetSchema(
            many=True, exclude=['deleted_at']).dump(
                asset_category.assets.filter_by(deleted=False)).data

        return {
            'status':
            'success',
            'message':
            serialization_errors['asset_category_assets'].format(
                asset_category.name),  # noqa
            'data':
            assets
        }


#  我真诚地保证：
#  我自己独立地完成了整个程序从分析、设计到编码的所有工作。
#  如果在上述过程中，我遇到了什么困难而求教于人，那么，我将在程序实习报告中
#  详细地列举我所遇到的问题，以及别人给我的提示。
#  在此，我感谢 XXX, …, XXX对我的启发和帮助。下面的报告中，我还会具体地提到
#  他们在各个方法对我的帮助。
#  我的程序里中凡是引用到其他程序或文档之处，
#  例如教材、课堂笔记、网上的源代码以及其他参考书上的代码段,
#  我都已经在程序的注释里很清楚地注明了引用的出处。

#  我从未没抄袭过别人的程序，也没有盗用别人的程序，
#  不管是修改式的抄袭还是原封不动的抄袭。
#  我编写这个程序，从来没有想过要去破坏或妨碍其他计算机系统的正常运转。
#  <胡崟昊> 改成自己的名字

from flask import Flask, request, render_template
from search import *
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template('index.html')

@app.route('/search', methods=['GET', 'POST'])
def search():
    # 2011-2018月份
    month_s = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
    # 2019月份
    month_2019 = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11']

    city = request.form['city']
    year = request.form['year']

    if int(year) == 2019:
        months = month_2019
    else:
        months = month_s
    # months = ['01']
    city_pinyin = get_city_pinyin(city)
    print(type(city_pinyin))
    temperature_list = get_date(city_pinyin, year, months)  # 日期，最高温度，最低温度
    # temperature_list = [[3, 2], [2, 1], [5, 5], [9, 6],
    #                     [8, 6], [8, 6], [7, 5], [7, 5],
    #                     [5, 5], [7, 6], [9, 6], [8, 5],
    #                     [8, 4], [6, 5], [7, 3], [4, 0],
    #                     [9, 0], [14, 4], [17, 8], [10, 2],
    #                     [8, 2], [12, 1], [14, 2], [16, 1],
    #                     [11, 3], [9, 0], [13, 3], [12, 6],
    #                     [15 6], [21, 7], [10, 3]]

    # encoding=utf-8
    return render_template('search.html', list=temperature_list, city=city, year1=str(year), year2=int(year))

if __name__ == '__main__':
    app.run(debug=True)


import pandas as pd, numpy as np
from fnmatch import fnmatch

def cols_match(self, pattern):
    '''
    self: dataframe
    pattern: unix filename pattern matching style columns names, separated by comma
    NOTES:
      - limitation: comma cannot form part of a column pattern
      - patern search is case insensitive
    '''

    columns_p = pattern.split(',')
    columns_out = []

    for col in self._obj.columns:
        if len(columns_p) == 0:
            break
        column_p = columns_p[0]
        if fnmatch(col.lower(),column_p.lower()):
            columns_out.append(col)
            columns_p.pop(0)

    return columns_out


'''
Created on Mar 31, 2012

@author: SFUser
'''
from xml.sax.handler import ContentHandler
from xml.sax import parse

class Dispatcher:
    def startElement(self, name, attrs):
        self.dispatch('start', name, attrs)

    def endElement(self, name):
        self.dispatch('end', name)

    def dispatch(self, prefix, name, attrs=None):
        mname = prefix + name.capitalize()
        dname = 'default' + prefix.capitalize()
        method = getattr(self, mname, None)
        if callable(method): args = ()
        else:
            method = getattr(self, dname, None)
            args = name,
        if prefix == 'start':args += attrs
        if callable(method): method(*args)

class TestHandler(Dispatcher, ContentHandler):
    def startElement(self, name, attrs):
        print(name, attrs.keys(), attrs.values())

parse("Nokia.xml", TestHandler())


import binascii
import os

class Utils:
    @staticmethod
    def random_hex_string(length: int):
        buffer = os.urandom(int(length / 2))
        return Utils.bytes_to_hex(buffer)

    @staticmethod
    def truncate_middle(s: str, length: int) -> str:
        if length <= 1:
            raise TypeError()

        first = length / 2
        result = s[:first]
        result += "..."
        result += s[len(s) - (length - first):]
        return result

    @staticmethod
    def split(s: str, c: str):
        return s.split(c)

    @staticmethod
    def to_byte_array(i: int) -> bytes:
        width = i.bit_length()
        width += 8 - ((width % 8) or 8)
        fmt = '%%0%dx' % (width // 4)
        if i == 0:
            return bytes([0])
        return binascii.unhexlify(fmt % i)

    @staticmethod
    def bytes_to_hex(buffer: bytes) -> str:
        return binascii.hexlify(buffer).decode()

    @staticmethod
    def hex_to_bytes(s: str) -> bytes:
        return binascii.unhexlify(s)


import tensorflow as tf
import os
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from preprocessing.time_series.df_to_dataset_synthetic import data_to_dataset_3D, split_input_target
import numpy as np

def split_dataset_into_seq(dataset, start_index, end_index, history_size, step):
  data = []
  start_index = start_index + history_size

  if end_index is None:
    end_index=len(dataset)

  for i in range(start_index, end_index):
    indices = range(i-history_size, i, step)
    data.append(dataset[indices])

  return np.array(data)

def df_to_data_regression(file_path, fname, col_name, index_name, history, step, TRAIN_SPLIT, VAL_SPLIT=0.5, VAL_SPLIT_cv=0.9, cv=False, max_samples=None):
  zip_path = tf.keras.utils.get_file(
      origin=file_path,
      fname=fname,
      extract=True)

  csv_path, _ = os.path.splitext(zip_path)
  df = pd.read_csv(csv_path)
  uni_data_df = df[col_name]
  uni_data_df.index = df[index_name]
  print('length of original continuous dataset: {}'.format(len(uni_data_df)))

  uni_data = uni_data_df.values
  if max_samples is not None:
    #index = list(np.random.randint(0, len(uni_data_df), size=max_samples))
    uni_data = uni_data[:max_samples, :]

  # normalization
  data_mean = uni_data.mean(axis=0)
  data_std = uni_data.std(axis=0)
  uni_data = (uni_data - data_mean) / data_std

  stats = (data_mean, data_std)

  data_in_seq = split_dataset_into_seq(uni_data, 0, None, history, step)

  if not cv:
    # split between validation dataset and test set:
    train_data, val_data = train_test_split(data_in_seq, train_size=TRAIN_SPLIT, shuffle=True)
    val_data, test_data = train_test_split(val_data, train_size=VAL_SPLIT, shuffle=True)

    # reshaping arrays to have a (future shape) of (B,S,1):
    if len(col_name) == 1:
      train_data = np.reshape(train_data, newshape=(train_data.shape[0], train_data.shape[1], 1))
      val_data = np.reshape(val_data, newshape=(val_data.shape[0], val_data.shape[1], 1))
      test_data = np.reshape(test_data, newshape=(test_data.shape[0], test_data.shape[1], 1))

    return (train_data, val_data, test_data), uni_data_df, stats

  else:
    train_val_data, test_data = train_test_split(data_in_seq, train_size=VAL_SPLIT_cv)
    kf = KFold(n_splits=5)
    list_train_data, list_val_data = [], []
    for train_index, val_index in kf.split(train_val_data):
      train_data = train_val_data[train_index, :, :]
      val_data = train_val_data[val_index, :, :]
      list_train_data.append(train_data)
      list_val_data.append(val_data)

    if len(col_name) == 1:
      list_train_data = [np.reshape(d, newshape=(d.shape[0], d.shape[1], 1)) for d in list_train_data]
      list_val_data = [np.reshape(d, newshape=(d.shape[0], d.shape[1], 1)) for d in list_val_data]
      test_data = np.reshape(test_data, newshape=(test_data.shape[0], test_data.shape[1], 1))

    return (list_train_data, list_val_data, test_data), uni_data_df, stats

if __name__ == '__main__':
    file_path = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2016.csv.zip'
    fname = 'jena_climate_2009_2016.csv.zip'
    col_name = ['p (mbar)', 'T (degC)', 'rh (%)', 'rho (g/m**3)']
    index_name = 'Date Time'
    # temperature recorded every 10 minutes.
    TRAIN_SPLIT = 0.7
    history = 6*24*4 + 6*4
    step = 6*4  # sample a temperature every 4 hours.
    cv = False

    (train_data, val_data, test_data), original_df, stats = df_to_data_regression(file_path=file_path,
                                                                                fname=fname,
                                                                                col_name=col_name,
                                                                                index_name=index_name,
                                                                                TRAIN_SPLIT=TRAIN_SPLIT,
                                                                                history=history,
                                                                                step=step,
                                                                                cv=cv,
                                                                                max_samples=20000)

    print(train_data[:5])

    BUFFER_SIZE = 5000
    BATCH_SIZE = 64

    train_dataset, val_dataset, test_dataset = data_to_dataset_3D(train_data=train_data,
                                                                  val_data=val_data,
                                                                  test_data=test_data,
                                                                   split_fn=split_input_target,
                                                                   BUFFER_SIZE=BUFFER_SIZE,
                                                                   BATCH_SIZE=BATCH_SIZE,
                                                                   cv=cv)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import matplotlib.pyplot as plt
import datetime as dt

directory_in_str = str("/home/xollad/Dropbox/laptop_time/log/")
# directory = os.fsencode(directory_in_str)
directory = directory_in_str

times = list()
dates = list()
days =list()
dateTime = list()

# get current month and year number
today = dt.datetime.today()
month_num = today.month
month_name = str( today.strftime("%B") )
year_num = str( today.year )
axix_label_x = month_name + "," + year_num
today_date_num=str(today.day)
print("%s,%s" %(today_date_num,axix_label_x))

# Read contents of files into
for root, dirs, filenames in os.walk(directory):
    for f in filenames:
        dates.append(f)
        fullpath = os.path.join(directory, f)
        with open(fullpath) as f:
            times.append(int(f.read()))

# reverse the list to make today stays as the last element
times.reverse()
dates.reverse()
maxY = max(times) + 50

# extract only day from the date
for date in dates:
    date=str(date)
    dateTime.append(dt.datetime.strptime(date, "%d-%m-%y").date())
    day,mon,year=date.split("-");
    days.append(int(day))

hours=times[-1]/60
mins=times[-1]%60
# print(times)
# print(days)
print("Today used %d hours and %d minutes " %(hours, mins))

#plot
barlist= plt.bar(days, times, align='center', alpha=0.5)
barlist[-1].set_color('g')
plt.xlabel('dates')
plt.ylabel('minutes')
plt.axis([1,31,0,maxY])
plt.title("Today used %d hours and %d minutes " %(hours, mins), fontweight='bold')
# plt.plot(dateTime, times)
plt.show()


#!/usr/bin/python

from compiler.ast import *
import compiler
import sys
import string
import math
from AssemblyAST import *
from PythonASTExtension import *

INT_t = 0		#00
BOOL_t = 1		#01
BIG_t = 3		#11
MASK = 3		#11
counter = 1

class Explicate:

	def __init__(self):
		self.counter = 0

	def getAndIncrement(self):
		counter = self.counter
		self.counter += 1
		return counter

	def explicateMap(self,ast):
		#Creates pyobj's
		if isinstance(ast,Const): return InjectFrom(Const(INT_t),ast)
		elif isinstance(ast,Boolean): return InjectFrom(Const(BOOL_t),Const(int(ast.value)))
		# elif isinstance(ast,List): return InjectFrom(Const(BIG_t),ast)
		# elif isinstance(ast,Dict): return InjectFrom(Const(BIG_t),ast)

		elif isinstance(ast,Add):
			leftName = Name("letAdd"+str(self.getAndIncrement()))
			rightName = Name("letAdd"+str(self.getAndIncrement()))
			#Checks if the left subtree is an int or bool
			leftPredicate = Or([IsTag(Const(INT_t),leftName),IsTag(Const(BOOL_t),leftName)])
			predicate = leftPredicate
			#Checks if the right subtree is an int or bool
			# rightPredicate = Or([IsTag(Const(INT_t),rightName),IsTag(Const(BOOL_t),rightName)])
			#Checks if both subtrees are an int or a bool
			# predicate = And([leftPredicate,rightPredicate])
			#Adds ints and bools
			addIntsAndBools = InjectFrom(Const(INT_t),Add((ProjectTo(Const(INT_t),leftName),ProjectTo(Const(INT_t),rightName))))
			#Adds bigs
			add = CallFunc(Name("add"),[ProjectTo(Const(BIG_t),leftName),ProjectTo(Const(BIG_t),rightName)],None,None)
			addBig = InjectFrom(Const(BIG_t),add)
			#Explicated add tree
			explicatedAdd = IfExp(predicate,addIntsAndBools,addBig)

			return Let(leftName,ast.left,Let(rightName,ast.right,explicatedAdd))
		elif isinstance(ast,Compare):
			if ast.ops[0][0] == "==":
				leftName = Name("letCompare"+str(self.getAndIncrement()))
				rightName = Name("letCompare"+str(self.getAndIncrement()))

				leftIntAndBoolPredicate = Or([IsTag(Const(INT_t),leftName),IsTag(Const(INT_t),rightName)])
				rightIntAndBoolPredicate = Or([IsTag(Const(INT_t),rightName),IsTag(Const(BOOL_t),rightName)])
				intAndBoolPredicate = And([leftIntAndBoolPredicate,rightIntAndBoolPredicate])

				intAndBoolCompare = InjectFrom( Const(BOOL_t), Compare(ProjectTo(Const(BOOL_t),leftName), [('==',ProjectTo(Const(BOOL_t),rightName))]))

				bigPredicate = And([IsTag(Const(BIG_t),leftName),IsTag(Const(INT_t),rightName)])

				bigCompare = InjectFrom(Const(BOOL_t),CallFunc(Name("equal"),[leftName,rightName],None,None))

				bigIf = IfExp(bigPredicate,bigCompare,InjectFrom(Const(BOOL_t),Const(0)))

				intAndBoolIf = IfExp(intAndBoolPredicate,intAndBoolCompare,bigIf)

				letRight = Let(rightName,ast.ops[0][1],intAndBoolIf)
				letLeft = Let(leftName,ast.expr,letRight)
				return letLeft
			elif ast.ops[0][0] == "!=":
				leftName = Name("letCompare"+str(self.getAndIncrement()))
				rightName = Name("letCompare"+str(self.getAndIncrement()))

				leftIntAndBoolPredicate = Or([IsTag(Const(INT_t),leftName),IsTag(Const(INT_t),rightName)])
				rightIntAndBoolPredicate = Or([IsTag(Const(INT_t),rightName),IsTag(Const(BOOL_t),rightName)])
				intAndBoolPredicate = And([leftIntAndBoolPredicate,rightIntAndBoolPredicate])

				intAndBoolCompare = InjectFrom( Const(BOOL_t), Not(Compare(ProjectTo(Const(BOOL_t),leftName), [('==',ProjectTo(Const(BOOL_t),rightName))])))

				bigPredicate = And([IsTag(Const(BIG_t),leftName),IsTag(Const(INT_t),rightName)])

				bigCompare = InjectFrom(Const(BOOL_t),Not(CallFunc(Name("equal"),[leftName,rightName],None,None)))

				bigIf = IfExp(bigPredicate,bigCompare,InjectFrom(Const(BOOL_t),Const(0)))

				intAndBoolIf = IfExp(intAndBoolPredicate,intAndBoolCompare,bigIf)

				letRight = Let(rightName,ast.ops[0][1],intAndBoolIf)
				letLeft = Let(leftName,ast.expr,letRight)
				return letLeft
			else: return ast

			# return intAndBoolIf

		elif isinstance(ast,UnarySub):
			return InjectFrom(Const(INT_t),UnarySub(ProjectTo(Const(INT_t),ast.expr)))
		elif isinstance(ast,CallFunc):
			#Not sure if we have to do anything here
			return ast

		elif isinstance(ast,Function):
			ast.code = Stmt(ast.code.nodes+[NoReturn()])
			newlambda = Lambda(ast.argnames,ast.defaults,ast.flags,ast.code)
			newlambda.uniquename = ast.name
			assign = Assign([AssName(ast.name,'OP_ASSIGN')],newlambda)
			return assign

		elif isinstance(ast,Lambda):
			return Lambda(ast.argnames,ast.defaults,ast.flags,Stmt([Return(ast.code)]))

		elif isinstance(ast,Return): return ast

		else: return ast

	def shortCircuitMap(self,ast):
		if isinstance(ast,Or):
			previous = ast.nodes[len(ast.nodes)-1]
			orNamePrefix ="letOr$"+str(self.getAndIncrement())+"$"
			i = len(ast.nodes) - 1
			currentOrName = None
			for current in reversed(ast.nodes[:len(ast.nodes)-1]):
				currentOrName = Name(orNamePrefix + str(i))
				orexp = Let(currentOrName,current,IfExp(currentOrName,currentOrName,previous))

				previous = orexp
				i -= 1
			return previous

		elif isinstance(ast,And):
			previous = ast.nodes[len(ast.nodes)-1]
			andNamePrefix = "letAnd$"+str(self.getAndIncrement())+"$"
			i = len(ast.nodes) - 1
			for current in reversed(ast.nodes[:len(ast.nodes)-1]):
				currentAndName = Name(andNamePrefix+str(i))
				andexp = Let(currentAndName,current,IfExp(currentAndName,previous,currentAndName))

				previous = andexp
				i -= 1
			return previous
		else: return ast

	@staticmethod
	def explicateCompareMap(ast):
		if isinstance(ast,Compare):
			return IfExp(ast,Const(5),Const(1))
		else: return ast

	@staticmethod
	def removeIsTagMap(ast):
		if isinstance(ast,IsTag):
			return Compare(GetTag(ast.arg),[('==',ast.typ)])
		else: return ast

	@staticmethod
	def removeNot(ast):
		if isinstance(ast,Not):
			return Compare(CallFunc(Name("is_true"),[ast.expr],None,None),[('==',Const(0))])

			notexp = InjectFrom(Const(BOOL_t),Not(CallFunc(Name("is_true"),[ast.expr],None,None)))
			return notexp
		else: return ast


import pytest

def test_nfs_common_is_installed(host):
    assert host.package("nfs-kernel-server").is_installed

@pytest.mark.parametrize("export", [
    "/home/dir1 host1.local(rw,sync,no_root_squash,no_subtree_check)",
    "/home/dir2/dir host2.local(rw,sync,no_root_squash,no_subtree_check)",
    "/home/dir1/test host3.local(rw,sync,no_root_squash,no_subtree_check)"
])
def test_nfs_exports(host, export):
    assert host.file("/etc/exports").contains(export)


"""DIRAC RPC Client utilities."""
import logging
from contextlib import contextmanager
import copy
import rpyc

logger = logging.getLogger(__name__)  # pylint: disable=invalid-name

# This is not strictly necessary as all works without it when deep copying
# However it bypasses the standard deepcopy implementation
# which does type detection for unknown netref type and uses getattr('__deepcopy__')
# which causes an not found exception server side. This tidy's up server side log since we know
# netref<class='__builtin__.dict'> behaves as a dict
netref_dict = rpyc.core.netref.builtin_classes_cache[('dict', '__builtin__')]
copy._deepcopy_dispatch[netref_dict] = copy._deepcopy_dict
# Add the other basic collection types
netref_list = rpyc.core.netref.builtin_classes_cache[('list', '__builtin__')]
copy._deepcopy_dispatch[netref_list] = copy._deepcopy_list
netref_tuple = rpyc.core.netref.builtin_classes_cache[('tuple', '__builtin__')]
copy._deepcopy_dispatch[netref_tuple] = copy._deepcopy_tuple

# Used in Solid to list the DIRAC file catalogue
@contextmanager
def dirac_rpc_client(rpc_endpoint, host="localhost", port=18861):
    """RPC DIRAC RPC client context."""
    conn = rpyc.connect(host, port, config={"allow_public_attrs": True,
                                            "sync_request_timeout": 300})  # 5 mins
    try:
        yield conn.root.RPCClient(rpc_endpoint)
    finally:
        conn.close()

@contextmanager
def dirac_api_client(host="localhost", port=18861):
    """RPC DIRAC API client context."""
    conn = rpyc.connect(host, port, config={"allow_public_attrs": True,
                                            "sync_request_timeout": 300})
    try:
        yield conn.root.Dirac()
    finally:
        conn.close()

@contextmanager
def dirac_api_job_client(host="localhost", port=18861):
    conn = rpyc.connect(host, port, config={"allow_public_attrs": True,
                                            "sync_request_timeout": 300})
    try:
        yield conn.root.Dirac(), conn.root.Job
    finally:
        conn.close()


import streamlit as st
import pandas as pd

from ResultPlots import *

@st.cache(allow_output_mutation=True)
def getUserImages(user):
    print("Caching image data")
    arr = user.openUserNpz("im_plot.npz", "img")
    # res=plot_arrayimg(imgs[value, :, :])
    #Plot each satelital sanpshot of the particiant and cache it
    res = [plot_arrayimg(arr[v, :, :]) for v in range(arr.shape[0])]
    print(arr.shape[0])
    return res

def ResultTab(users):
    st.subheader("Participant List")

    row_array = []
    users_list = []
    #Create a list of particiapnts for internal computation
    for user, data in users.items():
        row_array.append([data.userid, data.name, data.lastname])
        users_list.append(data.userid)

    st.write("Search for user in the following bar by typing user name:")
    option = st.multiselect(
        '', users_list)
    #Show list of all participants
    df = pd.DataFrame(row_array, columns=['User', "Name", "Last Name"])
    if (len(option)) is not 0:
        #Show a table with only the selected participants
        search_df = df[df['User'].isin(option)]
        st.table(search_df)
    else:
        #If not selected participant show all of them
        st.table(df)
    #More than one selected user
    if (len(option)) > 1:
        st.subheader("Comaprison of users")
        # Generate RMS plot concatenating all selected users
        seqgroup = [users[opt].openUserNpz_serie("rms_plot.npz") for opt in option]
        res = plotMultSeq(seqgroup, type="linear")
        st.image(res)
        # Generate Frequency spectral error plot concatenating all selected users
        seqgroup = [users[opt].openUserNpz_serie("freq_plot.npz") for opt in option]
        res = plotMultSeq(seqgroup, type="frequence")
        st.image(res)
    #In the user selction bar there was only one user selected
    if (len(option)) == 1:
        cols = st.beta_columns(2)
        # for usr_ind in range(len(option)):
        cols[0].subheader("Results of %s" % (option[0]))
        #Generate RMS plot
        res1 = plotSingSeq(users[option[0]].openUserNpz_serie("rms_plot.npz"), type="linear")
        #Generate spectral power plot
        res2 = plotSingSeq(users[option[0]].openUserNpz_serie("freq_plot.npz"), type="frequence")
        cols[0].image(res1)
        cols[0].image(res2)
        #Generate images of satelital reconstructed snaptshots
        res = getUserImages(users[option[0]])
        cols[0].write("Move the slider to visualize the reconstructed satelital timelapse")
        #Slider creation
        value = cols[0].slider("Number of frames: "+str(len(res)), 0, len(res)-1, 0, 1)
        # res3 = plot_arrayimg(res[value])
        #Show the snapshot
        cols[0].image(res[value])


from controllers import user_controller
from controllers import school_controller
from controllers import mail_controller

from models import mentor_model
from models import user_model

from views import user_view
from views import manager_view
from views import ui

import utilities
import os

def start_controller(school, manager):
    """
    Switches between options

    Args:
        school (obj): school object - aggregate all users and assignments
        manager (obj): Manager object

    Returns:
        None
    """

    choice = ''
    while choice != '0':
        os.system('clear')
        user_view.display_user_info(manager)
        manager_view.print_manager_menu()
        choice = manager_view.get_choice()

        if choice == '1':
            manager_view.list_users(school.mentors_list)

        elif choice == '2':
            view_mentor_details(school)

        elif choice == '3':
            add_mentor(school)

        elif choice == '4':
            remove_mentor(school)

        elif choice == '5':
            edit_mentor(school)

        elif choice == '6':
            manager_view.list_all_students(school.students_list)

        elif choice == '7':
            view_student_details(school)

        elif choice == '8':
            mail_controller.start_controller(school, manager)

        input('Press enter')

def get_mentor(school):
    """
    Args:
        school (obj): school object - aggregate all users and assignments

    Returns:
        Mentor object
    """

    return school_controller.get_user(school, school.mentors_list)

def get_student(school):
    """
    Args:
        school (obj): school object - aggregate all users and assignments

    Returns:
        Student object
    """

    return school_controller.get_user(school, school.students_list)

def view_mentor_details(school):
    """
    Ask for mentor id, then print mentor details
    Args:
        school (obj): school object - aggregate all users and assignments

    Returns:
        None
    """

    chosen_mentor = get_mentor(school)
    if chosen_mentor:
        manager_view.print_mentor(chosen_mentor)

def add_mentor(school):
    """
    Adds mentor

    Args:
        school (obj): school object - aggregate all users and assignments

    Returns:
        None
    """

    user_controller.add_user(school, 'mentor')

def remove_mentor(school):
    """
    Ask for mentor id then, deletes mentor from mentors_list in school object

    Args:
        school (obj): school object - aggregate all users and assignments

    Returns:
        None
    """

    mentor_to_remove = get_mentor(school)
    if mentor_to_remove in school.mentors_list:
        school.mentors_list.remove(mentor_to_remove)

def view_student_details(school):
    """
    Ask for student id, then print student details

    Args:
        school (obj): school object - aggregate all users and assignments

    Returns:
        None
    """

    chosen_student = get_student(school)
    if chosen_student:
        manager_view.print_student(chosen_student)

def edit_mentor(school):
    """
    Changes mentor data

    Args:
        school (obj): School object - aggregate all users and assignments

    Returns:
        None
    """

    mentor_to_change = get_mentor(school)
    user_controller.start_controller(mentor_to_change)


# -*- coding: utf-8

def generator(): # генератор
    i = 0
    while True:
        i += 1
        yield i
a = generator()

def autocompl(key, value):
    result = []
    count = 0
    for sub_str in value:
        if sub_str.lower().startswith(key.lower()):
            sub_str = filter(lambda x: x.isalpha(), sub_str)
            result.append(sub_str)
            count += 1
        if count == 5:
            break
    return result

print (autocompl('q', ['q65`7642@@@@', 'q$%$qw%$%$', 'qww ww','qwe&*rty', 'Qw5555', 'qw7777', 'qw0000', 'q7e000', 'qwoiuoiu', 'ethdff']))

 #   list = filter(lambda x: x.startswith(string), orig_dict)
 #   print orig_dict
 #   return list

# numbers = ['qwerty','qw5555','qw7777','qw0000','7e000','qwoiuoiu']
# #['qwerty','qw5555','qw7777','qw0000','7e000','qwoiuoiu']
# numbers_under_4 = filter(lambda x: x.startswith('qw'), numbers)

# print numbers_under_4


import os
import csv

budget1_csv = os.path.join("budget_data_1.csv")

revenue_1 = []
date_1 = []
revenue_change1 = []

with open(budget1_csv, 'r') as csvfile:
    csv_reader1 = csv.reader(csvfile, delimiter=",")
    next(csv_reader1, None)
    for row in csv_reader1:
        revenue_1.append(float(row[1]))
        date_1.append(row[0])
        total_months1 = len(date_1)
        total_revenue1 = sum(revenue_1)
        avg_rev_change1 = round(total_revenue1/total_months1, 0)

    for i in range(1, len(revenue_1)):
        revenue_change1.append(revenue_1[i] - revenue_1[i-1])
        inc_rev_change1 = max(revenue_change1)
        dec_rev_change1 = min(revenue_change1)
        inc_date1 = str(date_1[revenue_change1.index(max(revenue_change1))])
        dec_date1 = str(date_1[revenue_change1.index(min(revenue_change1))])

budget2_csv = os.path.join("budget_data_2.csv")

revenue_2 = []
date_2 = []
revenue_change2 = []
with open(budget2_csv, 'r') as csvfile:
    csv_reader2 = csv.reader(csvfile, delimiter=",")
    next(csv_reader2, None)
    for row in csv_reader2:
        revenue_2.append(float(row[1]))
        date_2.append(row[0])
        total_months2 = len(date_2)
        total_revenue2 = sum(revenue_2)
        avg_rev_change2 = round(total_revenue2/total_months2, 0)

    for i in range(1, len(revenue_2)):
        revenue_change2.append(revenue_2[i] - revenue_2[i-1])
        inc_rev_change2 = max(revenue_change2)
        dec_rev_change2 = min(revenue_change2)
        inc_date2 = str(date_2[revenue_change2.index(max(revenue_change2))])
        dec_date2 = str(date_2[revenue_change2.index(min(revenue_change2))])

    total_months = total_months1 + total_months2
    total_revenue = (total_revenue1) + (total_revenue2)
    avg_rev_change = total_revenue/total_months

    if inc_rev_change1 >= inc_rev_change2:
        inc_rev_change = inc_rev_change1
        inc_date = inc_date1
    else:
        inc_rev_change = inc_rev_change2
        inc_date = inc_date2
        Financial_Analysis.append(inc_date + inc_rev_change)
    if dec_rev_change1 <= dec_rev_change2:
        dec_rev_change = dec_rev_change1
        dec_date = dec_date1
    else:
        dec_rev_change = dec_rev_change2
        dec_date = dec_date1
    print("Financial Analysis")
    print("----------------------------")
    print("Total Months: " + str(total_months))
    print("Total Revenue: $" + str(int(total_revenue)))
    print("Average Change in Revenue: $" + str(int(avg_rev_change)))
    print("Greatest Increase in Revenue: " + inc_date + " ($" + str(int(inc_rev_change)) + ")")
    print("Greatest Decrease in Revenue: " + dec_date + " ($" + str(int(dec_rev_change)) + ")")

Financial_Analysis = os.path.join("FinancialAnalysis.csv")
with open(Financial_Analysis, 'w', newline="") as datafile:
    csvWriter = csv.writer(datafile)
    csvWriter.writerow(["Financial Analysis"])
    csvWriter.writerow(["----------------------------"])
    csvWriter.writerow(["Total Months: " + str(total_months)])
    csvWriter.writerow(["Total Revenue: $" + str(int(total_revenue))])
    csvWriter.writerow(["Average Revenue Change: $" + str(int(avg_rev_change))])
    csvWriter.writerow(["Greatest Increase in Revenue: " + str(inc_date) + " " + "($" + str(int(inc_rev_change)) + ")"])
    csvWriter.writerow(["Greatest Decrease in Revenue: " + str(dec_date) + " " + "($" + str(int(dec_rev_change)) + ")"])


from tests.common.base import *
from tests.facebook_user_actions.locators.user_actions_locators import *

class UserActionsBase(BaseClass):
    def __init__(self, driver):
        self.driver = driver
        super(UserActionsBase, self).__init__(driver)

    def read_shared_post(self,with_attachment=False, video=False,with_emoji = False):
        posted_data = {}
        smiley_to_select = ""
        posted_data['data'] = str(self.get_text("(//*[contains(@class,'userContent')]//p)[1]"))
        if with_attachment is True:
            posted_data['image'] = self.is_displayed(assert_image_loc)
            if with_emoji:
                if posted_data['data'].__contains__(smiley_to_select):
                    posted_data['emoji'] = True
            if video is True:
                posted_data['video'] = self.is_displayed(assert_video_loc)
        return posted_data

    def read_message(self,sent_message):
        posted_message = {}
        self.click(messenger_icon_loc)
        self.click(select_message_content_loc)
        posted_message["message"] = self.is_displayed(read_message_txt_loc.format(sent_message))
        return posted_message["message"]