import os
import io

import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import QtMultimedia
from copy import deepcopy
import soundfile as sf

#import numpy as np
def _translate(context, text, disambig):
    return QtCore.QCoreApplication.translate(context, text, disambig)

class playQtAudio():
    def __init__(self, parHandle=None, settings='default'):
        """!
        Initializing the CICoachLab player playQtAudio. This function provides the function to play back audio signals.
        with The signal format is as follows:
        signa['audio']
        signal['fs']
        The recomended field:
        signal['name']

        The recomended field signal['name'] is used to handle the check if the signal has been loaded before and the
        playing an pausing of the signal is possible, or if the signal has to be loaded to start the playing.

        Additionally to the obligatory functions ['run'] , ['settingsLoading'], ['settingsDefault'] and other the
        following functions are provided.

        The function provided with
        self.parHandle.curPlayer['functions']['run']
        takes the argument signal, loads it into the player, and starts the playing.

        The special functions provided by playQtAudio are found in self.parHandle.curPlayer['functions'] and are:

        ['addControlbar']:
        # this function returns a layout with control buttons and a slider which allow to play back different signals.
        # The control bar contains a play, pause and stop button, a slider to see and control the playback position of
        # the played audio. The label at the start and end of the slider indicate the start (0) and end (duration)
        # of the signal.
        # If the signal is played back and play is pressed again, the signal is stopped and started again at the
        # start of the signal.
        # Different control bars can be generated to play back and control different signals.
        # The same qt player is used to play back the different signals. When the control bar is changed a different
        # signal will be loaded. The assignment is handled by the argument controlbarName which defaults to 'main' if
        # no name is provided and a single control bar is used.
        # With layoutMode a 'stacked' and 'inline' version is returned. 'stacked' is used as default if enough place
        # is provided. A less place taking version is returned with the 'inline' version.
        ['getControlbarCaller']
        This function returns the label of the currently controlled signal.
        ['setControlbarLabel']:
        This function takes the input argument, label, to set the controlled signal.
        ['durationChanged']:
        If the widget seekSlider and seekSliderLabelEnd exist the label and and the range of the slider will be set
        to the duration input argument, defined in mili seconds.
        ['setPosition']
        The media pointer is set to position.
        ['playHandler']
        The loaded signal will be played.
        ['pauseHandler']
        The audio signal will be paused.
        ['stopHandler']
        The audio signal will be stopped.
        ['loadAudioSignal']
        The audio signal will be set.

        If a preprocessor is defined the preprocessor will be called and the audio signal processed.
        The default settings will be set or the provided settings will be loaded.

        If the waitFlag is set in the settings of the player, any input widget will block any signal as long as the
        audio is played.
        """

        if parHandle == None:
            print('cannot initilize without framework.')
        self.parHandle = parHandle

        self.parHandle.dPrint('playQtAudio: __init__()', 2)

        self.setDefaultSettings()
        self.parHandle.addingPath('curPlayer')
        if settings != 'default' and settings != '':
            # the loaded settings just may overwrite parts of the defaultSettings....
            self.loadSettings(settings)

        self.sysname     = self.parHandle.frameWork['settings']['system']['sysname']

        self.player = QtMultimedia.QMediaPlayer()
        self.player.mediaStatusChanged.connect(self.mediaStatusChanged)
        self.player.bufferStatusChanged.connect(self.bufferStatusChanged)
        self.player.stateChanged.connect(self.stateChanged)

        self.player.positionChanged.connect(self.positionChanged)
        self.player.durationChanged.connect(self.durationChanged)

        # self.userAction defines the state of the audio player as follows:
        # initialized: -1
        # stopped: 0
        # playing: 1
        # paused: 2
        self.userAction = -1

        self.buf = None

        self.parHandle.addingPath('curPlayer')

        self.parHandle.curPlayer['functions']['constructor']      = self.__init__
        self.parHandle.curPlayer['functions']['destructor']       = self.__del__
        self.parHandle.curPlayer['functions']['run']              = self.run
        self.parHandle.curPlayer['functions']['applyPreprocessor']=self.applyPreprocessor
        self.parHandle.curPlayer['functions']['settingsLoading']  = self.loadSettings
        self.parHandle.curPlayer['functions']['settingsDefault']  = self.setDefaultSettings
        self.parHandle.curPlayer['functions']['settingsGui']      = None

        self.parHandle.curPlayer['functions']['getControlbarCaller'] = self.getControlbarCaller
        self.parHandle.curPlayer['functions']['setControlbarLabel'] = self.setControlbarLabel
        # this function returns a layout with control buttons and a slider.
        self.parHandle.curPlayer['functions']['addControlbar'] = self.addControlbar
        self.parHandle.curPlayer['functions']['durationChanged'] = self.durationChanged
        self.parHandle.curPlayer['functions']['setPosition'] = self.setPosition
        self.parHandle.curPlayer['functions']['playHandler'] = self.playHandler
        self.parHandle.curPlayer['functions']['pauseHandler'] = self.pauseHandler
        self.parHandle.curPlayer['functions']['stopHandler'] = self.stopHandler
        self.parHandle.curPlayer['functions']['loadAudioSignal'] = self.loadAudioSignal
        self.parHandle.curPlayer['functions']['stateChanged'] = self.stateChanged

        # get reaction time delay from iniFile configuration and save it under
        self.parHandle.setDefaultCalibration('curPlayer', 'level')
        self.parHandle.readIniFile(mode='curPlayerSettings', module='curPlayer')

        self.parHandle.curPlayer['handle'] = self
        # The controlbar label is set if a single controlbar is added, or if a button of a controlbar is pressed which
        # defines the active controlbar. If self.controlbarLabel is empty no controlbar actions, like updating the
        # slider or labeling of the duration, will be allowed or run.
        self.controlbarLabel = ''
        self.playerWidgetConverter = dict()
        self.changedMediaFlag = True
        self.oldMediaName = ''

        self.oldInfoMsg = ''

        self.oldSettings = None

        self.parHandle.dPrint('playQtAudio: Leaving __init__()', 2)

    def __del__(self):
        """!
        The destructor of the class will delete the menu of the player. The parameters of curPlayer  will be
        reset. The player path will be reset
        """

        self.parHandle.dPrint('playQtAudio: __del__()', 2)

        self.parHandle.clearSettingsInMenu('curPlayer')
        self.parHandle.closePath('curPlayer')

        self.parHandle.initializeToDefaults(mode='curPlayer')

        self.parHandle.dPrint('playQtAudio: Leaving __del__()', 2)

    def applyPreprocessor(self, signalIn):
        """!
        This function calculates the preprocessed signal. The calling of this functions allows
        buffering of time intensively preprocessed signals.
        """

        self.parHandle.dPrint('playQtAudio: applyPreprocessor()', 2)

        # set name if name is not defined which allows prebuffering of curPreprocessor
        if not ('name' in signalIn):
            # if no name is defined by the generaotr, as in the genWavreader, which takes the filename, as name
            # the signal name should be unique enough by the settings of the generator.
            signalIn['name'] = str(self.parHandle.curGenerator['settings'])

        if not (self.parHandle.curPreprocessor['functions']['run'] == None) and \
                ('deactivate' in self.parHandle.curPreprocessor['settings'] and
                 not (self.parHandle.curPreprocessor['settings']['deactivate'])):

            try:
                self.oldInfoMsg = self.parHandle.statusBar().currentMessage()
                self.parHandle.dPrint('playQtAudio: Calling preprocessor', 4)
                self.parHandle.showInformation(_translate("playQtAudio", 'audio signal is processed ...', None)
                                               + signalIn['name'])
                signalOut = self.parHandle.curPreprocessor['functions']['run'](signalIn)
                self.parHandle.showInformation(self.oldInfoMsg)
            except:
                self.parHandle.dPrint('playsignal: could not call preprocessor', 1)
        else:
            signalOut = signalIn

        self.parHandle.dPrint('playQtAudio: Leaving applyPreprocessor()', 2)
        return signalOut

    def run(self, signal, enforceReloadedData=False):
        """!
        The audio signal is played back after the optional preprocessing. If curPlayer['settings']['visualPreparation']
        is set to true a visual feedback is provided before the presentation to call the subjects attention.
        """

        self.parHandle.dPrint('playQtAudio: run()', 2)

        self.oldInfoMsg = self.parHandle.statusBar().currentMessage()

        # if the audio player settings have been changed the data will be reloaded.
        if self.oldSettings != self.parHandle.curPlayer['settings']:
            enforceReloadedData = True

        # This distinction allows the handling of pause and rejoin playing at paused position
        if not(enforceReloadedData) and self.oldMediaName and 'name' in signal and signal['name'] == self.oldMediaName:
            # leave loaded media/signal unchanged
            msg = "The old signal is called again. The media won't be reloaded again."
            self.parHandle.dPrint(msg, 2)
            self.playHandler()
        else:
            # reload and/or reprocess media/signal

            self.oldMediaName = signal['name']
            #
            signal = self.applyPreprocessor(signal)

            stdPalette = self.parHandle.ui.exerWidget.palette()
            if self.parHandle.curPlayer['settings']['visualPreparation'] and\
                    'visualPreparationTime' in self.parHandle.curExercise['settings'].keys():
                newPalette = QtGui.QPalette(QtGui.QColor(145, 145 , 255))
                self.parHandle.changePalette(self.parHandle.ui.exerWidget, newPalette)
                timerPC = QtCore.QTimer(self.parHandle, timerType=QtCore.Qt.PreciseTimer)
                timerPC.setSingleShot(True)
                timerPC.setInterval(self.parHandle.curExercise['settings']['visualPreparationTime'] * 1000)
                timerPC.timeout.connect(lambda: self.parHandle.changePalette(self.parHandle.ui.exerWidget, stdPalette))
                timerPC.start()

            #if not(self.parHandle.curPlayer['settings']['fs'] == signal['fs']) and not(self.parHandle.curPlayer['settings']['fs'] == 0):
            #    print('Implement resampling if requirerd')

            if self.parHandle.frameWork['settings']['muteSignal']:
                scalFac = 0
            else:
                #scalFac = 1
                dBsystem = self.parHandle.frameWork['calibration']['level']['level']
                #dBplayerCal = 10**(self.parHandle.curExercise['calibration']['level']['level']/20)
                dBplayer = self.parHandle.curPlayer['settings']['level']
                scalFac = 10**(((dBsystem - 144)  + dBplayer) / 20)

                self.oldSettings = deepcopy(self.parHandle.curPlayer['settings'])

            if self.parHandle.curPlayer['settings']['visualPreparation']:
                timerPA = QtCore.QTimer(self.parHandle, timerType=QtCore.Qt.PreciseTimer)
                timerPA.setSingleShot(True)
                if 'visualPreparationTime' in self.parHandle.curExercise['settings'].keys():
                    timerPA.setInterval(self.parHandle.curExercise['settings']['visualPreparationTime'] * 1000)
                else:
                    timerPA.setInterval(0)
                timerPA.timeout.connect(lambda: self.parHandle.changePalette(self.parHandle.ui.exerWidget, stdPalette))

                timerPA.start()
            try:
                signalScaled = deepcopy(signal)
                signalScaled['audio'] = signalScaled['audio']*scalFac

                self.loadAudioSignal(signalScaled)

                #self.pauseHandler()
                if 'durationChanged' in dir(self.parHandle.curExercise['handle']):
                    self.durationChanged(self.player.duration())

                self.playHandler()
                #QtCore.QTimer.singleShot(
                #    self.parHandle.curPlayer['settings']['visualPreparationTime'] * 1000, self.playHandler)
            except:
                self.parHandle.dPrint(_translate("playQtAudio", 'playQtAudio: The player could not be run.',None),
                                      0, guiMode=True)

        self.parHandle.measureReactionTime(self.parHandle, mode='start')

        # test systemReactionTime by calling user input function directly
        if self.parHandle.frameWork['systemCheck']:
            self.parHandle.curExercise['handle'].runButton()

        self.parHandle.dPrint('playQtAudio: Leaving run()', 2)

    def loadAudioSignal(self, signal):
        """!
        The audio signal with the signal format
        signal['audio']
        signal['fs']

        This function converts the numpy array to bytes which can be loaded by the player.
        """

        self.parHandle.dPrint('playQtAudio: loadAudioSignal()', 2)

        f = io.BytesIO()
        sf.write(f, signal['audio'], signal['fs'], format='wav', subtype='PCM_24')

        # copy the bytes to a QBuffer
        self.buf = QtCore.QBuffer()
        self.buf.setData(f.getvalue())
        self.buf.open(QtCore.QIODevice.ReadOnly)

        self.player.setMedia(QtMultimedia.QMediaContent(), self.buf)

        self.parHandle.dPrint('playQtAudio: loadAudioSignal()', 2)

    def positionChanged(self, position):
        """!
        If the position is changed the position of at the slider is changed if a control bar is defined and
        if the slider widgets is defined.
        """

        #self.seekSlider.setValue(position)
        # check the exercise provides a controlbar with slider

        if self.controlbarLabel:

            if self.player.mediaStatus() == QtMultimedia.QMediaPlayer.BufferedMedia:
                # introduced to prevent
                """
                if position > 0:
                    status = 'playing'
                else:
                    # why does this happen?!?
                    status = 'buffered'
                """
                status = 'playing'
            else:
                status = 'playing'

            seekSlider = self.parHandle.curExercise['handle'].controlbarRefs[self.controlbarLabel]['seekSlider']
            seekSlider.setValue(position)
            duration = self.player.duration()

            if duration > 0:
                self.providePlayerFeedBack(status=status, position=position/duration)

    def durationChanged(self, duration):
        """!
        If the widget seekSlider and seekSliderLabelEnd exist the label and and the range of the slider will be set.

        duration: length of signal in mili seconds
        """

        self.parHandle.dPrint('playQtAudio: durationChanged()', 2)

        if self.controlbarLabel:
            seekSlider = self.parHandle.curExercise['handle'].controlbarRefs[self.controlbarLabel]['seekSlider']
            seekSliderLabelEnd = \
                self.parHandle.curExercise['handle'].controlbarRefs[self.controlbarLabel]['seekSliderLabelEnd']
            if seekSlider:
                seekSlider.setRange(0, duration)
            if seekSliderLabelEnd:
                msg = '%d:%02d' % (round(duration / 60000), round((duration / 1000) % 60))
                seekSliderLabelEnd.setText(msg)

        self.parHandle.dPrint('playQtAudio: Leaving durationChanged()', 2)

    def pauseHandler(self):
        """!
        The audio signal will be paused and in case of waitFlag == True the disabled gui user input elements will
        enabled again.
        """

        self.parHandle.dPrint('playQtAudio: pauseHandler()', 2)

        self.userAction = 2
        self.player.pause()
        if self.parHandle.curPlayer['settings']['waitFlag']:
            self.parHandle.enableExerciseGui()

        #self.oldInfoMsg = ''
        feedback = _translate("playQtAudio", 'Audio paused ... ', None)
        self.parHandle.showInformation(feedback)
        pos = self.player.position()
        duration = self.player.duration()

        if duration:
            position = pos / duration * 100
        else:
            position = 0
        self.providePlayerFeedBack(status='paused', position=position)

        self.parHandle.dPrint('playQtAudio: Leaving pauseHandler()', 2)

    def playHandler(self):
        """!
        The audio signal will be played back. User input gui elements will be disabled, if the waitFlag was set.
        """

        self.parHandle.dPrint('playQtAudio: playHandler()', 2)

        if self.parHandle.frameWork['settings']['fixMasterVolume']:
            #currentVol = self.parHandle.fixedMasterVol
            currentVol = self.parHandle.getMasterVolume()
            if self.parHandle.fixedMasterVol == currentVol:
                msg = 'Volume control passed.'
                self.parHandle.dPrint(msg, 4)
            else:
                msg = _translate("playQtAudio",
                                     f"Volume control failed. \n\nThe volume found was '{currentVol:02d}%'"
                                     f" and will be set to '{self.parHandle.fixedMasterVol:02d}%'.\n\n"
                                     "Please don't change the volume settings during the use of CICoach Lab.", None)
                self.parHandle.dPrint(msg, 0, guiMode=True)
                self.parHandle.setMasterVolume(self.parHandle.fixedMasterVol)
        senderWidget = self.parHandle.sender()
        #getControlbarCaller = self.getControlbarCaller(senderWidget)
        #self.parHandle.sender().parent().layout().count()

        self.userAction = 1
        if 'durationChanged' in dir(self.parHandle.curExercise['handle']):
            self.parHandle.curExercise['handle'].durationChanged(self.player.duration())
        # self.statusBar().showMessage('Playing at Volume %d' % self.player.volume())
        if self.player.state() == QtMultimedia.QMediaPlayer.StoppedState:
            if self.player.mediaStatus() == QtMultimedia.QMediaPlayer.LoadedMedia:
                self.player.play()
            elif self.player.mediaStatus() == QtMultimedia.QMediaPlayer.BufferedMedia:
                self.player.play()
            elif self.player.mediaStatus() == QtMultimedia.QMediaPlayer.EndOfMedia:
                # self.positionChanged(0)
                # self.setPosition(0)
                self.player.play()
            elif self.player.mediaStatus() == QtMultimedia.QMediaPlayer.LoadingMedia:
                # if buffer is used this state persists
                self.player.play()
        elif self.player.state() == QtMultimedia.QMediaPlayer.PlayingState:
            self.player.stop()
            self.player.play()
        elif self.player.state() == QtMultimedia.QMediaPlayer.PausedState:
            self.player.play()
        if self.parHandle.curPlayer['settings']['waitFlag']:
            # just disabling exercise gui elements to stop user interaction,the rest of the code will continue to run.
            self.parHandle.disableExerciseGui()
        self.providePlayerFeedBack(status='playing')

        #self.oldInfoMsg = ''
        feedback = _translate("playQtAudio", 'Audio playing ... ', None)
        self.parHandle.showInformation(feedback)

        self.parHandle.dPrint('playQtAudio: Leaving playHandler()', 2)

    def stopHandler(self):
        """!
        The audio is stopped and the disabled gui input elements will be enabled again, if they were disabled in
        case of waitFlag == True.
        """

        self.parHandle.dPrint('playQtAudio: stopHandler()', 2)

        self.userAction = 0
        if self.player.state() == QtMultimedia.QMediaPlayer.PlayingState:
            self.player.stop()
        elif self.player.state() == QtMultimedia.QMediaPlayer.PausedState:
            self.player.stop()
        elif self.player.state() == QtMultimedia.QMediaPlayer.StoppedState:
            pass
        if self.parHandle.curPlayer['settings']['waitFlag']:
            self.parHandle.enableExerciseGui()
        self.parHandle.showInformation(self.oldInfoMsg)
        self.oldInfoMsg = ''
        self.providePlayerFeedBack(status='stopped')

        self.parHandle.dPrint('playQtAudio: Leaving stopHandler()', 2)

    def stateChanged(self):
        """!
        """

        self.parHandle.dPrint('playQtAudio: stateChanged()', 2)

        if self.player.state() == QtMultimedia.QMediaPlayer.StoppedState:
            self.player.stop()
            self.parHandle.showInformation(self.oldInfoMsg)
            if self.controlbarLabel:
                if self.player.duration():
                    pos = self.player.position()/self.player.duration()*100
                else:
                    pos = 0
                self.providePlayerFeedBack(status='stopped', position=pos)

        self.parHandle.dPrint('playQtAudio: Leaving stateChanged()', 2)

    def setControlbarLabel(self, newLabel):
        """!
        This function takes the input argument, label, to set the controlled signal.
        """

        self.parHandle.dPrint('playQtAudio: setControlbarLabel()', 2)

        self.controlbarLabel = newLabel

        self.parHandle.dPrint('playQtAudio: Leaving setControlbarLabel()', 2)

    def providePlayerFeedBack(self, status='', position=np.nan):
        """!
        The function turns the status of the player and position, if possible, of the played signal to the feedback
        function of the calling exercise if the exercise has defined a feedback function.
        This function is called by the functions self.mediaStatusChanged(), self.bufferStatusChanged() and
        self.stateChanged()
        If no status can be provided an empty string is provided.
        If no position can be provided np.nan is provided.

        The status can be:
            'playing', 'waiting', 'paused', 'stopped', 'loading' or ''
        The position is returned in percent of the signal length.
        """

        self.parHandle.dPrint('playQtAudio: providePlayerFeedBack()', 4)

        if self.parHandle.curExercise['functions']['getPlayerStatus']:
            self.parHandle.curExercise['functions']['getPlayerStatus'](status, position)

        self.parHandle.dPrint('playQtAudio: Leaving providePlayerFeedBack()', 4)

    def mediaStatusChanged(self):
        """!
        If the data has been loaded and the media should be played as indicated by self.userAction the
        duration of the media will be read and set in the controlbar, if it was defined. The audio is played by
        calling self.playHandler()
        If the media has been ended the disabled input gui elements will be enabled again, if waitFlag == True.

        The function is called when media has been loaded, if media is started to play, when the media ends.
        """

        self.parHandle.dPrint('playQtAudio: mediaStatusChanged()', 2)

        if self.player.mediaStatus() == QtMultimedia.QMediaPlayer.BufferedMedia and self.userAction == 1:
            durationT = self.player.duration()

            if 'durationChanged' in dir(self.parHandle.curExercise['handle']):
                self.player.durationChanged.connect(self.parHandle.curExercise['handle'].durationChanged)
            # checks if the exercise has implemented some interaction toolbars
            if hasattr(self.parHandle.curExercise['handle'], 'controlbars') and self.parHandle.curExercise['handle'].controlbars:
                guiHandlingFailed = False
                # defining the calling controlbar, if several controlbars might exist in exercise
                if self.controlbarLabel:
                    controlbarLabel = self.controlbarLabel
                else:
                    if 'main' in self.parHandle.curExercise['handle'].controlbarRefs:
                        controlbarLabel = 'main'
                    elif len(self.parHandle.curExercise['handle'].controlbars) == 1:
                            [[controlbarLabel, temp]] = self.parHandle.curExercise['handle'].controlbarRefs.items()
                    else:
                        guiHandlingFailed = True
                if guiHandlingFailed:
                    self.controlbarLabel = ''
                    self.parHandle.dPrint('Tried to update controlbar and failed.', 0)
                else:
                    self.controlbarLabel = controlbarLabel
                    #seekSlider = self.parHandle.curExercise['handle'].controlbars[controlbarLabel].children()[0].itemAt(1).widget()

                    self.durationChanged(durationT)
            #self.playHandler()
            self.providePlayerFeedBack(status='waiting', position=0)
            status = QtMultimedia.QMediaPlayer.BufferedMedia
        elif self.player.mediaStatus() == QtMultimedia.QMediaPlayer.EndOfMedia:
            # enabling exercise gui elements again after disabling after the playing of the signal
            if self.parHandle.curPlayer['settings']['waitFlag']:
                self.parHandle.enableExerciseGui()
            #self.oldInfoMsg = ''
            feedback = _translate("playQtAudio", 'End of audio.', None)
            self.parHandle.showInformation(feedback)

            self.providePlayerFeedBack(status='stopped', position=100)
            status = QtMultimedia.QMediaPlayer.EndOfMedia
        else:
            status =  -1
        if 'getPlayerStatus' in self.parHandle.curExercise['functions'] and \
                self.parHandle.curExercise['functions']['getPlayerStatus']:
            self.parHandle.curExercise['functions']['getPlayerStatus'](status)

        self.parHandle.dPrint('playQtAudio: Leaving mediaStatusChanged()', 2)
        return status

    def bufferStatusChanged(self):
        """!
        If the buffer status changes the same code is run as in self.mediaStatusChanged()
        """

        self.parHandle.dPrint('playQtAudio: bufferStatusChanged()', 2)

        if self.player.mediaStatus() == QtMultimedia.QMediaPlayer.LoadedMedia and self.userAction == 1:
            durationT = self.player.duration()
            if 'durationChanged' in dir(self.parHandle.curExercise['handle']):
                self.player.durationChanged.connect(self.parHandle.curExercise['handle'].durationChanged)

            if self.parHandle.curExercise['handle'].controlbars:
                guiHandlingFailed = False
                # defining the calling controlbar, if several controlbars might exist in exercise
                if self.controlbarLabel:
                    controlbarLabel = self.controlbarLabel
                else:
                    if 'main' in self.parHandle.curExercise['handle']['playBtn']:
                        controlbarLabel = 'main'
                    elif len(self.parHandle.curExercise['handle'].controlbars) == 1:
                        [[controlbarLabel, temp]] = self.parHandle.curExercise['handle'].controlbarRefs.items()
                    else:
                        guiHandlingFailed = True
                if guiHandlingFailed:
                    self.controlbarLabel = ''
                    self.parHandle.dPrint('Tried to update controlbar and failed.', 0)
                else:
                    self.controlbarLabel = controlbarLabel
                    seekSlider = self.parHandle.curExercise['handle'].controlbars[controlbarLabel].children()[0].itemAt(1).widget()
                    seekSlider.setRange(0, durationT)
                    seekSlider.setText('%d:%02d' % (int(durationT / 60000), int((durationT / 1000) % 60)))
            self.playHandler()
            self.providePlayerFeedBack(status='playing') #TODO: Check and compare to mediaStatusChanged
            return QtMultimedia.QMediaPlayer.LoadedMedia
        elif self.player.mediaStatus() == QtMultimedia.QMediaPlayer.EndOfMedia:
            # enabling exercise gui elements again after disabling after the playing of the signal
            if self.parHandle.curPlayer['settings']['waitFlag']:
                self.parHandle.enableExerciseGui()

            #self.oldInfoMsg = ''
            feedback = _translate("playQtAudio", 'End of audio.', None)
            self.parHandle.showInformation(feedback)

            self.providePlayerFeedBack(status='stopped', position=100)
            return QtMultimedia.QMediaPlayer.EndOfMedia
        else:
            return -1

        self.parHandle.dPrint('playQtAudio: Leaving bufferStatusChanged()', 2)

    def addControlbar(self, controlbarName='main', layoutMode='stacked'):
        """!
        This function produces a controllbar widget to control the player. The widget controlbar  and
        is returned alongside controlbarRefs which enables the applying exercise an easier access to the control widgets
        (Referencing the control widgets>).
        With this function several controlbars can be generated by the exercises to enable the acces to such an
        specific controlbar, control of the respective audio signal, the controlbarName can be used to address a
        specific controlbar.

        With layoutMode the controlls can be arranged vertically stacked or inline. The belonging options are
         'stacked' or 'inline'.
        In the vertically stacked layout the slider and its labels is found at the top and big control buttons below.
        In the "inline" layout the slider with its labels and the control buttons are in line with smaller control
        buttons.

        Referencing the control widgets:

        To avoid non telling references in the exercises controlbarRefs is returned for easier references
        self.playBtn = controlbar.children()[1].itemAt(0).widget()
        self.pauseBtn = controlbar.children()[1].itemAt(1).widget()
        self.stopBtn = controlbar.children()[1].itemAt(2).widget()
        self.seekSlider = controlbar.children()[0].itemAt(1).widget().objectName()
        self.seekSliderLabelStart = controlbar.children()[0].itemAt(0).widget().objectName()
        self.seekSliderLabelEnd = controlbar.children()[0].itemAt(2).widget().objectName()

        is equal to

        self.playBtn = controlbarRefs['playBtn']
        self.pauseBtn = controlbarRefs['pauseBtn']
        self.stopBtn = controlbarRefs['stopBtn']
        self.seekSlider = controlbarRefs['seekSlider']
        self.seekSliderLabelStart = controlbarRefs['seekSliderLabelStart']
        self.seekSliderLabelEnd = controlbarRefs['seekSliderLabelEnd']

        If other controls like 'volumeDescBtn' or 'volumeIncBtn' will be added or the the order of the control
        changes the references won't change.
        """

        if layoutMode == 'stacked':
            controlbar = QtWidgets.QVBoxLayout()  # centralWidget
        else:
            controlbar = QtWidgets.QHBoxLayout()  # centralWidget

        seekSliderLayout = QtWidgets.QHBoxLayout()
        controls = QtWidgets.QHBoxLayout()
        # playlistCtrlLayout = QtWidgets.QHBoxLayout()

        controlbar.setObjectName(controlbarName)
        seekSliderLayout.setObjectName('seekSliderLayout')
        controls.setObjectName('controls')

        # creating buttons
        if layoutMode == 'stacked':
            playBtn = QtWidgets.QPushButton(_translate("playQtAudio", 'Play', None))  # play button
            pauseBtn = QtWidgets.QPushButton(_translate("playQtAudio", 'Pause', None))  # pause button
            stopBtn = QtWidgets.QPushButton(_translate("playQtAudio", 'Stop', None))  # stop button
            # volumeDescBtn = QtWidgets.QPushButton('V (-)')  # Decrease Volume
            # volumeIncBtn = QtWidgets.QPushButton('V (+)')  # Increase Volume

        else:
            # playButton
            objectName = f"pbPlay_{controlbarName:s}"
            playBtn = QtWidgets.QPushButton(text='', objectName=objectName)
            file  = os.path.join(self.parHandle.curExercise['path']['recources'], 'play.png')
            playBtn.setIcon(QtGui.QIcon(file))
            playBtn.setIconSize(QtCore.QSize(32, 32))
            playBtn.setMaximumSize(32, 32)
            playBtn.setMinimumSize(32, 32)
            playBtn.setStyleSheet("background-image: url('image.jpg'); border: none;")

            # pauseButton
            objectName = f"pbPause_{controlbarName:s}"
            pauseBtn = QtWidgets.QPushButton(text='', objectName=objectName)
            file  = os.path.join(self.parHandle.curExercise['path']['recources'], 'pause.png')
            pauseBtn.setIcon(QtGui.QIcon(file))
            pauseBtn.setIconSize(QtCore.QSize(32, 32))
            pauseBtn.setMaximumSize(32, 32)
            pauseBtn.setMinimumSize(32, 32)
            pauseBtn.setStyleSheet("background-image: url('image.jpg'); border: none;")

            # stopButton
            stopBtn = QtWidgets.QPushButton('Stop')  # stop button
            objectName = f"pbStop_{controlbarName:s}"
            stopBtn = QtWidgets.QPushButton(text='', objectName=objectName)
            file  = os.path.join(self.parHandle.curExercise['path']['recources'], 'stop.png')
            stopBtn.setIcon(QtGui.QIcon(file))
            stopBtn.setIconSize(QtCore.QSize(32, 32))
            stopBtn.setMaximumSize(32, 32)
            stopBtn.setMinimumSize(32, 32)
            stopBtn.setStyleSheet("background-image: url('image.jpg'); border: none;")

        playBtn.setObjectName('playBtn')
        pauseBtn.setObjectName('pauseBtn')
        stopBtn.setObjectName('stopBtn')

        # creating seek slider

        seekSlider = QtWidgets.QSlider()
        seekSlider.setObjectName('seekSlider')
        seekSlider.setMinimum(0)
        seekSlider.setMaximum(100)
        seekSlider.setOrientation(QtCore.Qt.Horizontal)
        seekSlider.setTracking(False)
        seekSlider.sliderMoved.connect(self.setPosition)

        seekSliderLabelStart = QtWidgets.QLabel('0.00')
        seekSliderLabelEnd = QtWidgets.QLabel('0.00')

        seekSliderLabelStart.setObjectName('seekSliderLabelStart')
        seekSliderLabelEnd.setObjectName('seekSliderLabelEnd')

        seekSliderLayout.addWidget(seekSliderLabelStart)
        seekSliderLayout.addWidget(seekSlider)
        seekSliderLayout.addWidget(seekSliderLabelEnd)

        # Add handler for each button. Not using the default slots.
        playBtn.clicked.connect(self.playHandler)
        pauseBtn.clicked.connect(self.pauseHandler)
        stopBtn.clicked.connect(self.stopHandler)

        # Adding to the horizontal layout
        # controls.addWidget(volumeDescBtn)
        controls.addWidget(playBtn)
        controls.addWidget(pauseBtn)
        controls.addWidget(stopBtn)
        # controls.addWidget(volumeIncBtn)

        # Adding to the vertical layout
        controlbar.addLayout(seekSliderLayout)
        controlbar.addLayout(controls)

        controlbarRefs = dict()
        controlbarRefs['playBtn'] = playBtn
        controlbarRefs['pauseBtn'] = pauseBtn
        controlbarRefs['stopBtn'] = stopBtn
        controlbarRefs['seekSlider'] = seekSlider
        controlbarRefs['seekSliderLabelStart'] = seekSliderLabelStart
        controlbarRefs['seekSliderLabelEnd'] = seekSliderLabelEnd

        self.playerWidgetConverter[playBtn] = controlbarName
        self.playerWidgetConverter[pauseBtn] = controlbarName
        self.playerWidgetConverter[stopBtn] = controlbarName
        self.playerWidgetConverter[seekSlider] = controlbarName
        self.playerWidgetConverter[seekSliderLabelStart] = controlbarName
        self.playerWidgetConverter[seekSliderLabelEnd] = controlbarName

        if not(self.controlbarLabel):
            self.controlbarLabel = controlbarName
        else:
            self.controlbarLabel = ''

        return controlbar, controlbarRefs

    def state(self):
        """!
        Returns state of the player as defined by userAction in playAudio

        Possible states are:

        0: player is stopped
        1: player is running
        2: player is paused
        -1: player state is undefined
        """

        self.parHandle.dPrint('playQtAudio: state()', 2)

        playerState = -1
        if self.player.state() == QtMultimedia.QMediaPlayer.StoppedState:
            playerState = 0
        elif self.player.state() == QtMultimedia.QMediaPlayer.PlayingState:
            playerState = 1
        elif self.player.state() == QtMultimedia.QMediaPlayer.PausedState:
            playerState = 2

        self.parHandle.dPrint('playQtAudio: Leaving state()', 2)

        return playerState

    def setPosition(self, position):
        """!
        The media pointer is set to position.
        """

        self.parHandle.dPrint('playQtAudio: setPosition()', 2)

        self.player.setPosition(position)

        self.parHandle.dPrint('playQtAudio: Leaving setPosition()', 2)

    def getControlbarCaller(self, inputWidget):
        """!
        This function takes the inputWidget (button) and checks for the name of the parent control bar.
        This function can bed used to determine which controlbar has been used, if multiple controlbars are used in the
        callingexercise.
        """

        self.parHandle.dPrint('playQtAudio: getControlbarCaller()', 2)

        if inputWidget in self.playerWidgetConverter:
            return self.playerWidgetConverter[inputWidget]
        else:
            return self.controlbarLabel

        self.parHandle.dPrint('playQtAudio: Leaving sgetControlbarCalleretPosition()', 2)

    def setDefaultSettings(self):
        """!
        The default parameters are set.
        """

        self.parHandle.dPrint('playQtAudio: setDefaultSettings()', 2)

        playerBaseName                      = self.parHandle.frameWork['path']['player']
        playerName                          = 'playQtAudio'

        self.parHandle.initializeToDefaults(mode='curPlayerSettings')

        self.parHandle.curPlayer['settings']['playerName']         = playerName
        self.parHandle.curPlayer['path']         = dict()
        self.parHandle.curPlayer['path']['base'] = os.path.join(playerBaseName, playerName)
        self.parHandle.curPlayer['path']['presets'] = os.path.join(self.parHandle.curPlayer['path']['base'], 'presets')

        self.parHandle.curPlayer['settings']['settingsName']    = 'default'
        self.parHandle.curPlayer['settings']['fs']              = 44100
        self.parHandle.curPlayer['settings']['level']           = 65
        self.parHandle.curPlayer['settings']['visualPreparation'] = False
        self.parHandle.curPlayer['settings']['visualPreparationTime'] = 0.4
        self.parHandle.curPlayer['settings']['waitFlag']       = True

        self.parHandle.curPlayer['settings']['comment']         = 'No comment'

        self.parHandle.curPlayer['settingLimits'] = dict()
        self.parHandle.curPlayer['settingLimits']['playerName'] = self.parHandle.setSettingLimitsTemplate()
        self.parHandle.curPlayer['settingLimits']['playerName']['type'] = 'string'
        self.parHandle.curPlayer['settingLimits']['playerName']['mandatory'] = True
        self.parHandle.curPlayer['settingLimits']['playerName']['editable'] = False
        self.parHandle.curPlayer['settingLimits']['playerName']['range'] = []

        self.parHandle.curPlayer['settingLimits']['settingsName'] = self.parHandle.setSettingLimitsTemplate()
        self.parHandle.curPlayer['settingLimits']['settingsName']['type'] = ['string']
        self.parHandle.curPlayer['settingLimits']['settingsName']['mandatory'] = True
        self.parHandle.curPlayer['settingLimits']['settingsName']['editable'] = True
        self.parHandle.curPlayer['settingLimits']['settingsName']['range'] = []

        self.parHandle.curPlayer['settingLimits']['fs'] = self.parHandle.setSettingLimitsTemplate()
        self.parHandle.curPlayer['settingLimits']['fs']['type'] = 'int'
        self.parHandle.curPlayer['settingLimits']['fs']['mandatory'] = False
        self.parHandle.curPlayer['settingLimits']['fs']['editable'] = False
        self.parHandle.curPlayer['settingLimits']['fs']['range'] = [8000, 16000, 32000, 44100, 48000, 96000]
        self.parHandle.curPlayer['settingLimits']['fs']['comboBoxStyle'] = True
        self.parHandle.curPlayer['settingLimits']['fs']['unit'] = 's'
        self.parHandle.curPlayer['settingLimits']['fs']['label'] = _translate("playQtAudio", "sampling rate", None)
        self.parHandle.curPlayer['settingLimits']['fs']['default'] = 44100

        self.parHandle.curPlayer['settingLimits']['level'] = self.parHandle.setSettingLimitsTemplate()
        self.parHandle.curPlayer['settingLimits']['level']['type'] = 'float'
        self.parHandle.curPlayer['settingLimits']['level']['mandatory'] = False
        self.parHandle.curPlayer['settingLimits']['level']['editable'] = True
        self.parHandle.curPlayer['settingLimits']['level']['range'] = [0, 85]
        self.parHandle.curPlayer['settingLimits']['level']['unit'] = 'dB'
        self.parHandle.curPlayer['settingLimits']['level']['label'] = _translate("playQtAudio", "level", None)
        self.parHandle.curPlayer['settingLimits']['level']['default'] = 65

        self.parHandle.curPlayer['settingLimits']['visualPreparation'] = self.parHandle.setSettingLimitsTemplate()
        self.parHandle.curPlayer['settingLimits']['visualPreparation']['type'] = 'bool'
        self.parHandle.curPlayer['settingLimits']['visualPreparation']['mandatory'] = False
        self.parHandle.curPlayer['settingLimits']['visualPreparation']['editable'] = True
        self.parHandle.curPlayer['settingLimits']['visualPreparation']['range'] = [True, False]
        self.parHandle.curPlayer['settingLimits']['visualPreparation']['comboBoxStyle']= True
        self.parHandle.curPlayer['settingLimits']['visualPreparation']['unit'] = ''
        self.parHandle.curPlayer['settingLimits']['visualPreparation']['label'] = _translate("playQtAudio", "Visual preparation", None)
        self.parHandle.curPlayer['settingLimits']['visualPreparation']['default'] = 44100

        self.parHandle.curPlayer['settingLimits']['visualPreparationTime'] = self.parHandle.setSettingLimitsTemplate()
        self.parHandle.curPlayer['settingLimits']['visualPreparationTime']['type'] = 'float'
        self.parHandle.curPlayer['settingLimits']['visualPreparationTime']['mandatory'] = False
        self.parHandle.curPlayer['settingLimits']['visualPreparationTime']['editable'] = True
        self.parHandle.curPlayer['settingLimits']['visualPreparationTime']['range'] = [0, 20]
        self.parHandle.curPlayer['settingLimits']['visualPreparationTime']['unit'] = 's'
        self.parHandle.curPlayer['settingLimits']['visualPreparationTime']['label'] = _translate("playQtAudio", "Preparation time", None)
        self.parHandle.curPlayer['settingLimits']['visualPreparationTime']['default'] = 0.4

        self.parHandle.curPlayer['settingLimits']['waitFlag'] = self.parHandle.setSettingLimitsTemplate()
        self.parHandle.curPlayer['settingLimits']['waitFlag']['type'] = 'bool'
        self.parHandle.curPlayer['settingLimits']['waitFlag']['mandatory'] = False
        self.parHandle.curPlayer['settingLimits']['waitFlag']['editable'] = True
        self.parHandle.curPlayer['settingLimits']['waitFlag']['range'] = [True, False]
        self.parHandle.curPlayer['settingLimits']['waitFlag']['comboBoxStyle'] = True
        self.parHandle.curPlayer['settingLimits']['waitFlag']['label'] = _translate("playQtAudio", "Wait for audio end", None)
        self.parHandle.curPlayer['settingLimits']['waitFlag']['default'] = True

        self.parHandle.dPrint('playQtAudio: Leaving setDefaultSettings()', 2)

    def loadSettings(self, settings):
        """
        Loading settings ....
        The settings are searched for in as .py files in the presets path of
        the current exercise.
        """

        self.parHandle.dPrint('playQtAudio: loadSettings()', 2)
        try:
            self.parHandle.loadSettings(settings, module = 'curPlayer')
        except:
            self.setDefaultSettings()
            if isinstance(settings, str):
                settingsName = settings
            else:
                settingsName = 'settings (dict)'
            print('Could not load settings (' + settingsName + ') loading default settings instead')
        self.parHandle.dPrint('playQtAudio: Leaving loadSettings()', 2)


"""empty message

Revision ID: a99faa0cc155
Revises: 4a907061bba7
Create Date: 2021-04-23 21:15:51.931598

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'a99faa0cc155'
down_revision = '4a907061bba7'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('users', schema=None) as batch_op:
        batch_op.add_column(sa.Column('username', sa.String(length=255, collation='NOCASE'), nullable=False))
        batch_op.drop_constraint('uq_users_email', type_='unique')
        batch_op.create_unique_constraint(batch_op.f('uq_users_username'), ['username'])
        batch_op.drop_column('email')

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('users', schema=None) as batch_op:
        batch_op.add_column(sa.Column('email', sa.VARCHAR(length=255), nullable=False))
        batch_op.drop_constraint(batch_op.f('uq_users_username'), type_='unique')
        batch_op.create_unique_constraint('uq_users_email', ['email'])
        batch_op.drop_column('username')

    # ### end Alembic commands ###


graph = {1:[2,4], 2:[1,3], 3:[3,4],4:[1,3]}

def dfs(g, s=1):
    g[0] = [0]
    stack = []
    visited = [0 for x in range(len(g))]
    stack.append(s)

    while stack:
        u = stack.pop(-1)
        visited[u] = 1
        edges = g[u]
        for v in edges:
            if not visited[v]:
                stack.append(v)
    return visited

def bfs(g, s=1):
    g[0] = 0
    visited = [0 for x in range(len(g))]
    q = []
    q.append(s)

    while q:
        u = q.pop(0)
        visited[u] = 1
        edges = g[u]
        for v in edges:
            if not visited[v]:
                q.append(v)

    return visited

if __name__=="__main__":
    g = graph
    print(dfs(g))
    print(bfs(g))


# first corpus, model omitted as unsuccessful
import os
os.chdir("D:\\Study\\CL\\prj2")
import numpy as np
import numpy as np
import pandas as pd
#load mails and toxic corpus
mail=pd.read_csv("mail_fromr_clean.csv",  delimiter=";")
toxic=pd.read_csv("Inappapropriate_messages.csv")

mail.columns
mail.rename(columns={'body':'text'},inplace = True)
#labelling
mail=mail.assign(label="mails")
toxic=toxic.assign(label="random")
#save
tryout=mail.append(toxic)
tryout['label'].value_counts()
tryout.to_csv("tryout1.csv")

#start classif
f = feature_extraction.text.CountVectorizer(stop_words = stoplist_mail)
X = f.fit_transform(tryout["text"])
print(f.get_feature_names()[1000:1020])
print(X.toarray())
X.shape
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, tryout['label'], test_size=0.2, random_state=50)
print(X_train.shape, X_test.shape)
print(y_train.shape, y_test.shape)

#tune
list_alpha = np.arange(1/100000, 20, 0.11)
print(len(list_alpha))
score_train = np.zeros(len(list_alpha)) # accuracy on train set
score_test = np.zeros(len(list_alpha)) #accuracy on test set
recall_test = np.zeros(len(list_alpha)) # recall on test
precision_test= np.zeros(len(list_alpha))

count = 0
for alpha in list_alpha: # для каждого значения в списке альф
    bayes = naive_bayes.MultinomialNB(alpha=alpha) # вызываем модель
    bayes.fit(X_train, y_train) # тренируем модель
    score_train[count] = bayes.score(X_train, y_train) # итерируемся по индексу в листе, добавляем значения accuracy on train
    score_test[count]= bayes.score(X_test, y_test) # то же самое,но для accuracy на тестовой выборке
    # а теперь для precision и recall
    recall_test[count] = metrics.recall_score(y_test, bayes.predict(X_test),pos_label='mails')
    precision_test[count] = metrics.precision_score(y_test, bayes.predict(X_test),pos_label='mails')
    count = count + 1 # после одной итерации, делаем новый шаг,  чтобы пройтись по всем alpha

#check fit metrics
matrix = np.matrix(np.c_[list_alpha, score_train, score_test, recall_test, precision_test])
models = pd.DataFrame(data = matrix,
                      columns = ['alpha',
                                 'Train Accuracy',
                                 'Test Accuracy',
                                 'Test Recall',
                                 'Test Precision'])

print(models.head(10))
print(matrix.shape)
#get best metrics
best_index = models['Test Accuracy'].idxmax()
print(models.iloc[best_index])
bayes = naive_bayes.MultinomialNB(alpha=16.390010, )
bayes.fit(X_train, y_train)
y_pred = bayes.predict(X_test)

#сделаем датафрейм с колонками для настоящего класса(это y_test) и для предсказанного (y_pred)

new_df = pd.DataFrame(data = y_test)
new_df["predicted"]=bayes.predict(X_test)
m_confusion_test = metrics.confusion_matrix(y_test, y_pred)
pd.DataFrame(data = m_confusion_test, columns = ['Predicted mail', 'Predicted random'],
            index = ['Actual mail', 'Actual random'])


#! /usr/bin/env python
# coding=utf-8

import tensorflow as tf
import os
import time
import datetime
import data_input_helper as data_helpers
from tensor_textcnn import TextCNN
# from text_cnn import TextCNN
import math
from tensorflow.contrib import learn
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
import numpy as np

import jieba
import jieba.posseg as pseg
from tensor_birnn import TextBiRNN
# from text_birnn import TextBiRNN
from tensor_textdnn import TextDNN
from tensor_textrcnn import TextRCNN
from tensor_textrnn import TextRNN
from tensor_textfast import TextFast

from utils import get_vocabulary_size, fit_in_vocabulary, zero_pad, batch_generator

# Parameters
# ==================================================
# Data loading params
model_type = "clf" #"the type of model ,classify or regression(defalut=clf)"
using_nn_type = "text_cnn" #the type of network(default:textcnn)
dev_sample_percentage = 0.1 # "Percentage of the training data to use for validation"
train_data_file =  "./data/cutclean_label_corpus10000.txt" #"Data source for the positive data."
train_label_data_file = "" #"Data source for the label data."
w2v_file =  "./data/vectors.bin"  #"w2v_file path"

# Model Hyperparameters
embedding_dim = 128 #"Dimensionality of character embedding (default: 128)"
filter_sizes = "2,3,4"  # "Comma-separated filter sizes (default: '3,4,5')"
num_filters = 128  #"Number of filters per filter size (default: 128)"
dropout_keep_prob = 0.5  #"Dropout keep probability (default: 0.5)"
l2_reg_lambda = 0.0  #"L2 regularization lambda (default: 0.0)"
hidden_size = 128  #"Number of hiddern layer units(defalut:128)"
hidden_layers  = 2  # "Number of hidden layers(default:2)"
rnn_size = 300  #"num of units rnn_size(default:3)"
num_rnn_layers  = 3  #"number of rnn layers(default:3)"

# Training parameters
batch_size = 64  #"Batch Size (default: 64)"
num_epochs  = 10  # "Number of training epochs (default: 200)"
evaluate_every = 50  #"Evaluate model on dev set after this many steps (default: 100)"
checkpoint_every = 100  #"Save model after this many steps (default: 100)"
num_checkpoints = 5  ##"Number of checkpoints to store (default: 5)"

# Misc Parameters
allow_soft_placement = True ## "Allow device soft device placement"
log_device_placement = False  ###"Log placement of ops on devices"

# FLAGS = tf.flags.FLAGS
# FLAGS.flag_values_dict()
# print("\nParameters:")
# for attr, value in sorted(FLAGS.flag_values_dict().items()):
#     print("{}={}".format(attr.upper(), value))
# print("")

#
def load_data(w2v_model=None):
    print("laoding data")
    x_text, y = data_helpers.load_data_and_labels(train_data_file)
    max_document_length = max([len(x.split(" ")) for x in x_text])
    if (w2v_model == None):
        vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
        x = np.array(list(vocab_processor.fit_transform(x_text)))
        vocab_size = len(vocab_processor.vocabulary_)
    else:
        x = data_helpers.get_text_idx(x_text, w2v_model.vocab_hash, max_document_length)
        vocab_size = len(w2v_model.vocab_hash)
        print('use w2v .bin')

    np.random.seed(10)
    shuffle_indices = np.random.permutation(np.arange(len(y)))
    x_shuffled = x[shuffle_indices]
    y_shuffled = y[shuffle_indices]

    dev_sample_index = -1 * int(dev_sample_percentage * float(len(y)))
    x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]
    y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]

    return x_train, x_dev, y_train, y_dev, vocab_size

# #####################--------------载入数据----

x_train1, x_dev1, y_train1, y_dev1, vocab_size1 = load_data(None)
#############--------定义nn类型
nn_type = "text_rnn"

############-----------------------载入imdb数据
from keras.datasets import imdb
from keras.preprocessing import sequence
from keras.utils import to_categorical
max_features = 10000
maxlen = 500
# batch_size = 32
print("load data")
(input_train,y_train),(input_test,y_test) = imdb.load_data(num_words=max_features)
print(len(input_train),"train_sequence")
print(len(input_test),"test sequence")

print("padding _squence")
input_train = sequence.pad_sequences(input_train,maxlen=maxlen)
input_test = sequence.pad_sequences(input_test,maxlen=maxlen)
print(input_train.shape,"input_trian_shape")
print(input_test.shape,"input_test_shape")
######----------y_train转化为one_hot
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
##########----------字典的大小-----
vocab_size = np.max([np.max(input_train[i]) for i in range(input_train.shape[0])])+1
print("vocab_size,--字典大小   ",vocab_size)

#####-------------------d带入训练
x_train = input_train.copy()

x_dev = input_test.copy()
y_dev = y_test.copy()

def train():
    # Training
    # ==================================================
    # x_train, x_dev, y_train, y_dev ,vocab_size= load_data(w2v_model)
    with tf.Graph().as_default():
        session_conf = tf.ConfigProto(
            allow_soft_placement=allow_soft_placement,
            log_device_placement=log_device_placement)
        sess = tf.Session(config=session_conf)
        with sess.as_default():
            if (nn_type == "text_cnn"):
                nn = TextCNN(
                    model_type=model_type,
                    sequence_length=x_train.shape[1],
                    num_classes=y_train.shape[1],
                    vocab_size=vocab_size,
                    embedding_size=embedding_dim,
                    filter_sizes=list(map(int, filter_sizes.split(","))),
                    num_filters=num_filters,
                    l2_reg_lambda=l2_reg_lambda
                )
            elif nn_type == "text_birnn":
                nn = TextBiRNN(
                    model_type=model_type,
                    sequence_length=x_train.shape[1],
                    num_classes=y_train.shape[1],
                    vocab_size=vocab_size,
                    embedding_size=embedding_dim,
                    rnn_size=128,
                    num_layers=3,
                    l2_reg_lambda=l2_reg_lambda
                )
            elif nn_type == "text_rnn":
                nn = TextRNN(
                    model_type=model_type,
                    sequence_length=x_train.shape[1],
                    num_classes=y_train.shape[1],
                    vocab_size=vocab_size,
                    embedding_size=embedding_dim,
                    rnn_size=128,
                    num_layers=3,
                    l2_reg_lambda=l2_reg_lambda
                )
            elif nn_type == "text_rcnn":
                nn = TextBiRNN(
                    model_type=model_type,
                    sequence_length=x_train.shape[1],
                    num_classes=y_train.shape[1],
                    vocab_size=vocab_size,
                    embedding_size=embedding_dim,
                    rnn_size=128,
                    num_layers=3,
                    l2_reg_lambda=l2_reg_lambda
                )
            elif nn_type == "text_dnn":
                nn = TextDNN(
                    model_type=model_type,
                    sequence_length=x_train.shape[1],
                    num_classes=y_train.shape[1],
                    vocab_size=vocab_size,
                    embedding_size=embedding_dim,
                    hidden_layes=2,
                    hidden_size=128,
                    l2_reg_lambda=l2_reg_lambda
                )
            elif nn_type == "text_fasttext":
                nn = TextFast(
                    model_type=model_type,
                    sequence_length=x_train.shape[1],
                    num_classes=y_train.shape[1],
                    vocab_size=vocab_size,
                    embedding_size=embedding_dim,
                    l2_reg_lambda=l2_reg_lambda
                )

            # Define Training procedure
            global_step = tf.Variable(0, name="global_step", trainable=False)
            optimizer = tf.train.AdamOptimizer(1e-3)
            grads_and_vars = optimizer.compute_gradients(nn.loss)
            train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)

            # Initialize all variables
            sess.run(tf.global_variables_initializer())

            def train_step(x_batch, y_batch):
                """
                A single training step
                """
                feed_dict = {
                    nn.input_x: x_batch,
                    nn.input_y: y_batch,
                    nn.dropout_keep_prob: dropout_keep_prob
                }
                _, step,loss, accuracy = sess.run(
                    [train_op, global_step, nn.loss, nn.accuracy],
                    feed_dict)

                time_str = datetime.datetime.now().isoformat()
                print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
                # print w[:2],idx[:2]
                # train_summary_writer.add_summary(summaries, step)

            def dev_step(x_batch, y_batch, writer=None):
                """
                Evaluates model on a dev set
                """
                feed_dict = {
                    nn.input_x: x_batch,
                    nn.input_y: y_batch,
                    nn.dropout_keep_prob: 1.0
                }

                step,loss, accuracy = sess.run(
                    [global_step, nn.loss, nn.accuracy],
                    feed_dict)
                #
                time_str = datetime.datetime.now().isoformat()
                print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))
                # if writer:
                #     writer.add_summary(summaries, step)

            # Generate batches
            batches = data_helpers.batch_iter(
                list(zip(x_train, y_train)),batch_size, num_epochs)

            def dev_test():
                batches_dev = data_helpers.batch_iter(list(zip(x_dev, y_dev)), batch_size, 1)
                for batch_dev in batches_dev:
                    x_batch_dev, y_batch_dev = zip(*batch_dev)
                    dev_step(x_batch_dev, y_batch_dev, writer=None)

            # Training loop. For each batch...
            for batch in batches:
                x_batch, y_batch = zip(*batch)
                train_step(x_batch, y_batch)
                #
                # current_step = tf.train.global_step(sess, global_step)

if __name__ == "__main__":
    # w2v_wr = data_helpers.w2v_wrapper(FLAGS.w2v_file)
    train()
    attrs = []
    values = []
    # for attr, value in sorted(FLAGS.__flags.items()):
    #     attrs += [attr]
    #     values += [value]
    # info = pd.DataFrame()
    # info["attr"] = attrs
    # info["value"] = values
    # info.to_csv(os.path.curdir + '/config.csv', index=False)


from ats.topology import loader
from library.system_info import *

testbed = 'pyats-testbed.yaml'
testbed = loader.load(testbed)
testbed = Genie.init(testbed)

n9k = testbed.devices['NetChatBot1']
n9k.connect()
n9k.execute('show version')

n9k_platform = get_platform_info(n9k)
n9k_interfaces = get_interfaces(n9k)
n9k_routing = get_routing_info(n9k)
n9k_ospf = get_ospf_info(n9k)
n9k_vlans = get_vlans(n9k)
n9k_crc_errors = crc_errors(n9k)
n9k_arps = get_arps(n9k)

print("\n\n")
print("We've now gathered a lot of details about our device with pyATS and made them available to use.")
print("Here we'll use some of the details.\n\n")

print("First let's look at some details about the OSPF interfaces configured.")
for interface, details in n9k_ospf["vrf"]["default"]["address_family"]["ipv4"]["instance"]["1"]["areas"]["0.0.0.0"]["interfaces"].items():
    print("Interface {} has cost of {}, is a {} interface, and passive state is {}".format(interface, details["cost"], details["interface_type"], details["passive"]))
print("--------------------------------------------------------------------------------\n")

print("Now we'll look at the next hops for all ipv4 routes in the routing default vrf table")
for prefix, details in n9k_routing["vrf"]["default"]["address_family"]["ipv4"]["routes"].items():
    print("For prefix {} the next hop is {} out interface {}.".format(prefix,
    details["next_hop"]["next_hop_list"][1]["next_hop"],
    details["next_hop"]["next_hop_list"][1]["outgoing_interface"]
    )
    )
print("--------------------------------------------------------------------------------\n")


file = open("ciagi.txt", "r")
ciagi = []
for x in file:
    ciag = x.split()
    if len(ciag) <= 1:
        continue
    ciag = [int(i) for i in ciag]
    ciag.pop(0)
    ciagi.append(ciag)
print(ciagi)

g = 0
gi = 0
for i, x in enumerate(ciagi):
    l = 0
    for prev, curr in zip(x, x[1:]):
        if curr > prev:
            l += 1
        else:
            if l > g:
                g = l
                gi = i - 1
            l = 1
    if l > g:
        g = l
        gi = i
print(gi)

g = 0
gi = 0
for i, x in enumerate(ciagi):
    l = 0
    for prev, curr in zip(x, x[1:]):
        if curr == prev:
            l += 1
        else:
            if l > g:
                g = l
                gi = i - 1
            l = 0
    if l > g:
        g = l
        gi = i
print(gi)


from django.urls import include, path
from .views import BoardViewSet, CategoryViewSet, TaskViewSet, UserView
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'boards', BoardViewSet, basename='boards')
router.register(r'boards/(?P<id>[\w-]+)/tasks', TaskViewSet, basename='boardtasks')
router.register(r'boards/(?P<id>[\w-]+)/categories', CategoryViewSet, basename='boardcategories')

urlpatterns = [
    path('users/', UserView.as_view()),
    path('boards/<int:id>/users/', UserView.as_view()),
    path('', include(router.urls))
]


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

class node:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right
        return None

class tree:
    def __init__(self):
        self.root = None
        return None
    def insert(self, data):
        if self.root is None:
            self.root=node(data)
        else:
            parent=self.root
            now = self.root.left if data < self.root.data else self.root.right
            while now is not None:
                parent=now
                now = now.left if data < now.data else now.right
            if data < parent.data:
                parent.left = node(data)
            else:
                parent.right = node(data)
        return self

def main():
    s = input()
    t = tree()
    for c in s.split():
        t.insert(c)
    str(t)

if __name__ == '__main__':
    main()


#!/usr/bin/python3
""" The 4-print_square module

The module defines a square-printing function.
"""

def print_square(size):
    """ prints a square with a character #
    """
    if not isinstance(size, int):
        raise TypeError("size must be an integer")
    if size < 0:
        raise ValueError("size must be >= 0")

    print(("#" * size + "\n") * size, end="")


import argparse
import asyncio
import importlib
import json
import os
import re

import cv2 as cv
import numpy as np
from PySide2.QtCore import *
import websockets

class MMRWSData():
  def __init__(self):
    self.requestType = ''
    self.dataType = ''
    self.data = {}

  def load_from_bytes(self, data):
    byteArray = QByteArray(data)
    inStream = QDataStream(byteArray)
    inStream.setVersion(QDataStream.Qt_5_9)

    self.requestType = inStream.readQString()
    self.dataType = inStream.readQString()
    self.data = inStream.readQVariant()

  def to_bytes(self):
    byteArray = QByteArray()
    outStream = QDataStream(byteArray, QIODevice.WriteOnly)
    outStream.setVersion(QDataStream.Qt_5_9)

    outStream.writeQString(self.requestType)
    outStream.writeQString(self.dataType)
    outStream.writeQVariant(self.data)

    return byteArray.data()

# parser
parser = argparse.ArgumentParser()

parser.add_argument('--config_path', help='Path of the config file', type=str)

args = parser.parse_args()

# config
config = json.load(open(args.config_path, 'r'))

# model
model_module = importlib.import_module(config['model']['name'])
model = model_module.create_model(config['model']['config'])

# modalities
modality_identifier_list = []
modality_info_list = []
modality_identifier_to_name_dict = {}
for modality_info in config['modalities']:
  if (not 'identifier' in modality_info):
    modality_info['identifier'] = ''
  if (len(modality_info['identifier']) <= 0):
    identifier = input('- input identifier for %s: ' % (modality_info['name']))
    modality_info['identifier'] = identifier

  modality_identifier_to_name_dict[modality_info['identifier']] = modality_info['name']

  modality_identifier_list.append(modality_info['identifier'])
  modality_info_list.append(modality_info)

# websocket functions
def wsPrepare():
  model.prepare()

def wsStart():
  model.start()

def wsRecognize(data):
  new_data = {}
  for (identifier, item) in data.items():
    new_item = {}
    for subitem in item:
      if (subitem['type'] == 'value'):
        new_item[subitem['name']] = subitem['value']
      elif (subitem['type'] == 'byte_array'):
        new_item[subitem['name']] = subitem['byte_array'].data()
    new_data[modality_identifier_to_name_dict[identifier]] = new_item
  return model.recognize(new_data)

def wsStop():
  model.stop()

def wsFinalize():
  model.finalize()

# run websocket
async def run():
  print('- connecting...')
  async with websockets.connect(config['server']['url'], max_size=(2**32), read_limit=(2**32), write_limit=(2**32), max_queue=(2**8)) as websocket:
    wsData = MMRWSData()
    wsData.requestType = 'register'
    wsData.dataType = 'request'
    wsData.data['name'] = config['model']['name']
    wsData.data['identifier'] = config['model']['identifier']
    wsData.data['modalities'] = modality_identifier_list
    wsData.data['fps'] = config['model']['fps']

    await websocket.send(wsData.to_bytes())
    receivedData = await websocket.recv()
    print('- connected')

    while True:
      try:
        receivedData = await websocket.recv()
        wsData = MMRWSData()
        wsData.load_from_bytes(receivedData)

        print(wsData.requestType)

        if (wsData.requestType == 'prepare'):
          wsPrepare()
        elif (wsData.requestType == 'start'):
          wsStart()
        elif (wsData.requestType == 'recognize'):
          res = wsRecognize(wsData.data)

          resWsData = MMRWSData()
          resWsData.requestType = 'recognize'
          resWsData.dataType = 'response'
          resWsData.data = res
          await websocket.send(resWsData.to_bytes())

        elif (wsData.requestType == 'stop'):
          wsStop()
        elif (wsData.requestType == 'finalize'):
          wsFinalize()
          break
      except Exception as e:
        print(e)
        break

asyncio.get_event_loop().run_until_complete(run())

# finalize


# Write a function square that takes 1 argument, the side of the square, and returns 3 values
# (using a tuple): the perimeter of the square, the area of the square, and the diagonal of the square.
from math import sqrt

def square(side: float) -> tuple:
    """
        Takes side of the square, and returns a tuple of its parameters
            (perimeter, area, diagonal)
    """
    square_perimeter = side * 4
    square_area = pow(side, 2)
    square_diagonal = round(side * sqrt(2), 3)
    return square_perimeter, square_area, square_diagonal

if __name__ == "__main__":
    square_parameters = square(2)
    print(f'Square perimeter: {square_parameters[0]}\n'
          f'Square area: {square_parameters[1]}\n'
          f'Square diagonal: {square_parameters[2]}')


import numpy as np
import pandas_datareader as pdr
import datetime as dt
import pandas as pd
import plotly.graph_objects as go
import calendar
import requests

symbol='BTCUSD' #symbol to be traded
tick_interval = '1' #candle in minutes

now = dt.datetime.utcnow()
unixtime = calendar.timegm(now.utctimetuple())
since = unixtime
start = str(since - 60 * 60 * int(tick_interval))
url = 'https://api.bybit.com/v2/public/kline/list?symbol='+symbol+'&interval='+tick_interval+'&from='+str(start)
data = requests.get(url).json()
D = pd.DataFrame(data['result'])

a = 1
c = 10

high_low = D['high'].astype(float) - D['low'].astype(float)
high_close = np.abs(D['high'].astype(float) - D['close'].astype(float).shift())
low_close = np.abs(D['low'].astype(float) - D['close'].astype(float).shift())
ranges = pd.concat([high_low, high_close, low_close], axis=1)
true_range = np.max(ranges, axis=1)

atr_indicator = true_range.rolling(c).sum()/c
nLoss = atr_indicator * a

print("############ ATR ############")
print(atr_indicator)
print("#############################")


import logging
import os
import threading
import time
from os.path import join

from ServiceRunner.Camera import Camera
from ServiceRunner.Followers import SimpleFollower
from ServiceRunner.NeuralEngine import NetHandler, process_output
from ServiceRunner.Processors import ItemProcessor
from ServiceRunner.Tools import PathManager, ItemLogger, ImageSaver

logger = logging.getLogger(__name__)

class Worker:
    def __init__(self, config):
        self.net_handler = NetHandler(config.nn_config)
        self.target_label = config.nn_config.target_label
        self.follower = SimpleFollower()
        self.item_processor = ItemProcessor()
        self.keep_running = False
        self.resolution = (config.cam_width, config.cam_height)

    def close(self):
        self.follower.close()

    def work(self):
        abs_path = os.path.dirname(os.path.abspath(__file__))
        path_manager = PathManager(join(abs_path, "..", "Images"))
        path_manager.new_set()
        item_logger = ItemLogger(path_manager.log_path)
        saver = ImageSaver(path_manager.images_pattern)
        frame_number = 0
        cam = Camera(self.resolution)

        logger.info("Starting working loop")
        while self.keep_running:
            image = cam.read()
            saver.save(image)
            logger.debug(f"Image size = {image.shape}")
            self.net_handler.load(image)
            out = self.net_handler.infer()
            items = process_output(out, frame_number, time.time(), self.target_label)
            frame_number += 1
            item = self.item_processor.process(items)
            item_logger.log(item)
            if item:
                self.follower.follow(item)
        cam.close()
        logger.info("Stopping working loop")
        item_logger.close()
        self.follower.pause()

class MultithreadWorker:
    def __init__(self, config):
        # config = ServiceConfig.read_config(r"ServiceRunner/config.json")
        self.keep_running = False
        self.resolution = (config.cam_width, config.cam_height)
        self.follower = SimpleFollower()
        self.net_handler = NetHandler(config.nn_config)
        self.target_label = config.nn_config.target_label
        self.out = None
        self.image_available = threading.Event()
        self.output_available = threading.Event()

    def work(self):
        threading.Thread(target=self._infer_loop).start()
        item_processor = ItemProcessor()
        frame_number = 0
        abs_path = os.path.dirname(os.path.abspath(__file__))
        path_manager = PathManager(join(abs_path, "..", "Images"))
        path_manager.new_set()
        saver = ImageSaver(path_manager.images_pattern)
        item_logger = ItemLogger(path_manager.log_path)
        camera = Camera(self.resolution)
        time.sleep(2.0)
        image = camera.read()
        self.net_handler.load(image)
        saver.save(image)
        self.image_available.set()
        while self.keep_running:
            image = camera.read()
            blob = self.net_handler.preprocess_image(image)
            if not self.output_available.wait(10):
                break
            self.output_available.clear()
            self.net_handler.load_blob(blob)
            self.image_available.set()
            saver.save(image)
            items = process_output(self.out, frame_number, time.time(), self.target_label)
            frame_number += 1
            item = item_processor.process(items)
            item_logger.log(item)
            if item:
                self.follower.follow(item)

        self.keep_running = False
        self.image_available.set()
        self.follower.pause()
        item_logger.close()
        camera.close()

    def _infer_loop(self):
        while self.keep_running:
            if not self.image_available.wait(10):
                break
            self.image_available.clear()
            self.out = self.net_handler.infer()
            self.output_available.set()

    def close(self):
        self.follower.close()


from pydantic import BaseModel
from typing import List, Optional

# File
class FileBase(BaseModel):
    title: str
    description: str | None = None

class File(FileBase):
    id: int
    description: str | None = None
    owner_id: int

    class Config:
        orm_mode = True

class FileSchema(BaseModel):
    own_files: list[File] = []
    shared_files: list[File] = []

# Token
class Token(BaseModel):
    access_token: str
    token_type: str

class TokenData(BaseModel):
    username: Optional[str] = None
    scopes: List[str] = []

# User
class UserBase(BaseModel):
    username: str

class UserCreate(UserBase):
    password: str

class User(UserBase):
    id: int

    class Config:
        orm_mode = True

class UserSchema(User):
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None
    is_admin: bool
    files: list[File] = []

class Perm(BaseModel):
    id: int
    user_id: int
    file_id: int
    view: bool
    rename: bool
    delete: bool

    class Config:
        orm_mode = True

# Sessions
class SessionData(BaseModel):
    token: str


#!/usr/bin/env python3
# vim: set expandtab cindent sw=4 ts=4:
#
# (C)2015 Jan Tulak <jan@tulak.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import unittest
from unittest import mock as mock
import json
import dummy
import huefri
import huefri.common
from huefri.tradfri import Tradfri

class TestTradfri(unittest.TestCase):

    def setUp(self):
        self.fnt_log = huefri.common.log
        huefri.common.log = lambda x,y: None
        huefri.tradfri.log = lambda x,y: None
        huefri.common.Config._config = json.loads("""{
            "hue":{
                "addr":"hue",
                "secret": "SECRET1",
                "controlled": [1,2,3],
                "main": 1
                },
            "tradfri":{
                "addr": "tradfri",
                "secret": "SECRET2",
                "controlled": [0,1,2],
                "main": 0
                }
            }""")
        self.map = [
            {"hex": "efd275", # warm - 34,98 in OpenHab
                "hsb": {'on': True, 'hue':  6188, 'sat': 249}},
            {"hex": "f1e0b5", # medium - 42,59 in OpenHab
                "hsb": {'on': True, 'hue':  7644, 'sat': 150}},
            {"hex": "f5faf6", # cold - 216,5 in OpenHab
                "hsb": {'on': True, 'hue': 39312, 'sat':  13}},
        ]
        self.cls_map = huefri.common.COLORS_MAP
        huefri.common.COLORS_MAP = self.map
        with mock.patch('pytradfri.coap_cli.api_factory', dummy.TAPI) as m:
            with mock.patch('pytradfri.gateway.Gateway', dummy.Gateway) as n:
                self.tradfri = Tradfri.autoinit()

    def tearDown(self):
        huefri.common.log = self.fnt_log
        huefri.common.COLORS_MAP = self.cls_map

    def test_init(self):
        with mock.patch('pytradfri.coap_cli.api_factory', dummy.TAPI) as m:
            with mock.patch('pytradfri.gateway.Gateway', dummy.Gateway) as n:
                tradfri = Tradfri.autoinit()
        self.assertEqual('tradfri', tradfri.api.ip)
        self.assertIsNone(tradfri.color)
        self.assertTrue(isinstance(tradfri.gateway, dummy.Gateway))

    def test__set(self):
        self.tradfri._set(0, "caffee", 100)
        self.assertEqual("caffee", self.tradfri.gateway.lights[0].color)
        self.assertEqual(100, self.tradfri.gateway.lights[0].dimmer)
        self.assertTrue(self.tradfri.gateway.lights[0].state)

        self.tradfri._set(0, "caffee", 0)
        self.assertEqual("caffee", self.tradfri.gateway.lights[0].color)
        self.assertFalse(self.tradfri.gateway.lights[0].state)

        # we didn't changed any other light
        self.assertIsNone(self.tradfri.gateway.lights[1].color)

    def test_set_all(self):
        self.tradfri.set_all("bababa", 150)
        self.assertEqual("bababa", self.tradfri.gateway.lights[0].color)
        self.assertEqual("bababa", self.tradfri.gateway.lights[1].color)
        self.assertEqual("bababa", self.tradfri.gateway.lights[2].color)
        self.assertIsNone(self.tradfri.gateway.lights[3].color)

        self.assertEqual(150, self.tradfri.gateway.lights[0].dimmer)
        self.assertTrue(self.tradfri.gateway.lights[2].state)

    def test_changed(self):
        # exception if we don't know about hue
        self.tradfri.hue = None
        with self.assertRaises(Exception):
            self.tradfri.changed()

        # set up
        self.tradfri.set_all("bababa", 150)
        self.tradfri.hue = dummy.DummyHub()

        # save current state
        self.tradfri.hue.set_time_to_now()
        self.assertFalse(self.tradfri.changed())
        # move time, test if it remembers state
        self.tradfri.hue.set_time_to_past()
        self.assertFalse(self.tradfri.changed())

        # change state
        self.tradfri.set_all("caffee", 100)
        self.assertTrue(self.tradfri.changed())
        # move time, test if it remembers state
        self.tradfri.hue.set_time_to_past()
        self.assertFalse(self.tradfri.changed())

    def test_update(self):
        self.tradfri.hue = dummy.DummyHub()

        # the colors of tradfri should change
        with mock.patch('huefri.tradfri.Tradfri.changed', lambda x: True) as m:
            self.tradfri.set_all("efd275", 100)
            self.tradfri.update()
            self.assertEqual({'on': True, 'hue':  6188, 'sat': 249, 'bri': 100}, self.tradfri.hue.hsb)

        # the colors of tradfri should stay same as in the previous case
        with mock.patch('huefri.tradfri.Tradfri.changed', lambda x: False) as m:
            self.tradfri.set_all("f5faf6", 150)
            self.tradfri.update()
            self.assertEqual({'on': True, 'hue':  6188, 'sat': 249, 'bri': 100}, self.tradfri.hue.hsb)


import tensorflow as tf
import numpy as np
from utils import next_batch
from skimage.io import imread
from skimage.transform import resize

class relation_network():
	def __init__(self):
		self.sample_image=tf.placeholder(tf.float32,[5,28,28,1])
		self.query_image=tf.placeholder(tf.float32,[19*5,28,28,1])
		self.target=tf.placeholder(tf.int64,[19*5])
		self.mode=tf.placeholder_with_default(False,shape=[])
	def conv_block(self,feature_in,filters,kernel_size,padding='same'):
		conv=tf.layers.conv2d(feature_in,filters=filters,kernel_size=kernel_size,padding=padding)
		bn=tf.layers.batch_normalization(conv,training=self.mode)
		return tf.nn.relu(bn)
	def embedding(self,image_in):
		conv1=self.conv_block(image_in,64,3,padding='valid')
		pool1=tf.layers.max_pooling2d(conv1,pool_size=2,strides=2)
		conv2=self.conv_block(pool1,64,3,padding='valid')
		pool2=tf.layers.max_pooling2d(conv2,pool_size=2,strides=2)
		conv3=self.conv_block(pool2,64,3)
		conv4=self.conv_block(conv3,64,3)
		return conv4
	def feature_concatenation(self):
		sample_feature=self.embedding(self.sample_image)
		sample_feature=tf.expand_dims(sample_feature,[0])
		sample_feature=tf.tile(sample_feature,[19*5,1,1,1,1])
		query_feature=self.embedding(self.query_image)
		query_feature=tf.expand_dims(query_feature,[0])
		query_feature=tf.tile(query_feature,[5,1,1,1,1])
		query_feature=tf.transpose(query_feature,[1,0,2,3,4])
		concatenation_map=tf.concat([sample_feature,query_feature],axis=-1)
		concatenation_map=tf.reshape(concatenation_map,[-1,5,5,128])
		# print(concatenation_map)
		return concatenation_map
	def relation(self):
		feature_map=self.feature_concatenation()
		conv_rela1=self.conv_block(feature_map,64,3)
		pool_rela1=tf.layers.max_pooling2d(conv_rela1,pool_size=2,strides=2)
		conv_rela2=self.conv_block(pool_rela1,64,3)
		pool_rela2=tf.layers.max_pooling2d(conv_rela2,pool_size=2,strides=2)
		fc1=tf.layers.flatten(pool_rela2)
		fc2=tf.layers.dense(fc1,8,activation=tf.nn.relu)
		fc3=tf.layers.dense(fc2,1,activation=tf.nn.sigmoid)
		return tf.reshape(fc3,[-1,5])
	def read_image(self,file):
		images=[]
		for file_name in file:
			image=imread(file_name)/255.0
			image=resize(image,(28,28))
			image=(image-0.92206)/0.08426
			images.append(np.expand_dims(image,axis=-1))
		return images
	def accuracy(self,predict,label):
		correct=tf.equal(tf.argmax(predict,1),label)
		return tf.reduce_mean(tf.cast(correct,tf.float32))
	def train(self):
		logits=self.relation()
		mse_loss=tf.reduce_mean(tf.square(tf.one_hot(self.target,5)-logits))
		optimizer=tf.train.AdamOptimizer(0.001).minimize(mse_loss)
		accuracy=self.accuracy(logits,self.target)
		with tf.Session() as sess:
			sess.run(tf.global_variables_initializer())
			for step in range(1000):
				sample_image,query_image,target=next_batch(5,1,19)
				sample_image=self.read_image(sample_image)
				query_image=self.read_image(query_image)
				idx=np.arange(0,len(query_image))
				np.random.shuffle(idx)
				query_image=np.array(query_image)[idx]
				target=np.array(target)[idx]
				loss,_,acc=sess.run([mse_loss,optimizer,accuracy],feed_dict={self.sample_image:sample_image,
																self.query_image:query_image,
																self.target:target,
																self.mode:True})
				if step%10==0:
					print("number step %d,loss is %f"%(step,loss))
					print("number step %d,accuracy is %f"%(step,acc))


import pytest

from applications.choices import ApplicationStatusChoice
from tests.factories import ApplicationFactory, ApplicationRoundFactory

# Applied to all tests
pytestmark = [
    pytest.mark.django_db,
    pytest.mark.usefixtures("_disable_elasticsearch"),
]

def test_reset_application_allocation():
    # given:
    # - There is a single handled application in an application round in allocation
    application_round = ApplicationRoundFactory.create_in_status_in_allocation()
    application = ApplicationFactory.create_in_status_handled(application_round=application_round)

    # when:
    # - User tries to reset allocation on the application
    application.actions.reset_application_allocation()

    # then:
    # - The application is in allocation again
    application.refresh_from_db()
    assert application.status == ApplicationStatusChoice.IN_ALLOCATION

def test_reset_application_round_allocation():
    # given:
    # - There is a single handled application in an application round in allocation
    application_round = ApplicationRoundFactory.create_in_status_in_allocation()
    application_1 = ApplicationFactory.create_in_status_handled(application_round=application_round)
    application_2 = ApplicationFactory.create_in_status_handled(application_round=application_round)
    application_3 = ApplicationFactory.create_in_status_handled(application_round=application_round)

    # when:
    # - User tries to reset allocation on the application
    application_round.actions.reset_application_round_allocation()

    # then:
    # - The application is in allocation again
    application_1.refresh_from_db()
    assert application_1.status == ApplicationStatusChoice.IN_ALLOCATION
    application_2.refresh_from_db()
    assert application_2.status == ApplicationStatusChoice.IN_ALLOCATION
    application_3.refresh_from_db()
    assert application_3.status == ApplicationStatusChoice.IN_ALLOCATION


from PyQt5.QtWidgets import QWidget, QInputDialog, QFontDialog, QFileDialog
import os

class Dialogs(QWidget):
    def nameAsk(self):
        name, ok = QInputDialog.getText(self, 'Input Name',
                                        'Your name please? ')
        if ok:
            self.tedit.setText('Hello ' + str(name) +
                               '. Did you sleep well?')

    def fontDialog(self):
        font, ok = QFontDialog.getFont()
        if ok:
            self.tedit.setFont(font)

    def saveDialog(self):
        filename = QFileDialog.getSaveFileName(self, 'Save File',
                                               os.getenv('HOME'))[0]
        f = open(filename, 'w')
        tedittext = self.tedit.toPlainText()
        f.write(tedittext)
        f.close()

    def openDialog(self):
        filename = QFileDialog.getOpenFileName(self, 'Open File',
                                               os.getenv('HOME'))[0]
        self.setWindowTitle('Laze Text Editor - ' + filename)
        f = open(filename, 'ra')
        self.tedit.setText(f.read())
        f.close()


from datetime import date
hoje = date.today()
print('''{:-^50}
O formato padrão será como o exemplo: {}27/06/1991{}
{:-^50}'''.format(' CADASTRO DATA DE NASCIMENTO ', '\033[1:33m', '\033[m', ''))
totmaior = 0
totmenor = 0
for pess in range(1, 8):
    n = input('Favor digitar a {}ª data de nascimento: '.format(pess)).strip().replace('/', ' ').split()
    n = [int(n[2]), int(n[1]), int(n[0])]
    n = date(n[0], n[1], n[2])
    i = (hoje - n).days/365.25
    if i >= 18:
        totmaior += 1
    else:
        totmenor += 1
print('Ao todo tivemos {} pessoas maiores de idade.\nTambém tivemos {} pessoas menores de idade.'.format(totmaior, totmenor))

Trainning Scripts/Curso em Vídeo/Mundo 2/2 - Estrutura de Repetição FOR/ex054 - Grupo de Maioridade.py


def solution(string):
    answer = [-1]

    for idx in range(1, len(string)):
        adjacentCharIdx = string[:idx].rfind(string[idx])
        if adjacentCharIdx != -1:
            answer.append(idx - adjacentCharIdx)
        else:
            answer.append(adjacentCharIdx)
    return answer


from typing import List

import pygame

from battle.cell_types import CellTypes, cell_color_by_cell_type
from battle.sprites.cell_sprites import Cell

class Field:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.size = (20, 15)
        self.cells_group = self.create_cells()
        self.__cells: List[List[Cell]] = []
        self.fill_cells_matrix()
        self.paint_cells()

    @property
    def cells(self):
        return self.__cells

    def fill_cells_matrix(self):
        j = -1
        for i, cell in enumerate(self.cells_group.sprites()):
            if i % self.size[1] == 0:
                j += 1
                self.__cells.append([])

            self.__cells[j].append(cell)

    def create_cells(self):
        cells_group = pygame.sprite.Group()
        blockSize = 40
        for j in range(self.size[0]):
            for i in range(self.size[1]):
                cell = Cell(j * blockSize, i * blockSize, blockSize, j, i)
                cells_group.add(cell)

        return cells_group

    def fill_matrix(self, matrix):
        for i, _ in enumerate(matrix):
            for j, _ in enumerate(matrix[i]):
                self.cells[j][i].type = CellTypes(matrix[i][j])
                if CellTypes(matrix[i][j]) == CellTypes.water:
                    self.cells[j][i].image = pygame.transform.scale(pygame.image.load("battle/icons/water.png"), (40, 40))
                if CellTypes(matrix[i][j]) == CellTypes.gold:
                    self.cells[j][i].image = pygame.transform.scale(pygame.image.load("battle/icons/gold.png"), (40, 40))

    def paint_cells(self):
        for x in range(self.size[0]):
            for y in range(self.size[1]):
                self.__cells[x][y].color = cell_color_by_cell_type(self.cells[x][y].type).value


# def solution(queue1, queue2):
#     answer = -2
#     return answer

queue1 = [3, 2, 7, 2]
queue2 = [4, 6, 5, 1]
# q = queue1 + queue2
# from itertools import combinations
q = [3, 2, 7, 2, 4, 6, 5, 1]
n = len(queue1)
target = (sum(queue1) + sum(queue2))/2
answer = -1

for i in range(2*n):
    sum = 0
    for j in range(2*n-i):
        sum += q[i+j]
        if sum == target:
            print(i, j)
            if (answer > i + (i+j-n+1)) or (answer == -1):
                answer = i + (i+j-n+1)
        if sum > target:
            break
print(answer)

# for m in range(2, len(q)+1):
#     comb = list(combinations(q, m))
#     for i in range(len(comb)):
#         res = sum(comb[i])
#         if res == target:
#             print(comb[i])
#             print('ok')

# queue1 = [1, 2, 1, 2]
# queue2 = [1, 10, 1, 2]
# queue1 = [1, 1]
# queue2 = [1, 5]

# n = len(queue1)
# cnt = 0
# for _ in range(2**n):
#     if sum(queue1) > sum(queue2): # q1에서 빼서 q2에 넣기
#         print('sum1 > sum2')
#         queue2.append(queue1.pop(0))
#         cnt += 1
#         print('queue1=',queue1)
#         print('queue2=',queue2)
#         if sum(queue1) == sum(queue2):
#             break
#     if sum(queue1) < sum(queue2): # q2에서 빼서 q1에 넣기
#         print('sum2 > sum1')
#         queue1.append(queue2.pop(0))
#         cnt += 1
#         print('queue1=',queue1)
#         print('queue2=',queue2)
#         if sum(queue1) == sum(queue2):
#             break
#     # if cnt > 2**n:
#     #     print(-1)
#     #     break
# if sum(queue1) == sum(queue2):
#     print(cnt)
# else:
#     print(-1)


def findMax(s1,s2):
    max=0
    m=min(len(s1),len(s2))
    for i in range(len(s1)):
        if s1[i]==s2[0]:
            for j in range(m-i):
                if s1[i+j] != s2[j]:
                    break
            if j+1>max:
                max=j+1
    return max

start = input();
num = int(start[2])
s = input()
list=[]
for i in range(num):
    list.append(input())
for i in range(num):
    num1=int(list[i][0])
    num2=int(list[i][2])
    num3=int(list[i][4])
    num4=int(list[i][6])
    str1=s[num1:num2+1]
    str2=s[num3:num4+1]
    print(findMax(str1,str2))


# imports modules
import sys
import time
from getpass import getuser

# user puts in their name
name = getuser()
name_check = input("Is your name " + name + "? → ")
if name_check.lower().startswith("y"):
    print("Okay.")
    time.sleep(1)

if name_check.lower().startswith("n"):
    name = input("Then what is it? → ")

# Python lists their name
userList = name

# Python & user dialoge
print("Hello", name + ", my name is Python.")
time.sleep(0.8)
print("The first letter of your name is", userList[0] + ".")
time.sleep(0.8)
print("Nice to meet you. :)")
time.sleep(0.8)
response = input("Would you say it's nice to meet me? → ")

# other dialoge
if response.lower().startswith("y"):
    print("Nice :)")
    sys.exit()

elif response.lower().startswith("n"):
    response2 = input("Is it because I am a robot? → ")

else:
    print("You may have made an input error. Please restart and try again.")
    sys.exit()
if response2.lower().startswith("y"):
    print("Aw :(")

elif response2.lower().startswith("n"):
    response3 = input("Then why? → ")
    time.sleep(1)
    print("Oh.")

else:
    print("You may have made an input error. Please restart and try again.")
    sys.exit()


# Django
from django import template
from django.utils.html import format_html

# Squarelet
from squarelet.users.models import User

register = template.Library()

@register.simple_tag
def avatar(profile_or_org, size=45):
    if profile_or_org is not None:
        src = profile_or_org.avatar_url
    else:
        src = User.default_avatar
    return format_html(
        '
'
        "
",
        size=size,
        src=src,
    )